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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
67a4d8676287f3c315828cb7820aa0f6a0c32cf1 | 13,406 | cpp | C++ | print/XPSDrvSmpl/src/filters/booklet/bkflt.cpp | ixjf/Windows-driver-samples | 38985ba91feb685095754775e101389ad90c2aa6 | [
"MS-PL"
] | 3,084 | 2015-03-18T04:40:32.000Z | 2019-05-06T17:14:33.000Z | print/XPSDrvSmpl/src/filters/booklet/bkflt.cpp | ixjf/Windows-driver-samples | 38985ba91feb685095754775e101389ad90c2aa6 | [
"MS-PL"
] | 275 | 2015-03-19T18:44:41.000Z | 2019-05-06T14:13:26.000Z | print/XPSDrvSmpl/src/filters/booklet/bkflt.cpp | ixjf/Windows-driver-samples | 38985ba91feb685095754775e101389ad90c2aa6 | [
"MS-PL"
] | 3,091 | 2015-03-19T00:08:54.000Z | 2019-05-06T16:42:01.000Z | /*++
Copyright (c) 2005 Microsoft Corporation
All rights reserved.
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
File Name:
bkflt.cpp
Abstract:
Booklet filter implementation. This class derives from the Xps filter
class and implements the necessary part handlers to support booklet
printing. The booklet filter is responsible for re-ordering pages and re-uses
the NUp filter to provide 2-up and offset support.
--*/
#include "precomp.h"
#include "debug.h"
#include "globals.h"
#include "xdstring.h"
#include "xdexcept.h"
#include "pthndlr.h"
#include "bkflt.h"
#include "bksax.h"
#include "bkpthndlr.h"
using XDPrintSchema::Binding::BindingData;
/*++
Routine Name:
CBookletFilter::CBookletFilter
Routine Description:
Default constructor for the booklet filter which initialises the
filter to sensible default values
Arguments:
None
Return Value:
None
--*/
CBookletFilter::CBookletFilter() :
m_bSendAllDocs(TRUE),
m_bookScope(CBkPTProperties::None)
{
}
/*++
Routine Name:
CBookletFilter::~CBookletFilter
Routine Description:
Default destructor for the booklet filter
Arguments:
None
Return Value:
None
--*/
CBookletFilter::~CBookletFilter()
{
}
/*++
Routine Name:
CNUpFilter::ProcessPart
Routine Description:
Method for processing each fixed document sequence part in a container
Arguments:
pFDS - Pointer to the fixed document sequence to process
Return Value:
HRESULT
S_OK - On success
E_* - On error
--*/
HRESULT
CBookletFilter::ProcessPart(
_Inout_ IFixedDocumentSequence* pFDS
)
{
VERBOSE("Processing Fixed Document Sequence part with booklet filter handler\n");
HRESULT hr = S_OK;
if (SUCCEEDED(hr = CHECK_POINTER(pFDS, E_POINTER)))
{
//
// Get the PT manager to return the FixedDocumentSequence ticket.
//
IXMLDOMDocument2* pPT = NULL;
if (SUCCEEDED(hr = m_ptManager.SetTicket(pFDS)) &&
SUCCEEDED(hr = m_ptManager.GetTicket(kPTJobScope, &pPT)))
{
//
// Set the binding scope from the PrintTicket
//
hr = SetBindingScope(pPT);
}
}
if (SUCCEEDED(hr))
{
hr = m_pXDWriter->SendFixedDocumentSequence(pFDS);
}
ERR_ON_HR(hr);
return hr;
}
/*++
Routine Name:
CBookletFilter::ProcessPart
Routine Description:
Method for processing each fixed document part in a container
Arguments:
pFD - Pointer to the fixed document to process
Return Value:
HRESULT
S_OK - On success
S_FALSE - When not enabled in the PT
E_* - On error
--*/
HRESULT
CBookletFilter::ProcessPart(
_Inout_ IFixedDocument* pFD
)
{
VERBOSE("Processing Fixed Document part with booklet filter handler\n");
HRESULT hr = S_OK;
if (SUCCEEDED(hr = CHECK_POINTER(pFD, E_POINTER)) &&
SUCCEEDED(hr = m_ptManager.SetTicket(pFD)))
{
//
// If we are in a JobBook session we want to maintain the current
// JobBook settings
//
if (m_bookScope != CBkPTProperties::Job)
{
//
// Flush any outstanding pages in case we have just completed a
// DocNUp sequence
//
hr = FlushCache();
//
// Get the PT manager to return the FixedDocument ticket.
//
IXMLDOMDocument2* pPT = NULL;
if (SUCCEEDED(hr) &&
SUCCEEDED(hr = m_ptManager.GetTicket(kPTDocumentScope, &pPT)))
{
//
// Set the binding scope from the PrintTicket
//
hr = SetBindingScope(pPT);
}
}
}
if (SUCCEEDED(hr) &&
m_bSendAllDocs)
{
hr = m_pXDWriter->SendFixedDocument(pFD);
//
// If we are JobBindAllDocuments we only ever send one doc - now we have
// sent the first document we can test to see if we need to send all of them
//
if (m_bookScope == CBkPTProperties::Job)
{
m_bSendAllDocs = FALSE;
}
}
ERR_ON_HR(hr);
return hr;
}
/*++
Routine Name:
CBookletFilter::ProcessPart
Routine Description:
Method for processing each fixed page part in a container
Arguments:
pFP - Pointer to the fixed page to process
Return Value:
HRESULT
S_OK - On success
E_* - On error
--*/
HRESULT
CBookletFilter::ProcessPart(
_Inout_ IFixedPage* pFP
)
{
ASSERTMSG(m_pXDWriter != NULL, "XD writer is not initialised.\n");
VERBOSE("Processing Fixed Page with booklet filter handler\n");
HRESULT hr = S_OK;
if (SUCCEEDED(hr = CHECK_POINTER(pFP, E_POINTER)) &&
SUCCEEDED(hr = CHECK_POINTER(m_pXDWriter, E_PENDING)))
{
//
// Check if we are processing a booklet job
//
if (m_bookScope != CBkPTProperties::None)
{
//
// Cache pages for reordering
//
try
{
m_cacheFP.push_back(pFP);
}
catch (exception& DBG_ONLY(e))
{
ERR(e.what());
hr = E_FAIL;
}
}
else
{
hr = m_pXDWriter->SendFixedPage(pFP);
}
}
ERR_ON_HR(hr);
return hr;
}
/*++
Routine Name:
CBookletFilter::Finalize
Routine Description:
Method to flush the cache of pages as the last action of the filter
Arguments:
None
Return Value:
HRESULT
S_OK - On success
E_* - On error
--*/
HRESULT
CBookletFilter::Finalize(
VOID
)
{
//
// Just flush the cache of pages
//
return FlushCache();
}
/*++
Routine Name:
CBookletFilter::FlushCache
Routine Description:
Method to send the cached collection of pages in the correct order back
Arguments:
None
Return Value:
HRESULT
S_OK - On success
E_* - On error
--*/
HRESULT
CBookletFilter::FlushCache(
VOID
)
{
HRESULT hr = S_OK;
if (m_pXDWriter == NULL)
{
hr = E_PENDING;
}
size_t cPages = m_cacheFP.size();
if (SUCCEEDED(hr) &&
cPages > 0 &&
m_bookScope != CBkPTProperties::None)
{
//
// We may need to add a pad page if the page count is odd
//
CComPtr<IFixedPage> pNewFP(NULL);
if (cPages%2 == 1 &&
SUCCEEDED(hr = CreatePadPage(&pNewFP)))
{
//
// We successfully created our pad page; add it to the cache
//
try
{
m_cacheFP.push_back(pNewFP);
}
catch (exception& DBG_ONLY(e))
{
ERR(e.what());
hr = E_FAIL;
}
cPages++;
}
if (SUCCEEDED(hr))
{
try
{
//
// Re-order pages in the cache
//
map<size_t, IFixedPage*> reorderedPages;
size_t newIndex = 0;
size_t pageIndex = 0;
for (pageIndex = 0; pageIndex < cPages/2; pageIndex++)
{
reorderedPages[newIndex] = m_cacheFP[pageIndex];
newIndex += 2;
}
newIndex = cPages - 1;
for (pageIndex = cPages/2; pageIndex < cPages; pageIndex++)
{
reorderedPages[newIndex] = m_cacheFP[pageIndex];
newIndex -= 2;
}
//
// Write out reordered pages
//
for (pageIndex = 0; pageIndex < cPages && SUCCEEDED(hr); pageIndex++)
{
hr = m_pXDWriter->SendFixedPage(reorderedPages[pageIndex]);
}
//
// Clean out the cache
//
m_cacheFP.clear();
}
catch (exception& DBG_ONLY(e))
{
ERR(e.what());
hr = E_FAIL;
}
}
}
ERR_ON_HR(hr);
return hr;
}
/*++
Routine Name:
CBookletFilter::CreatePadPage
Routine Description:
Method to create a pad page which is required for odd page counts to
ensure pages are correctly ordered for presentation as a booklet
Arguments:
ppNewPage - Pointer to a pointer to the newly created fixed page
Return Value:
HRESULT
S_OK - On success
E_* - On error
--*/
HRESULT
CBookletFilter::CreatePadPage(
_Outptr_ IFixedPage** ppNewPage
)
{
HRESULT hr = S_OK;
//
// Validate parameters and members before proceeding
//
if (SUCCEEDED(hr = CHECK_POINTER(ppNewPage, E_POINTER)) &&
SUCCEEDED(hr = CHECK_POINTER(m_pXDWriter, E_PENDING)))
{
*ppNewPage = NULL;
PCWSTR pszPageName = NULL;
try
{
//
// Create a unique name for the pad page for this print session
//
CStringXDW szNewPageName;
szNewPageName.Format(L"/Pad_page_%u.xaml", GetUniqueNumber());
pszPageName = szNewPageName.GetBuffer();
//
// Create a new empty page and retrieve a writer. Also get a
// reader from the first page so we can copy the FixedPage root
// element. This ensures the page sizes match.
//
CComPtr<IPrintWriteStream> pWriter(NULL);
CComPtr<ISAXXMLReader> pSaxRdr(NULL);
if (SUCCEEDED(hr) &&
SUCCEEDED(hr = m_pXDWriter->GetNewEmptyPart(pszPageName,
IID_IFixedPage,
reinterpret_cast<PVOID*>(ppNewPage),
&pWriter)) &&
SUCCEEDED(hr = pSaxRdr.CoCreateInstance(CLSID_SAXXMLReader60)))
{
//
// We use a simple SAX handler which copies only the root
// element and discards all other content.
//
CBkSaxHandler bkSaxHndlr(pWriter);
CComPtr<IPrintReadStream> pReader(NULL);
IFixedPage* pFP = NULL;
pFP = m_cacheFP[0];
if (SUCCEEDED(hr) &&
SUCCEEDED(hr = pSaxRdr->putContentHandler(&bkSaxHndlr)) &&
SUCCEEDED(hr = pFP->GetStream(&pReader)))
{
CComPtr<ISequentialStream> pReadStreamToSeq(NULL);
pReadStreamToSeq.Attach(new(std::nothrow) pfp::PrintReadStreamToSeqStream(pReader));
if (SUCCEEDED(hr = CHECK_POINTER(pReadStreamToSeq, E_OUTOFMEMORY)))
{
hr = pSaxRdr->parse(CComVariant(static_cast<ISequentialStream*>(pReadStreamToSeq)));
}
}
pWriter->Close();
}
}
catch (CXDException& e)
{
hr = e;
}
}
ERR_ON_HR(hr);
return hr;
}
/*++
Routine Name:
CBookletFilter::SetBindingScope
Routine Description:
Method to retrieve the binding scope from a PrintTicket
Arguments:
pPT - Pointer to the PrintTicket to retrieve the scope from
Return Value:
HRESULT
S_OK - On success
S_FALSE - Booklet settings not present in the PT
E_* - On error
--*/
HRESULT
CBookletFilter::SetBindingScope(
_In_ IXMLDOMDocument2* pPT
)
{
HRESULT hr = S_OK;
if (SUCCEEDED(hr = CHECK_POINTER(pPT, E_POINTER)))
{
try
{
BindingData bindingData;
CBookPTHandler bkPTHandler(pPT);
//
// Retrieve the booklet properties from the ticket via the handler
//
if (SUCCEEDED(hr) &&
SUCCEEDED(hr = bkPTHandler.GetData(&bindingData)))
{
CBkPTProperties bookletPTProps(bindingData);
//
// Retrieve the booklet scope
//
hr = bookletPTProps.GetScope(&m_bookScope);
}
else if (hr == E_ELEMENT_NOT_FOUND)
{
//
// Booklet PT settings are not present - reset hr to S_FALSE and proceed
//
hr = S_FALSE;
}
}
catch (CXDException& e)
{
hr = e;
}
}
return hr;
}
| 22.64527 | 109 | 0.518425 | ixjf |
67a4fa120a52db19fe68dd92cc03e67e9f09811b | 9,495 | cc | C++ | src/ArtificialViscosity/TensorCRKSPHViscosity.cc | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 22 | 2018-07-31T21:38:22.000Z | 2020-06-29T08:58:33.000Z | src/ArtificialViscosity/TensorCRKSPHViscosity.cc | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 41 | 2020-09-28T23:14:27.000Z | 2022-03-28T17:01:33.000Z | src/ArtificialViscosity/TensorCRKSPHViscosity.cc | jmikeowen/Spheral | 3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4 | [
"BSD-Source-Code",
"BSD-3-Clause-LBNL",
"FSFAP"
] | 7 | 2019-12-01T07:00:06.000Z | 2020-09-15T21:12:39.000Z | //---------------------------------Spheral++----------------------------------//
// ArtificialViscosity -- The base class for all ArtificialViscosities in
// Spheral++.
//----------------------------------------------------------------------------//
#include "FileIO/FileIO.hh"
#include "Hydro/HydroFieldNames.hh"
#include "Boundary/Boundary.hh"
#include "Kernel/TableKernel.hh"
#include "NodeList/FluidNodeList.hh"
#include "DataBase/State.hh"
#include "DataBase/StateDerivatives.hh"
#include "Neighbor/ConnectivityMap.hh"
#include "Utilities/rotationMatrix.hh"
#include "Utilities/GeometricUtilities.hh"
#include "RK/RKFieldNames.hh"
#include "RK/gradientRK.hh"
#include "TensorCRKSPHViscosity.hh"
#include <algorithm>
using std::vector;
using std::string;
using std::pair;
using std::make_pair;
using std::cout;
using std::cerr;
using std::endl;
using std::min;
using std::max;
using std::abs;
namespace Spheral {
//------------------------------------------------------------------------------
// Construct with the given value for the linear and quadratic coefficients.
//------------------------------------------------------------------------------
template<typename Dimension>
TensorCRKSPHViscosity<Dimension>::
TensorCRKSPHViscosity(Scalar Clinear, Scalar Cquadratic):
TensorMonaghanGingoldViscosity<Dimension>(Clinear, Cquadratic),
mGradVel(FieldStorageType::CopyFields){
}
//------------------------------------------------------------------------------
// Destructor.
//------------------------------------------------------------------------------
template<typename Dimension>
TensorCRKSPHViscosity<Dimension>::
~TensorCRKSPHViscosity() {
}
//------------------------------------------------------------------------------
// Method to apply the viscous acceleration, work, and pressure, to the derivatives
// all in one step (efficiency and all).
//------------------------------------------------------------------------------
template<typename Dimension>
pair<typename Dimension::Tensor,
typename Dimension::Tensor>
TensorCRKSPHViscosity<Dimension>::
Piij(const unsigned nodeListi, const unsigned i,
const unsigned nodeListj, const unsigned j,
const Vector& xi,
const Vector& etai,
const Vector& vi,
const Scalar rhoi,
const Scalar csi,
const SymTensor& /*Hi*/,
const Vector& xj,
const Vector& etaj,
const Vector& vj,
const Scalar rhoj,
const Scalar csj,
const SymTensor& /*Hj*/) const {
// Estimate the velocity difference.
Vector vij = vi - vj;
const Vector xij = xi - xj;
const Tensor& DvDxi = mGradVel(nodeListi, i);
const Tensor& DvDxj = mGradVel(nodeListj, j);
const Vector vi1 = vi - 0.5*(DvDxi.dot(xij));
const Vector vj1 = vj + 0.5*(DvDxj.dot(xij));
const Vector vij1 = vi1 - vj1;
if (((vi1 - vj).dot(vij) > 0.0) and
((vi - vj1).dot(vij) > 0.0) and
(vij1.dot(vij) > 0.0)) {
const Vector vijhat = vij.unitVector();
// const bool barf = (vij.magnitude() > 1.0e-5);
// if (barf) cerr << "Cutting vij from " << vij << " to ";
vij = min(vij.magnitude(), vij1.magnitude())*vijhat;
// if (barf) cerr << vij << endl;
}
// If the nodes are not closing, then skip the rest and the Q is zero.
if (vij.dot(xij) < 0.0) {
const double tiny = 1.0e-20;
double Cl = this->mClinear;
double Cq = this->mCquadratic;
const double eps2 = this->mEpsilon2;
//const bool balsara = this->mBalsaraShearCorrection;
const bool limiter = this->mLimiterSwitch;
// Grab the FieldLists scaling the coefficients.
// These incorporate things like the Balsara shearing switch or Morris & Monaghan time evolved
// coefficients.
const Scalar fCli = this->mClMultiplier(nodeListi, i);
const Scalar fCqi = this->mCqMultiplier(nodeListi, i);
const Scalar fClj = this->mClMultiplier(nodeListj, j);
const Scalar fCqj = this->mCqMultiplier(nodeListj, j);
const Scalar fshear = std::max(this->mShearCorrection(nodeListi, i), this->mShearCorrection(nodeListj, j));
Cl *= 0.5*(fCli + fClj)*fshear;
Cq *= 0.5*(fCqi + fCqj)*fshear;
// Some more geometry.
const Scalar xij2 = xij.magnitude2();
const Vector xijUnit = xij.unitVector();
const Scalar hi2 = xij2/(etai.magnitude2() + tiny);
const Scalar hj2 = xij2/(etaj.magnitude2() + tiny);
const Scalar hi = sqrt(hi2);
const Scalar hj = sqrt(hj2);
// BOOGA!
const Tensor& _sigmai = this->mSigma(nodeListi, i);
const Tensor& _sigmaj = this->mSigma(nodeListj, j);
Tensor sigmai = _sigmai;
Tensor sigmaj = _sigmaj;
{
const Tensor R = rotationMatrix(xijUnit);
const Tensor Rinverse = R.Transpose();
const Vector thpt1 = sqrt(xij2)*(R*vij);
const Vector deltaSigmai = thpt1/(xij2 + eps2*hi2);
const Vector deltaSigmaj = thpt1/(xij2 + eps2*hj2);
sigmai.rotationalTransform(R);
sigmaj.rotationalTransform(R);
sigmai.setColumn(0, deltaSigmai);
sigmaj.setColumn(0, deltaSigmaj);
sigmai.rotationalTransform(Rinverse);
sigmaj.rotationalTransform(Rinverse);
}
// BOOGA!
// Calculate the tensor viscous internal energy.
const Tensor mui = hi*sigmai;
Tensor Qepsi = -Cl*csi*mui.Transpose() + Cq*mui*mui;
if (limiter) Qepsi = this->calculateLimiter(vi, vj, csi, csj, hi, hj, nodeListi, i)*Qepsi;
const Tensor muj = hj*sigmaj;
Tensor Qepsj = -Cl*csj*muj.Transpose() + Cq*muj*muj;
if (limiter) Qepsj = this->calculateLimiter(vj, vi, csj, csi, hj, hi, nodeListj, j)*Qepsj;
// We now have enough to compute Pi!
const Tensor QPii = Qepsi/rhoi;
const Tensor QPij = Qepsj/rhoj;
return make_pair(QPii, QPij);
} else {
return make_pair(Tensor::zero, Tensor::zero);
}
}
//------------------------------------------------------------------------------
// Compute the internal background sigma and grad-div-v fields.
//------------------------------------------------------------------------------
template<typename Dimension>
void
TensorCRKSPHViscosity<Dimension>::
calculateSigmaAndGradDivV(const DataBase<Dimension>& dataBase,
const State<Dimension>& state,
const StateDerivatives<Dimension>& /*derivs*/,
const TableKernel<Dimension>& /*W*/,
typename TensorCRKSPHViscosity<Dimension>::ConstBoundaryIterator boundaryBegin,
typename TensorCRKSPHViscosity<Dimension>::ConstBoundaryIterator boundaryEnd) {
const auto order = ArtificialViscosity<Dimension>::QcorrectionOrder();
auto& sigma = ArtificialViscosity<Dimension>::mSigma;
auto& gradDivVelocity = ArtificialViscosity<Dimension>::mGradDivVelocity;
// Get the necessary state.
const auto mass = state.fields(HydroFieldNames::mass, 0.0);
const auto position = state.fields(HydroFieldNames::position, Vector::zero);
const auto velocity = state.fields(HydroFieldNames::velocity, Vector::zero);
const auto rho = state.fields(HydroFieldNames::massDensity, 0.0);
const auto H = state.fields(HydroFieldNames::H, SymTensor::zero);
const auto WR = state.template getAny<ReproducingKernel<Dimension>>(RKFieldNames::reproducingKernel(order));
const auto corrections = state.fields(RKFieldNames::rkCorrections(order), RKCoefficients<Dimension>());
const auto& connectivityMap = dataBase.connectivityMap();
const auto numNodeLists = dataBase.numFluidNodeLists();
// Compute the basic velocity gradient.
const auto vol = mass/rho;
mGradVel = gradientRK(velocity, position, vol, H, connectivityMap, WR, corrections, NodeCoupling());
sigma = mGradVel;
sigma.copyFields();
// Compute sigma and build the velocity divergence.
auto divVel = dataBase.newFluidFieldList(0.0, "velocity divergence");
for (auto nodeListi = 0u; nodeListi != numNodeLists; ++nodeListi) {
for (auto iItr = connectivityMap.begin(nodeListi); iItr < connectivityMap.end(nodeListi); ++iItr) {
const auto i = *iItr;
auto& sigmai = sigma(nodeListi, i);
// Update the velocity divergence.
divVel(nodeListi, i) = sigmai.Trace();
// Now limit to just negative eigen-values. This is 'cause we only
// care about convergent geometries for the Q.
const auto sigmai_s = sigmai.Symmetric();
const auto sigmai_a = sigmai.SkewSymmetric();
auto eigeni = sigmai_s.eigenVectors();
sigmai = constructTensorWithMinDiagonal(eigeni.eigenValues, 0.0);
sigmai.rotationalTransform(eigeni.eigenVectors);
// sigmai += sigmai_a;
}
}
// Apply boundary conditions.
for (auto boundItr = boundaryBegin; boundItr < boundaryEnd; ++boundItr) (*boundItr)->applyFieldListGhostBoundary(divVel);
for (auto boundItr = boundaryBegin; boundItr < boundaryEnd; ++boundItr) (*boundItr)->finalizeGhostBoundary();
// Compute the gradient of div vel.
gradDivVelocity = gradientRK(divVel, position, vol, H, connectivityMap, WR, corrections, NodeCoupling());
// Apply boundary conditions.
for (auto boundItr = boundaryBegin; boundItr < boundaryEnd; ++boundItr) {
(*boundItr)->applyFieldListGhostBoundary(sigma);
(*boundItr)->applyFieldListGhostBoundary(gradDivVelocity);
(*boundItr)->applyFieldListGhostBoundary(mGradVel);
}
// for (typename ArtificialViscosity<Dimension>::ConstBoundaryIterator boundItr = boundaryBegin;
// boundItr != boundaryEnd;
// ++boundItr) {
// (*boundItr)->finalizeGhostBoundary();
// }
}
}
| 39.39834 | 123 | 0.635071 | jmikeowen |
67a57f1e230da950109c4536ffd684d3ca0ea070 | 13,732 | cpp | C++ | modules/gles2/functional/es2fTextureSizeTests.cpp | billkris-ms/VK-GL-CTS | fbd32b9e48d981580e40c6e4b54d30ddb4980867 | [
"Apache-2.0"
] | 1 | 2017-09-20T12:24:13.000Z | 2017-09-20T12:24:13.000Z | modules/gles2/functional/es2fTextureSizeTests.cpp | billkris-ms/VK-GL-CTS | fbd32b9e48d981580e40c6e4b54d30ddb4980867 | [
"Apache-2.0"
] | null | null | null | modules/gles2/functional/es2fTextureSizeTests.cpp | billkris-ms/VK-GL-CTS | fbd32b9e48d981580e40c6e4b54d30ddb4980867 | [
"Apache-2.0"
] | null | null | null | /*-------------------------------------------------------------------------
* drawElements Quality Program OpenGL ES 2.0 Module
* -------------------------------------------------
*
* Copyright 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Texture size tests.
*//*--------------------------------------------------------------------*/
#include "es2fTextureSizeTests.hpp"
#include "glsTextureTestUtil.hpp"
#include "gluTexture.hpp"
#include "gluStrUtil.hpp"
#include "gluTextureUtil.hpp"
#include "gluPixelTransfer.hpp"
#include "tcuTestLog.hpp"
#include "tcuTextureUtil.hpp"
#include "glwEnums.hpp"
#include "glwFunctions.hpp"
namespace deqp
{
namespace gles2
{
namespace Functional
{
using tcu::TestLog;
using std::vector;
using std::string;
using tcu::Sampler;
using namespace glu;
using namespace gls::TextureTestUtil;
using namespace glu::TextureTestUtil;
class Texture2DSizeCase : public tcu::TestCase
{
public:
Texture2DSizeCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const char* name, const char* description, deUint32 format, deUint32 dataType, int width, int height, bool mipmaps);
~Texture2DSizeCase (void);
void init (void);
void deinit (void);
IterateResult iterate (void);
private:
Texture2DSizeCase (const Texture2DSizeCase& other);
Texture2DSizeCase& operator= (const Texture2DSizeCase& other);
glu::RenderContext& m_renderCtx;
deUint32 m_format;
deUint32 m_dataType;
int m_width;
int m_height;
bool m_useMipmaps;
glu::Texture2D* m_texture;
TextureRenderer m_renderer;
};
Texture2DSizeCase::Texture2DSizeCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const char* name, const char* description, deUint32 format, deUint32 dataType, int width, int height, bool mipmaps)
: TestCase (testCtx, name, description)
, m_renderCtx (renderCtx)
, m_format (format)
, m_dataType (dataType)
, m_width (width)
, m_height (height)
, m_useMipmaps (mipmaps)
, m_texture (DE_NULL)
, m_renderer (renderCtx, testCtx.getLog(), glu::GLSL_VERSION_100_ES, glu::PRECISION_MEDIUMP)
{
}
Texture2DSizeCase::~Texture2DSizeCase (void)
{
Texture2DSizeCase::deinit();
}
void Texture2DSizeCase::init (void)
{
DE_ASSERT(!m_texture);
m_texture = new Texture2D(m_renderCtx, m_format, m_dataType, m_width, m_height);
int numLevels = m_useMipmaps ? deLog2Floor32(de::max(m_width, m_height))+1 : 1;
// Fill levels.
for (int levelNdx = 0; levelNdx < numLevels; levelNdx++)
{
m_texture->getRefTexture().allocLevel(levelNdx);
tcu::fillWithComponentGradients(m_texture->getRefTexture().getLevel(levelNdx), tcu::Vec4(-1.0f, -1.0f, -1.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f));
}
}
void Texture2DSizeCase::deinit (void)
{
delete m_texture;
m_texture = DE_NULL;
m_renderer.clear();
}
Texture2DSizeCase::IterateResult Texture2DSizeCase::iterate (void)
{
const glw::Functions& gl = m_renderCtx.getFunctions();
TestLog& log = m_testCtx.getLog();
RandomViewport viewport (m_renderCtx.getRenderTarget(), 128, 128, deStringHash(getName()));
tcu::Surface renderedFrame (viewport.width, viewport.height);
tcu::Surface referenceFrame (viewport.width, viewport.height);
tcu::RGBA threshold = m_renderCtx.getRenderTarget().getPixelFormat().getColorThreshold() + tcu::RGBA(7,7,7,7);
deUint32 wrapS = GL_CLAMP_TO_EDGE;
deUint32 wrapT = GL_CLAMP_TO_EDGE;
// Do not minify with GL_NEAREST. A large POT texture with a small POT render target will produce
// indeterminate results.
deUint32 minFilter = m_useMipmaps ? GL_NEAREST_MIPMAP_NEAREST : GL_LINEAR;
deUint32 magFilter = GL_NEAREST;
vector<float> texCoord;
computeQuadTexCoord2D(texCoord, tcu::Vec2(0.0f, 0.0f), tcu::Vec2(1.0f, 1.0f));
// Setup base viewport.
gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
// Upload texture data to GL.
m_texture->upload();
// Bind to unit 0.
gl.activeTexture(GL_TEXTURE0);
gl.bindTexture(GL_TEXTURE_2D, m_texture->getGLTexture());
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
gl.texParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
GLU_EXPECT_NO_ERROR(gl.getError(), "Set texturing state");
// Draw.
m_renderer.renderQuad(0, &texCoord[0], TEXTURETYPE_2D);
glu::readPixels(m_renderCtx, viewport.x, viewport.y, renderedFrame.getAccess());
// Compute reference.
sampleTexture(tcu::SurfaceAccess(referenceFrame, m_renderCtx.getRenderTarget().getPixelFormat()), m_texture->getRefTexture(), &texCoord[0], ReferenceParams(TEXTURETYPE_2D, mapGLSampler(wrapS, wrapT, minFilter, magFilter)));
// Compare and log.
bool isOk = compareImages(log, referenceFrame, renderedFrame, threshold);
m_testCtx.setTestResult(isOk ? QP_TEST_RESULT_PASS : QP_TEST_RESULT_FAIL,
isOk ? "Pass" : "Image comparison failed");
return STOP;
}
class TextureCubeSizeCase : public tcu::TestCase
{
public:
TextureCubeSizeCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const char* name, const char* description, deUint32 format, deUint32 dataType, int width, int height, bool mipmaps);
~TextureCubeSizeCase (void);
void init (void);
void deinit (void);
IterateResult iterate (void);
private:
TextureCubeSizeCase (const TextureCubeSizeCase& other);
TextureCubeSizeCase& operator= (const TextureCubeSizeCase& other);
bool testFace (tcu::CubeFace face);
glu::RenderContext& m_renderCtx;
deUint32 m_format;
deUint32 m_dataType;
int m_width;
int m_height;
bool m_useMipmaps;
glu::TextureCube* m_texture;
TextureRenderer m_renderer;
int m_curFace;
bool m_isOk;
};
TextureCubeSizeCase::TextureCubeSizeCase (tcu::TestContext& testCtx, glu::RenderContext& renderCtx, const char* name, const char* description, deUint32 format, deUint32 dataType, int width, int height, bool mipmaps)
: TestCase (testCtx, name, description)
, m_renderCtx (renderCtx)
, m_format (format)
, m_dataType (dataType)
, m_width (width)
, m_height (height)
, m_useMipmaps (mipmaps)
, m_texture (DE_NULL)
, m_renderer (renderCtx, testCtx.getLog(), glu::GLSL_VERSION_100_ES, glu::PRECISION_MEDIUMP)
, m_curFace (0)
, m_isOk (false)
{
}
TextureCubeSizeCase::~TextureCubeSizeCase (void)
{
TextureCubeSizeCase::deinit();
}
void TextureCubeSizeCase::init (void)
{
DE_ASSERT(!m_texture);
DE_ASSERT(m_width == m_height);
m_texture = new TextureCube(m_renderCtx, m_format, m_dataType, m_width);
static const tcu::Vec4 gradients[tcu::CUBEFACE_LAST][2] =
{
{ tcu::Vec4(-1.0f, -1.0f, -1.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // negative x
{ tcu::Vec4( 0.0f, -1.0f, -1.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // positive x
{ tcu::Vec4(-1.0f, 0.0f, -1.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // negative y
{ tcu::Vec4(-1.0f, -1.0f, 0.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) }, // positive y
{ tcu::Vec4(-1.0f, -1.0f, -1.0f, 0.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 1.0f) }, // negative z
{ tcu::Vec4( 0.0f, 0.0f, 0.0f, 2.0f), tcu::Vec4(1.0f, 1.0f, 1.0f, 0.0f) } // positive z
};
int numLevels = m_useMipmaps ? deLog2Floor32(de::max(m_width, m_height))+1 : 1;
// Fill levels.
for (int levelNdx = 0; levelNdx < numLevels; levelNdx++)
{
for (int face = 0; face < tcu::CUBEFACE_LAST; face++)
{
m_texture->getRefTexture().allocLevel((tcu::CubeFace)face, levelNdx);
fillWithComponentGradients(m_texture->getRefTexture().getLevelFace(levelNdx, (tcu::CubeFace)face), gradients[face][0], gradients[face][1]);
}
}
// Upload texture data to GL.
m_texture->upload();
// Initialize iteration state.
m_curFace = 0;
m_isOk = true;
}
void TextureCubeSizeCase::deinit (void)
{
delete m_texture;
m_texture = DE_NULL;
m_renderer.clear();
}
bool TextureCubeSizeCase::testFace (tcu::CubeFace face)
{
const glw::Functions& gl = m_renderCtx.getFunctions();
TestLog& log = m_testCtx.getLog();
RandomViewport viewport (m_renderCtx.getRenderTarget(), 128, 128, deStringHash(getName())+(deUint32)face);
tcu::Surface renderedFrame (viewport.width, viewport.height);
tcu::Surface referenceFrame (viewport.width, viewport.height);
tcu::RGBA threshold = m_renderCtx.getRenderTarget().getPixelFormat().getColorThreshold() + tcu::RGBA(7,7,7,7);
deUint32 wrapS = GL_CLAMP_TO_EDGE;
deUint32 wrapT = GL_CLAMP_TO_EDGE;
// Do not minify with GL_NEAREST. A large POT texture with a small POT render target will produce
// indeterminate results.
deUint32 minFilter = m_useMipmaps ? GL_NEAREST_MIPMAP_NEAREST : GL_LINEAR;
deUint32 magFilter = GL_NEAREST;
vector<float> texCoord;
computeQuadTexCoordCube(texCoord, face);
// \todo [2011-10-28 pyry] Image set name / section?
log << TestLog::Message << face << TestLog::EndMessage;
// Setup base viewport.
gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
// Bind to unit 0.
gl.activeTexture(GL_TEXTURE0);
gl.bindTexture(GL_TEXTURE_CUBE_MAP, m_texture->getGLTexture());
gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, wrapS);
gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, wrapT);
gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, minFilter);
gl.texParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, magFilter);
GLU_EXPECT_NO_ERROR(gl.getError(), "Set texturing state");
m_renderer.renderQuad(0, &texCoord[0], TEXTURETYPE_CUBE);
glu::readPixels(m_renderCtx, viewport.x, viewport.y, renderedFrame.getAccess());
// Compute reference.
Sampler sampler = mapGLSampler(wrapS, wrapT, minFilter, magFilter);
sampler.seamlessCubeMap = false;
sampleTexture(tcu::SurfaceAccess(referenceFrame, m_renderCtx.getRenderTarget().getPixelFormat()), m_texture->getRefTexture(), &texCoord[0], ReferenceParams(TEXTURETYPE_CUBE, sampler));
// Compare and log.
return compareImages(log, referenceFrame, renderedFrame, threshold);
}
TextureCubeSizeCase::IterateResult TextureCubeSizeCase::iterate (void)
{
// Execute test for all faces.
if (!testFace((tcu::CubeFace)m_curFace))
m_isOk = false;
m_curFace += 1;
if (m_curFace == tcu::CUBEFACE_LAST)
{
m_testCtx.setTestResult(m_isOk ? QP_TEST_RESULT_PASS : QP_TEST_RESULT_FAIL,
m_isOk ? "Pass" : "Image comparison failed");
return STOP;
}
else
return CONTINUE;
}
TextureSizeTests::TextureSizeTests (Context& context)
: TestCaseGroup(context, "size", "Texture Size Tests")
{
}
TextureSizeTests::~TextureSizeTests (void)
{
}
void TextureSizeTests::init (void)
{
struct
{
int width;
int height;
} sizes2D[] =
{
{ 64, 64 }, // Spec-mandated minimum.
{ 65, 63 },
{ 512, 512 },
{ 1024, 1024 },
{ 2048, 2048 }
};
struct
{
int width;
int height;
} sizesCube[] =
{
{ 15, 15 },
{ 16, 16 }, // Spec-mandated minimum
{ 64, 64 },
{ 128, 128 },
{ 256, 256 },
{ 512, 512 }
};
struct
{
const char* name;
deUint32 format;
deUint32 dataType;
} formats[] =
{
{ "l8", GL_LUMINANCE, GL_UNSIGNED_BYTE },
{ "rgba4444", GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 },
{ "rgb888", GL_RGB, GL_UNSIGNED_BYTE },
{ "rgba8888", GL_RGBA, GL_UNSIGNED_BYTE }
};
// 2D cases.
tcu::TestCaseGroup* group2D = new tcu::TestCaseGroup(m_testCtx, "2d", "2D Texture Size Tests");
addChild(group2D);
for (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizes2D); sizeNdx++)
{
int width = sizes2D[sizeNdx].width;
int height = sizes2D[sizeNdx].height;
bool isPOT = deIsPowerOfTwo32(width) && deIsPowerOfTwo32(height);
for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(formats); formatNdx++)
{
for (int mipmap = 0; mipmap < (isPOT ? 2 : 1); mipmap++)
{
std::ostringstream name;
name << width << "x" << height << "_" << formats[formatNdx].name << (mipmap ? "_mipmap" : "");
group2D->addChild(new Texture2DSizeCase(m_testCtx, m_context.getRenderContext(), name.str().c_str(), "",
formats[formatNdx].format, formats[formatNdx].dataType,
width, height, mipmap != 0));
}
}
}
// Cubemap cases.
tcu::TestCaseGroup* groupCube = new tcu::TestCaseGroup(m_testCtx, "cube", "Cubemap Texture Size Tests");
addChild(groupCube);
for (int sizeNdx = 0; sizeNdx < DE_LENGTH_OF_ARRAY(sizesCube); sizeNdx++)
{
int width = sizesCube[sizeNdx].width;
int height = sizesCube[sizeNdx].height;
bool isPOT = deIsPowerOfTwo32(width) && deIsPowerOfTwo32(height);
for (int formatNdx = 0; formatNdx < DE_LENGTH_OF_ARRAY(formats); formatNdx++)
{
for (int mipmap = 0; mipmap < (isPOT ? 2 : 1); mipmap++)
{
std::ostringstream name;
name << width << "x" << height << "_" << formats[formatNdx].name << (mipmap ? "_mipmap" : "");
groupCube->addChild(new TextureCubeSizeCase(m_testCtx, m_context.getRenderContext(), name.str().c_str(), "",
formats[formatNdx].format, formats[formatNdx].dataType,
width, height, mipmap != 0));
}
}
}
}
} // Functional
} // gles2
} // deqp
| 32.084112 | 224 | 0.696257 | billkris-ms |
67a7ddb373e541a806d5fe3435dd83853e771c82 | 122 | cpp | C++ | doc/TRUST/exercices/equation_convection_diffusion/src/Ref_Constituant_Avec_Vitesse.cpp | cea-trust-platform/trust-code | c4f42d8f8602a8cc5e0ead0e29dbf0be8ac52f72 | [
"BSD-3-Clause"
] | 12 | 2021-06-30T18:50:38.000Z | 2022-03-23T09:03:16.000Z | doc/TRUST/exercices/equation_convection_diffusion/src/Ref_Constituant_Avec_Vitesse.cpp | pledac/trust-code | 46ab5c5da3f674185f53423090f526a38ecdbad1 | [
"BSD-3-Clause"
] | null | null | null | doc/TRUST/exercices/equation_convection_diffusion/src/Ref_Constituant_Avec_Vitesse.cpp | pledac/trust-code | 46ab5c5da3f674185f53423090f526a38ecdbad1 | [
"BSD-3-Clause"
] | 2 | 2021-10-04T09:19:39.000Z | 2021-12-15T14:21:04.000Z | #include <Ref_Constituant_Avec_Vitesse.h>
#include <Constituant_Avec_Vitesse.h>
Implemente_ref(Constituant_Avec_Vitesse);
| 30.5 | 41 | 0.868852 | cea-trust-platform |
67aa285653f4260035aaf5f8727e431a230c3307 | 6,575 | cpp | C++ | 3rdparty/GPSTk/core/tests/FileHandling/Binex_Attrs_T.cpp | mfkiwl/ICE | e660d031bb1bcea664db1de4946fd8781be5b627 | [
"MIT"
] | 50 | 2019-10-12T01:22:20.000Z | 2022-02-15T23:28:26.000Z | 3rdparty/GPSTk/core/tests/FileHandling/Binex_Attrs_T.cpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | null | null | null | 3rdparty/GPSTk/core/tests/FileHandling/Binex_Attrs_T.cpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | 14 | 2019-11-05T01:50:29.000Z | 2021-08-06T06:23:44.000Z | //============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk 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.0 of the License, or
// any later version.
//
// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
#include "BinexData.hpp"
#include "TestUtil.hpp"
using namespace std;
using namespace gpstk;
//=============================================================================
// Class declarations
//=============================================================================
class BinexAttrs_T
{
public:
// constructor
BinexAttrs_T() : verboseLevel(0)
{
init();
};
// destructor
virtual ~BinexAttrs_T() {};
// initialize tests
void init();
// test methods
// @return number of failures, i.e., 0=PASS, !0=FAIL
int doIsDataTests();
int doRecordFlagsTests();
int doRecordIdTests();
int doMessageCapacityTests();
int doMessageLengthTests();
unsigned verboseLevel; // amount to display during tests, 0 = least
}; // class BinexAttrs_T
//============================================================
// Initialize Test Data Filenames and Values
//============================================================
void BinexAttrs_T :: init( void )
{
// empty
}
int BinexAttrs_T :: doIsDataTests()
{
TUDEF("BinexData", "isData");
BinexData rec;
TUASSERT(rec.isData());
TURETURN();
}
int BinexAttrs_T :: doRecordFlagsTests()
{
TUDEF("BinexData", "getRecordFlags");
BinexData rec;
TUASSERTE(BinexData::SyncByte, BinexData::DEFAULT_RECORD_FLAGS, rec.getRecordFlags());
TUCSM("setRecordFlags");
rec.setRecordFlags(0);
TUASSERTE(BinexData::SyncByte, 0, rec.getRecordFlags());
rec.setRecordFlags(0xFF);
TUASSERTE(BinexData::SyncByte, BinexData::VALID_RECORD_FLAGS, rec.getRecordFlags());
TURETURN();
}
int BinexAttrs_T :: doRecordIdTests()
{
TUDEF("BinexData", "getRecordID");
BinexData recA;
TUASSERTE(BinexData::RecordID, BinexData::INVALID_RECORD_ID, recA.getRecordID());
BinexData recB(123);
TUASSERTE(BinexData::RecordID, 123, recB.getRecordID());
TUCSM("setRecordID");
recB.setRecordID(456);
TUASSERTE(BinexData::RecordID, 456, recB.getRecordID());
TURETURN();
}
int BinexAttrs_T :: doMessageLengthTests()
{
TUDEF("BinexData", "getMessageLength");
BinexData rec(1); // a record id is required
TUASSERTE(size_t, 0, rec.getMessageLength());
TUCSM("getHeadLength");
TUASSERTE(size_t, 3, rec.getHeadLength());
TUCSM("getTailLength");
TUASSERTE(size_t, 1, rec.getTailLength());
TUCSM("getRecordSize");
TUASSERTE(size_t, 4, rec.getRecordSize());
std::string s("1");
size_t offset = 0;
rec.updateMessageData(offset, s, s.size());
TUCSM("getMessageLength");
TUASSERTE(size_t, 1, rec.getMessageLength());
TUCSM("getHeadLength");
TUASSERTE(size_t, 3, rec.getHeadLength());
TUCSM("getTailLength");
TUASSERTE(size_t, 1, rec.getTailLength());
TUCSM("getRecordSize");
TUASSERTE(size_t, 5, rec.getRecordSize());
s.assign(199, '2');
rec.updateMessageData(offset, s, s.size());
TUCSM("getMessageLength");
TUASSERTE(size_t, 200, rec.getMessageLength());
TUCSM("getHeadLength");
TUASSERTE(size_t, 4, rec.getHeadLength());
TUCSM("getTailLength");
TUASSERTE(size_t, 2, rec.getTailLength());
TUCSM("getRecordSize");
TUASSERTE(size_t, 206, rec.getRecordSize());
s.assign(17000, '3');
rec.updateMessageData(offset, s, s.size());
TUCSM("getMessageLength");
TUASSERTE(size_t, 17200, rec.getMessageLength());
TUCSM("getHeadLength");
TUASSERTE(size_t, 5, rec.getHeadLength());
TUCSM("getTailLength");
TUASSERTE(size_t, 4, rec.getTailLength());
TUCSM("getRecordSize");
TUASSERTE(size_t, 17209, rec.getRecordSize());
s.assign(2100800, '4');
rec.updateMessageData(offset, s, s.size());
TUCSM("getMessageLength");
TUASSERTE(size_t, 2118000, rec.getMessageLength());
TUCSM("getHeadLength");
TUASSERTE(size_t, 6, rec.getHeadLength());
TUCSM("getTailLength");
TUASSERTE(size_t, 16, rec.getTailLength());
TUCSM("getRecordSize");
TUASSERTE(size_t, 2118022, rec.getRecordSize());
TURETURN();
}
int BinexAttrs_T :: doMessageCapacityTests()
{
TUDEF("BinexData", "getMessageCapacity");
BinexData rec;
BinexData::UBNXI u;
size_t offset = 0;
rec.updateMessageData(offset, u);
TUASSERT(rec.getMessageData().capacity() >= 1);
TUCSM("ensureMessageCapacity");
rec.ensureMessageCapacity(1024);
TUASSERT(rec.getMessageData().capacity() >= 1024);
rec.ensureMessageCapacity(2048);
TUASSERT(rec.getMessageData().capacity() >= 2048);
TURETURN();
}
/** Run the program.
*
* @return Total error count for all tests
*/
int main(int argc, char *argv[])
{
int errorTotal = 0;
BinexAttrs_T testClass; // test data is loaded here
errorTotal += testClass.doIsDataTests();
errorTotal += testClass.doRecordFlagsTests();
errorTotal += testClass.doRecordIdTests();
errorTotal += testClass.doMessageCapacityTests();
errorTotal += testClass.doMessageLengthTests();
return( errorTotal );
} // main()
| 27.860169 | 89 | 0.626464 | mfkiwl |
67ab99e4ba08264d6738fc7f2d6d1f8ad3bcdf03 | 10,260 | cc | C++ | modules/congestion_controller/goog_cc/goog_cc_network_control_slowtest.cc | Numbrs/WebRTC | d9348ec831b8a1f178ce1a92877f04b1fbd27a04 | [
"BSD-3-Clause"
] | 4 | 2019-11-26T07:08:00.000Z | 2021-06-20T08:53:50.000Z | modules/congestion_controller/goog_cc/goog_cc_network_control_slowtest.cc | Numbrs/WebRTC | d9348ec831b8a1f178ce1a92877f04b1fbd27a04 | [
"BSD-3-Clause"
] | null | null | null | modules/congestion_controller/goog_cc/goog_cc_network_control_slowtest.cc | Numbrs/WebRTC | d9348ec831b8a1f178ce1a92877f04b1fbd27a04 | [
"BSD-3-Clause"
] | 4 | 2020-07-10T13:45:23.000Z | 2021-06-03T03:44:14.000Z | /*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <queue>
#include "api/transport/goog_cc_factory.h"
#include "test/field_trial.h"
#include "test/gtest.h"
#include "test/scenario/scenario.h"
namespace webrtc {
namespace test {
namespace {
// Count dips from a constant high bandwidth level within a short window.
int CountBandwidthDips(std::queue<DataRate> bandwidth_history,
DataRate threshold) {
if (bandwidth_history.empty())
return true;
DataRate first = bandwidth_history.front();
bandwidth_history.pop();
int dips = 0;
bool state_high = true;
while (!bandwidth_history.empty()) {
if (bandwidth_history.front() + threshold < first && state_high) {
++dips;
state_high = false;
} else if (bandwidth_history.front() == first) {
state_high = true;
} else if (bandwidth_history.front() > first) {
// If this is toggling we will catch it later when front becomes first.
state_high = false;
}
bandwidth_history.pop();
}
return dips;
}
} // namespace
TEST(GoogCcNetworkControllerTest, MaintainsLowRateInSafeResetTrial) {
const DataRate kLinkCapacity = DataRate::kbps(200);
const DataRate kStartRate = DataRate::kbps(300);
ScopedFieldTrials trial("WebRTC-Bwe-SafeResetOnRouteChange/Enabled/");
Scenario s("googcc_unit/safe_reset_low", true);
auto* send_net = s.CreateSimulationNode([&](NetworkNodeConfig* c) {
c->simulation.bandwidth = kLinkCapacity;
c->simulation.delay = TimeDelta::ms(10);
});
// TODO(srte): replace with SimulatedTimeClient when it supports probing.
auto* client = s.CreateClient("send", [&](CallClientConfig* c) {
c->transport.cc = TransportControllerConfig::CongestionController::kGoogCc;
c->transport.rates.start_rate = kStartRate;
});
auto* route = s.CreateRoutes(client, {send_net},
s.CreateClient("return", CallClientConfig()),
{s.CreateSimulationNode(NetworkNodeConfig())});
s.CreateVideoStream(route->forward(), VideoStreamConfig());
// Allow the controller to stabilize.
s.RunFor(TimeDelta::ms(500));
EXPECT_NEAR(client->send_bandwidth().kbps(), kLinkCapacity.kbps(), 50);
s.ChangeRoute(route->forward(), {send_net});
// Allow new settings to propagate.
s.RunFor(TimeDelta::ms(100));
// Under the trial, the target should be unchanged for low rates.
EXPECT_NEAR(client->send_bandwidth().kbps(), kLinkCapacity.kbps(), 50);
}
TEST(GoogCcNetworkControllerTest, CutsHighRateInSafeResetTrial) {
const DataRate kLinkCapacity = DataRate::kbps(1000);
const DataRate kStartRate = DataRate::kbps(300);
ScopedFieldTrials trial("WebRTC-Bwe-SafeResetOnRouteChange/Enabled/");
Scenario s("googcc_unit/safe_reset_high_cut", true);
auto send_net = s.CreateSimulationNode([&](NetworkNodeConfig* c) {
c->simulation.bandwidth = kLinkCapacity;
c->simulation.delay = TimeDelta::ms(50);
});
// TODO(srte): replace with SimulatedTimeClient when it supports probing.
auto* client = s.CreateClient("send", [&](CallClientConfig* c) {
c->transport.cc = TransportControllerConfig::CongestionController::kGoogCc;
c->transport.rates.start_rate = kStartRate;
});
auto* route = s.CreateRoutes(client, {send_net},
s.CreateClient("return", CallClientConfig()),
{s.CreateSimulationNode(NetworkNodeConfig())});
s.CreateVideoStream(route->forward(), VideoStreamConfig());
// Allow the controller to stabilize.
s.RunFor(TimeDelta::ms(500));
EXPECT_NEAR(client->send_bandwidth().kbps(), kLinkCapacity.kbps(), 300);
s.ChangeRoute(route->forward(), {send_net});
// Allow new settings to propagate.
s.RunFor(TimeDelta::ms(50));
// Under the trial, the target should be reset from high values.
EXPECT_NEAR(client->send_bandwidth().kbps(), kStartRate.kbps(), 30);
}
TEST(GoogCcNetworkControllerTest, DetectsHighRateInSafeResetTrial) {
ScopedFieldTrials trial(
"WebRTC-Bwe-SafeResetOnRouteChange/Enabled,ack/"
"WebRTC-Bwe-ProbeRateFallback/Enabled/");
const DataRate kInitialLinkCapacity = DataRate::kbps(200);
const DataRate kNewLinkCapacity = DataRate::kbps(800);
const DataRate kStartRate = DataRate::kbps(300);
Scenario s("googcc_unit/safe_reset_high_detect", true);
auto* initial_net = s.CreateSimulationNode([&](NetworkNodeConfig* c) {
c->simulation.bandwidth = kInitialLinkCapacity;
c->simulation.delay = TimeDelta::ms(50);
});
auto* new_net = s.CreateSimulationNode([&](NetworkNodeConfig* c) {
c->simulation.bandwidth = kNewLinkCapacity;
c->simulation.delay = TimeDelta::ms(50);
});
// TODO(srte): replace with SimulatedTimeClient when it supports probing.
auto* client = s.CreateClient("send", [&](CallClientConfig* c) {
c->transport.cc = TransportControllerConfig::CongestionController::kGoogCc;
c->transport.rates.start_rate = kStartRate;
});
auto* route = s.CreateRoutes(client, {initial_net},
s.CreateClient("return", CallClientConfig()),
{s.CreateSimulationNode(NetworkNodeConfig())});
s.CreateVideoStream(route->forward(), VideoStreamConfig());
// Allow the controller to stabilize.
s.RunFor(TimeDelta::ms(1000));
EXPECT_NEAR(client->send_bandwidth().kbps(), kInitialLinkCapacity.kbps(), 50);
s.ChangeRoute(route->forward(), {new_net});
// Allow new settings to propagate, but not probes to be received.
s.RunFor(TimeDelta::ms(50));
// Under the field trial, the target rate should be unchanged since it's lower
// than the starting rate.
EXPECT_NEAR(client->send_bandwidth().kbps(), kInitialLinkCapacity.kbps(), 50);
// However, probing should have made us detect the higher rate.
s.RunFor(TimeDelta::ms(2000));
EXPECT_GT(client->send_bandwidth().kbps(), kNewLinkCapacity.kbps() - 300);
}
TEST(GoogCcNetworkControllerTest,
TargetRateReducedOnPacingBufferBuildupInTrial) {
// Configure strict pacing to ensure build-up.
ScopedFieldTrials trial(
"WebRTC-CongestionWindowPushback/Enabled/WebRTC-CwndExperiment/"
"Enabled-100/WebRTC-Video-Pacing/factor:1.0/"
"WebRTC-AddPacingToCongestionWindowPushback/Enabled/");
const DataRate kLinkCapacity = DataRate::kbps(1000);
const DataRate kStartRate = DataRate::kbps(1000);
Scenario s("googcc_unit/pacing_buffer_buildup", true);
auto* net = s.CreateSimulationNode([&](NetworkNodeConfig* c) {
c->simulation.bandwidth = kLinkCapacity;
c->simulation.delay = TimeDelta::ms(50);
});
// TODO(srte): replace with SimulatedTimeClient when it supports pacing.
auto* client = s.CreateClient("send", [&](CallClientConfig* c) {
c->transport.cc = TransportControllerConfig::CongestionController::kGoogCc;
c->transport.rates.start_rate = kStartRate;
});
auto* route = s.CreateRoutes(client, {net},
s.CreateClient("return", CallClientConfig()),
{s.CreateSimulationNode(NetworkNodeConfig())});
s.CreateVideoStream(route->forward(), VideoStreamConfig());
// Allow some time for the buffer to build up.
s.RunFor(TimeDelta::seconds(5));
// Without trial, pacer delay reaches ~250 ms.
EXPECT_LT(client->GetStats().pacer_delay_ms, 150);
}
TEST(GoogCcNetworkControllerTest, NoBandwidthTogglingInLossControlTrial) {
ScopedFieldTrials trial("WebRTC-Bwe-LossBasedControl/Enabled/");
Scenario s("googcc_unit/no_toggling", true);
auto* send_net = s.CreateSimulationNode([&](NetworkNodeConfig* c) {
c->simulation.bandwidth = DataRate::kbps(2000);
c->simulation.loss_rate = 0.2;
c->simulation.delay = TimeDelta::ms(10);
});
// TODO(srte): replace with SimulatedTimeClient when it supports probing.
auto* client = s.CreateClient("send", [&](CallClientConfig* c) {
c->transport.cc = TransportControllerConfig::CongestionController::kGoogCc;
c->transport.rates.start_rate = DataRate::kbps(300);
});
auto* route = s.CreateRoutes(client, {send_net},
s.CreateClient("return", CallClientConfig()),
{s.CreateSimulationNode(NetworkNodeConfig())});
s.CreateVideoStream(route->forward(), VideoStreamConfig());
// Allow the controller to initialize.
s.RunFor(TimeDelta::ms(250));
std::queue<DataRate> bandwidth_history;
const TimeDelta step = TimeDelta::ms(50);
for (TimeDelta time = TimeDelta::Zero(); time < TimeDelta::ms(2000);
time += step) {
s.RunFor(step);
const TimeDelta window = TimeDelta::ms(500);
if (bandwidth_history.size() >= window / step)
bandwidth_history.pop();
bandwidth_history.push(client->send_bandwidth());
EXPECT_LT(CountBandwidthDips(bandwidth_history, DataRate::kbps(100)), 2);
}
}
TEST(GoogCcNetworkControllerTest, NoRttBackoffCollapseWhenVideoStops) {
ScopedFieldTrials trial("WebRTC-Bwe-MaxRttLimit/limit:2s/");
Scenario s("googcc_unit/rttbackoff_video_stop", true);
auto* send_net = s.CreateSimulationNode([&](NetworkNodeConfig* c) {
c->simulation.bandwidth = DataRate::kbps(2000);
c->simulation.delay = TimeDelta::ms(100);
});
auto* client = s.CreateClient("send", [&](CallClientConfig* c) {
c->transport.cc = TransportControllerConfig::CongestionController::kGoogCc;
c->transport.rates.start_rate = DataRate::kbps(1000);
});
auto* route = s.CreateRoutes(client, {send_net},
s.CreateClient("return", CallClientConfig()),
{s.CreateSimulationNode(NetworkNodeConfig())});
auto* video = s.CreateVideoStream(route->forward(), VideoStreamConfig());
// Allow the controller to initialize, then stop video.
s.RunFor(TimeDelta::seconds(1));
video->send()->Stop();
s.RunFor(TimeDelta::seconds(4));
EXPECT_GT(client->send_bandwidth().kbps(), 1000);
}
} // namespace test
} // namespace webrtc
| 43.474576 | 80 | 0.699025 | Numbrs |
67ad3a3b3743c8589aff3f4d2694c3f739d977b0 | 5,557 | cc | C++ | power_manager/powerd/system/dbus_wrapper.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | power_manager/powerd/system/dbus_wrapper.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | power_manager/powerd/system/dbus_wrapper.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Chromium OS 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 "power_manager/powerd/system/dbus_wrapper.h"
#include <memory>
#include <utility>
#include <base/bind.h>
#include <base/check.h>
#include <base/logging.h>
#include <base/memory/ptr_util.h>
#include <chromeos/dbus/service_constants.h>
#include <dbus/bus.h>
#include <dbus/message.h>
#include <google/protobuf/message_lite.h>
#include "power_manager/common/power_constants.h"
namespace power_manager {
namespace system {
namespace {
// Handles the result of an attempt to connect to a D-Bus signal, logging an
// error on failure.
void HandleSignalConnected(const std::string& interface,
const std::string& signal,
bool success) {
if (!success)
LOG(ERROR) << "Failed to connect to signal " << interface << "." << signal;
}
} // namespace
DBusWrapper::DBusWrapper(scoped_refptr<dbus::Bus> bus,
dbus::ExportedObject* exported_object)
: bus_(bus), exported_object_(exported_object), weak_ptr_factory_(this) {
// Listen for NameOwnerChanged signals from the bus itself.
dbus::ObjectProxy* bus_proxy =
bus->GetObjectProxy(kBusServiceName, dbus::ObjectPath(kBusServicePath));
bus_proxy->ConnectToSignal(
kBusInterface, kBusNameOwnerChangedSignal,
base::Bind(&DBusWrapper::HandleNameOwnerChangedSignal,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&HandleSignalConnected));
}
DBusWrapper::~DBusWrapper() = default;
// static
std::unique_ptr<DBusWrapper> DBusWrapper::Create() {
dbus::Bus::Options options;
options.bus_type = dbus::Bus::SYSTEM;
scoped_refptr<dbus::Bus> bus(new dbus::Bus(options));
if (!bus->Connect()) {
LOG(ERROR) << "Failed to connect to system bus";
return nullptr;
}
dbus::ExportedObject* exported_object =
bus->GetExportedObject(dbus::ObjectPath(kPowerManagerServicePath));
if (!exported_object) {
LOG(ERROR) << "Failed to export " << kPowerManagerServicePath << " object";
return nullptr;
}
return base::WrapUnique(new DBusWrapper(bus, exported_object));
}
void DBusWrapper::AddObserver(Observer* observer) {
DCHECK(observer);
observers_.AddObserver(observer);
}
void DBusWrapper::RemoveObserver(Observer* observer) {
DCHECK(observer);
observers_.RemoveObserver(observer);
}
scoped_refptr<dbus::Bus> DBusWrapper::GetBus() {
return bus_;
}
dbus::ObjectProxy* DBusWrapper::GetObjectProxy(const std::string& service_name,
const std::string& object_path) {
return bus_->GetObjectProxy(service_name, dbus::ObjectPath(object_path));
}
void DBusWrapper::RegisterForServiceAvailability(
dbus::ObjectProxy* proxy,
dbus::ObjectProxy::WaitForServiceToBeAvailableCallback callback) {
DCHECK(proxy);
proxy->WaitForServiceToBeAvailable(std::move(callback));
}
void DBusWrapper::RegisterForSignal(
dbus::ObjectProxy* proxy,
const std::string& interface_name,
const std::string& signal_name,
dbus::ObjectProxy::SignalCallback callback) {
DCHECK(proxy);
proxy->ConnectToSignal(interface_name, signal_name, callback,
base::Bind(&HandleSignalConnected));
}
void DBusWrapper::ExportMethod(
const std::string& method_name,
dbus::ExportedObject::MethodCallCallback callback) {
CHECK(exported_object_->ExportMethodAndBlock(kPowerManagerInterface,
method_name, callback));
}
bool DBusWrapper::PublishService() {
return bus_->RequestOwnershipAndBlock(kPowerManagerServiceName,
dbus::Bus::REQUIRE_PRIMARY);
}
void DBusWrapper::EmitSignal(dbus::Signal* signal) {
DCHECK(exported_object_);
DCHECK(signal);
exported_object_->SendSignal(signal);
}
void DBusWrapper::EmitBareSignal(const std::string& signal_name) {
dbus::Signal signal(kPowerManagerInterface, signal_name);
EmitSignal(&signal);
}
void DBusWrapper::EmitSignalWithProtocolBuffer(
const std::string& signal_name,
const google::protobuf::MessageLite& protobuf) {
dbus::Signal signal(kPowerManagerInterface, signal_name);
dbus::MessageWriter writer(&signal);
writer.AppendProtoAsArrayOfBytes(protobuf);
EmitSignal(&signal);
}
std::unique_ptr<dbus::Response> DBusWrapper::CallMethodSync(
dbus::ObjectProxy* proxy,
dbus::MethodCall* method_call,
base::TimeDelta timeout) {
DCHECK(proxy);
DCHECK(method_call);
return std::unique_ptr<dbus::Response>(
proxy->CallMethodAndBlock(method_call, timeout.InMilliseconds()));
}
void DBusWrapper::CallMethodAsync(
dbus::ObjectProxy* proxy,
dbus::MethodCall* method_call,
base::TimeDelta timeout,
dbus::ObjectProxy::ResponseCallback callback) {
DCHECK(proxy);
DCHECK(method_call);
proxy->CallMethod(method_call, timeout.InMilliseconds(), std::move(callback));
}
void DBusWrapper::HandleNameOwnerChangedSignal(dbus::Signal* signal) {
DCHECK(signal);
dbus::MessageReader reader(signal);
std::string name, old_owner, new_owner;
if (!reader.PopString(&name) || !reader.PopString(&old_owner) ||
!reader.PopString(&new_owner)) {
LOG(ERROR) << "Unable to parse " << kBusNameOwnerChangedSignal << " signal";
return;
}
for (DBusWrapper::Observer& observer : observers_)
observer.OnDBusNameOwnerChanged(name, old_owner, new_owner);
}
} // namespace system
} // namespace power_manager
| 31.573864 | 80 | 0.711535 | Toromino |
67ad54db2302bb014f877cd80fc4905d41ff9f64 | 2,350 | cpp | C++ | aws-cpp-sdk-glue/source/model/LongColumnStatisticsData.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-glue/source/model/LongColumnStatisticsData.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-glue/source/model/LongColumnStatisticsData.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-03-23T15:17:18.000Z | 2022-03-23T15:17:18.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/glue/model/LongColumnStatisticsData.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Glue
{
namespace Model
{
LongColumnStatisticsData::LongColumnStatisticsData() :
m_minimumValue(0),
m_minimumValueHasBeenSet(false),
m_maximumValue(0),
m_maximumValueHasBeenSet(false),
m_numberOfNulls(0),
m_numberOfNullsHasBeenSet(false),
m_numberOfDistinctValues(0),
m_numberOfDistinctValuesHasBeenSet(false)
{
}
LongColumnStatisticsData::LongColumnStatisticsData(JsonView jsonValue) :
m_minimumValue(0),
m_minimumValueHasBeenSet(false),
m_maximumValue(0),
m_maximumValueHasBeenSet(false),
m_numberOfNulls(0),
m_numberOfNullsHasBeenSet(false),
m_numberOfDistinctValues(0),
m_numberOfDistinctValuesHasBeenSet(false)
{
*this = jsonValue;
}
LongColumnStatisticsData& LongColumnStatisticsData::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("MinimumValue"))
{
m_minimumValue = jsonValue.GetInt64("MinimumValue");
m_minimumValueHasBeenSet = true;
}
if(jsonValue.ValueExists("MaximumValue"))
{
m_maximumValue = jsonValue.GetInt64("MaximumValue");
m_maximumValueHasBeenSet = true;
}
if(jsonValue.ValueExists("NumberOfNulls"))
{
m_numberOfNulls = jsonValue.GetInt64("NumberOfNulls");
m_numberOfNullsHasBeenSet = true;
}
if(jsonValue.ValueExists("NumberOfDistinctValues"))
{
m_numberOfDistinctValues = jsonValue.GetInt64("NumberOfDistinctValues");
m_numberOfDistinctValuesHasBeenSet = true;
}
return *this;
}
JsonValue LongColumnStatisticsData::Jsonize() const
{
JsonValue payload;
if(m_minimumValueHasBeenSet)
{
payload.WithInt64("MinimumValue", m_minimumValue);
}
if(m_maximumValueHasBeenSet)
{
payload.WithInt64("MaximumValue", m_maximumValue);
}
if(m_numberOfNullsHasBeenSet)
{
payload.WithInt64("NumberOfNulls", m_numberOfNulls);
}
if(m_numberOfDistinctValuesHasBeenSet)
{
payload.WithInt64("NumberOfDistinctValues", m_numberOfDistinctValues);
}
return payload;
}
} // namespace Model
} // namespace Glue
} // namespace Aws
| 20.79646 | 82 | 0.745532 | Neusoft-Technology-Solutions |
67af7a36c1718a383f6b9ca5e5e38cb6004ba8ed | 363 | hpp | C++ | mod04/ex03/ICharacter.hpp | paozer/piscine_cpp | 449d4a60b3c50c7ba6d94e38a7b632b5f447a438 | [
"Unlicense"
] | null | null | null | mod04/ex03/ICharacter.hpp | paozer/piscine_cpp | 449d4a60b3c50c7ba6d94e38a7b632b5f447a438 | [
"Unlicense"
] | null | null | null | mod04/ex03/ICharacter.hpp | paozer/piscine_cpp | 449d4a60b3c50c7ba6d94e38a7b632b5f447a438 | [
"Unlicense"
] | 2 | 2021-01-31T13:52:11.000Z | 2021-05-19T18:36:17.000Z | #ifndef ICHARACTER_HPP
#define ICHARACTER_HPP
#include <string>
class AMateria;
class ICharacter
{
public:
virtual ~ICharacter() {};
virtual std::string const & getName() const = 0;
virtual void equip(AMateria* m) = 0;
virtual void unequip(int idx) = 0;
virtual void use(int idx, ICharacter& target) = 0;
};
#endif
| 19.105263 | 58 | 0.636364 | paozer |
67b00a5dc92c58c08d5213df692d56e1eb4bcd19 | 1,144 | cpp | C++ | src/sx_serie_cronologia.cpp | D33pBlue/Cinenote-3.0 | 7dd871b40c537fdf73e7489919c4bfef391864c2 | [
"MIT"
] | null | null | null | src/sx_serie_cronologia.cpp | D33pBlue/Cinenote-3.0 | 7dd871b40c537fdf73e7489919c4bfef391864c2 | [
"MIT"
] | null | null | null | src/sx_serie_cronologia.cpp | D33pBlue/Cinenote-3.0 | 7dd871b40c537fdf73e7489919c4bfef391864c2 | [
"MIT"
] | null | null | null | #include "sx_serie_cronologia.h"
#include "form_serie_mese.h"
#include <QtSql>
#include <iostream>
using namespace std;
sx_serie_cronologia::sx_serie_cronologia(QWidget *parent) :
QWidget(parent)
{
lay=new QVBoxLayout(this);
tit=new QLabel("Cronologia serie",this);
tit->setFont(QFont("Times",15));
area=new QScrollArea(this);
QWidget *bg=new QWidget(this);
QVBoxLayout *lbg=new QVBoxLayout(this);
bg->setLayout(lbg);
int altezza=0,numero=0;
QSqlQuery q;
q.exec("select min(datainizio),max(datafine) from visionestagione;");
q.next();
QDate curr=QDate::fromString(q.value(1).toString(),"yyyy-MM-dd");
QDate fine=QDate::fromString(q.value(0).toString(),"yyyy-MM-dd");
while(curr>=fine){
Form_serie_mese *fo=new Form_serie_mese(this);
numero+=fo->settamese(curr);
lbg->addWidget(fo);
altezza++;
curr=curr.addMonths(-1);
}
tit->setText(QString("Cronologia serie [visioni: ")+QString::number(numero)+QString("]"));
bg->setMinimumSize(770,altezza*200);
area->setWidget(bg);
lay->addWidget(tit);
lay->addWidget(area);
setLayout(lay);
}
| 27.238095 | 94 | 0.671329 | D33pBlue |
67b60a8d79680c45917ae52f7688ec00c7534bbf | 16,907 | cpp | C++ | src/mlpack/methods/kmeans/kmeans_main.cpp | oblanchet/mlpack | e02ab3be544694294d2f73bd12a98d0d162ef3af | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 4,216 | 2015-01-01T02:06:12.000Z | 2022-03-31T19:12:06.000Z | src/mlpack/methods/kmeans/kmeans_main.cpp | oblanchet/mlpack | e02ab3be544694294d2f73bd12a98d0d162ef3af | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2,621 | 2015-01-01T01:41:47.000Z | 2022-03-31T19:01:26.000Z | src/mlpack/methods/kmeans/kmeans_main.cpp | oblanchet/mlpack | e02ab3be544694294d2f73bd12a98d0d162ef3af | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1,972 | 2015-01-01T23:37:13.000Z | 2022-03-28T06:03:41.000Z | /**
* @file methods/kmeans/kmeans_main.cpp
* @author Ryan Curtin
*
* Executable for running K-Means.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include <mlpack/prereqs.hpp>
#include <mlpack/core/util/io.hpp>
#ifdef BINDING_NAME
#undef BINDING_NAME
#endif
#define BINDING_NAME kmeans
#include <mlpack/core/util/mlpack_main.hpp>
#include "kmeans.hpp"
#include "allow_empty_clusters.hpp"
#include "kill_empty_clusters.hpp"
#include "refined_start.hpp"
#include "kmeans_plus_plus_initialization.hpp"
#include "elkan_kmeans.hpp"
#include "hamerly_kmeans.hpp"
#include "pelleg_moore_kmeans.hpp"
#include "dual_tree_kmeans.hpp"
using namespace mlpack;
using namespace mlpack::kmeans;
using namespace mlpack::util;
using namespace std;
// Program Name.
BINDING_USER_NAME("K-Means Clustering");
// Short description.
BINDING_SHORT_DESC(
"An implementation of several strategies for efficient k-means clustering. "
"Given a dataset and a value of k, this computes and returns a k-means "
"clustering on that data.");
// Long description.
BINDING_LONG_DESC(
"This program performs K-Means clustering on the given dataset. It can "
"return the learned cluster assignments, and the centroids of the clusters."
" Empty clusters are not allowed by default; when a cluster becomes empty,"
" the point furthest from the centroid of the cluster with maximum variance"
" is taken to fill that cluster."
"\n\n"
"Optionally, the strategy to choose initial centroids can be specified. "
"The k-means++ algorithm can be used to choose initial centroids with "
"the " + PRINT_PARAM_STRING("kmeans_plus_plus") + " parameter. The "
"Bradley and Fayyad approach (\"Refining initial points for k-means "
"clustering\", 1998) can be used to select initial points by specifying "
"the " + PRINT_PARAM_STRING("refined_start") + " parameter. This approach "
"works by taking random samplings of the dataset; to specify the number of "
"samplings, the " + PRINT_PARAM_STRING("samplings") + " parameter is used, "
"and to specify the percentage of the dataset to be used in each sample, "
"the " + PRINT_PARAM_STRING("percentage") + " parameter is used (it should "
"be a value between 0.0 and 1.0)."
"\n\n"
"There are several options available for the algorithm used for each Lloyd "
"iteration, specified with the " + PRINT_PARAM_STRING("algorithm") + " "
" option. The standard O(kN) approach can be used ('naive'). Other "
"options include the Pelleg-Moore tree-based algorithm ('pelleg-moore'), "
"Elkan's triangle-inequality based algorithm ('elkan'), Hamerly's "
"modification to Elkan's algorithm ('hamerly'), the dual-tree k-means "
"algorithm ('dualtree'), and the dual-tree k-means algorithm using the "
"cover tree ('dualtree-covertree')."
"\n\n"
"The behavior for when an empty cluster is encountered can be modified with"
" the " + PRINT_PARAM_STRING("allow_empty_clusters") + " option. When "
"this option is specified and there is a cluster owning no points at the "
"end of an iteration, that cluster's centroid will simply remain in its "
"position from the previous iteration. If the " +
PRINT_PARAM_STRING("kill_empty_clusters") + " option is specified, then "
"when a cluster owns no points at the end of an iteration, the cluster "
"centroid is simply filled with DBL_MAX, killing it and effectively "
"reducing k for the rest of the computation. Note that the default option "
"when neither empty cluster option is specified can be time-consuming to "
"calculate; therefore, specifying either of these parameters will often "
"accelerate runtime."
"\n\n"
"Initial clustering assignments may be specified using the " +
PRINT_PARAM_STRING("initial_centroids") + " parameter, and the maximum "
"number of iterations may be specified with the " +
PRINT_PARAM_STRING("max_iterations") + " parameter.");
// Example.
BINDING_EXAMPLE(
"As an example, to use Hamerly's algorithm to perform k-means clustering "
"with k=10 on the dataset " + PRINT_DATASET("data") + ", saving the "
"centroids to " + PRINT_DATASET("centroids") + " and the assignments for "
"each point to " + PRINT_DATASET("assignments") + ", the following "
"command could be used:"
"\n\n" +
PRINT_CALL("kmeans", "input", "data", "clusters", 10, "output",
"assignments", "centroid", "centroids") +
"\n\n"
"To run k-means on that same dataset with initial centroids specified in " +
PRINT_DATASET("initial") + " with a maximum of 500 iterations, "
"storing the output centroids in " + PRINT_DATASET("final") + " the "
"following command may be used:"
"\n\n" +
PRINT_CALL("kmeans", "input", "data", "initial_centroids", "initial",
"clusters", 10, "max_iterations", 500, "centroid", "final"));
// See also...
BINDING_SEE_ALSO("K-Means tutorial", "@doxygen/kmtutorial.html");
BINDING_SEE_ALSO("@dbscan", "#dbscan");
BINDING_SEE_ALSO("k-means++", "https://en.wikipedia.org/wiki/K-means%2B%2B");
BINDING_SEE_ALSO("Using the triangle inequality to accelerate k-means (pdf)",
"http://www.aaai.org/Papers/ICML/2003/ICML03-022.pdf");
BINDING_SEE_ALSO("Making k-means even faster (pdf)",
"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.586.2554"
"&rep=rep1&type=pdf");
BINDING_SEE_ALSO("Accelerating exact k-means algorithms with geometric"
" reasoning (pdf)", "http://reports-archive.adm.cs.cmu.edu/anon/anon"
"/usr/ftp/usr0/ftp/2000/CMU-CS-00-105.pdf");
BINDING_SEE_ALSO("A dual-tree algorithm for fast k-means clustering with large "
"k (pdf)", "http://www.ratml.org/pub/pdf/2017dual.pdf");
BINDING_SEE_ALSO("mlpack::kmeans::KMeans class documentation",
"@doxygen/classmlpack_1_1kmeans_1_1KMeans.html");
// Required options.
PARAM_MATRIX_IN_REQ("input", "Input dataset to perform clustering on.", "i");
PARAM_INT_IN_REQ("clusters", "Number of clusters to find (0 autodetects from "
"initial centroids).", "c");
// Output options.
PARAM_FLAG("in_place", "If specified, a column containing the learned cluster "
"assignments will be added to the input dataset file. In this case, "
"--output_file is overridden. (Do not use in Python.)", "P");
PARAM_MATRIX_OUT("output", "Matrix to store output labels or labeled data to.",
"o");
PARAM_MATRIX_OUT("centroid", "If specified, the centroids of each cluster will "
" be written to the given file.", "C");
// k-means configuration options.
PARAM_FLAG("allow_empty_clusters", "Allow empty clusters to be persist.", "e");
PARAM_FLAG("kill_empty_clusters", "Remove empty clusters when they occur.",
"E");
PARAM_FLAG("labels_only", "Only output labels into output file.", "l");
PARAM_INT_IN("max_iterations", "Maximum number of iterations before k-means "
"terminates.", "m", 1000);
PARAM_INT_IN("seed", "Random seed. If 0, 'std::time(NULL)' is used.", "s", 0);
PARAM_MATRIX_IN("initial_centroids", "Start with the specified initial "
"centroids.", "I");
// Parameters for "refined start" k-means.
PARAM_FLAG("refined_start", "Use the refined initial point strategy by Bradley "
"and Fayyad to choose initial points.", "r");
PARAM_INT_IN("samplings", "Number of samplings to perform for refined start "
"(use when --refined_start is specified).", "S", 100);
PARAM_DOUBLE_IN("percentage", "Percentage of dataset to use for each refined "
"start sampling (use when --refined_start is specified).", "p", 0.02);
PARAM_FLAG("kmeans_plus_plus", "Use the k-means++ initialization strategy to "
"choose initial points.", "K");
PARAM_STRING_IN("algorithm", "Algorithm to use for the Lloyd iteration "
"('naive', 'pelleg-moore', 'elkan', 'hamerly', 'dualtree', or "
"'dualtree-covertree').", "a", "naive");
// Given the type of initial partition policy, figure out the empty cluster
// policy and run k-means.
template<typename InitialPartitionPolicy>
void FindEmptyClusterPolicy(util::Params& params,
util::Timers& timers,
const InitialPartitionPolicy& ipp);
// Given the initial partitionining policy and empty cluster policy, figure out
// the Lloyd iteration step type and run k-means.
template<typename InitialPartitionPolicy, typename EmptyClusterPolicy>
void FindLloydStepType(util::Params& params,
util::Timers& timers,
const InitialPartitionPolicy& ipp);
// Given the template parameters, sanitize/load input and run k-means.
template<typename InitialPartitionPolicy,
typename EmptyClusterPolicy,
template<class, class> class LloydStepType>
void RunKMeans(util::Params& params,
util::Timers& timers,
const InitialPartitionPolicy& ipp);
void BINDING_FUNCTION(util::Params& params, util::Timers& timers)
{
// Initialize random seed.
if (params.Get<int>("seed") != 0)
math::RandomSeed((size_t) params.Get<int>("seed"));
else
math::RandomSeed((size_t) std::time(NULL));
RequireOnlyOnePassed(params, { "refined_start", "kmeans_plus_plus" }, true,
"Only one initialization strategy can be specified!", true);
// Now, start building the KMeans type that we'll be using. Start with the
// initial partition policy. The call to FindEmptyClusterPolicy<> results in
// a call to RunKMeans<> and the algorithm is completed.
if (params.Has("refined_start"))
{
RequireParamValue<int>(params, "samplings", [](int x) { return x > 0; },
true, "number of samplings must be positive");
const int samplings = params.Get<int>("samplings");
RequireParamValue<double>(params, "percentage",
[](double x) { return x > 0.0 && x <= 1.0; }, true, "percentage to "
"sample must be greater than 0.0 and less than or equal to 1.0");
const double percentage = params.Get<double>("percentage");
FindEmptyClusterPolicy<RefinedStart>(params, timers,
RefinedStart(samplings, percentage));
}
else if (params.Has("kmeans_plus_plus"))
{
FindEmptyClusterPolicy<KMeansPlusPlusInitialization>(params, timers,
KMeansPlusPlusInitialization());
}
else
{
FindEmptyClusterPolicy<SampleInitialization>(params, timers,
SampleInitialization());
}
}
// Given the type of initial partition policy, figure out the empty cluster
// policy and run k-means.
template<typename InitialPartitionPolicy>
void FindEmptyClusterPolicy(util::Params& params,
util::Timers& timers,
const InitialPartitionPolicy& ipp)
{
if (params.Has("allow_empty_clusters") ||
params.Has("kill_empty_clusters"))
{
RequireOnlyOnePassed(params, { "allow_empty_clusters",
"kill_empty_clusters" }, true);
}
if (params.Has("allow_empty_clusters"))
{
FindLloydStepType<InitialPartitionPolicy, AllowEmptyClusters>(params,
timers, ipp);
}
else if (params.Has("kill_empty_clusters"))
{
FindLloydStepType<InitialPartitionPolicy, KillEmptyClusters>(params, timers,
ipp);
}
else
{
FindLloydStepType<InitialPartitionPolicy, MaxVarianceNewCluster>(params,
timers, ipp);
}
}
// Given the initial partitionining policy and empty cluster policy, figure out
// the Lloyd iteration step type and run k-means.
template<typename InitialPartitionPolicy, typename EmptyClusterPolicy>
void FindLloydStepType(util::Params& params,
util::Timers& timers,
const InitialPartitionPolicy& ipp)
{
RequireParamInSet<string>(params, "algorithm", { "elkan", "hamerly",
"pelleg-moore", "dualtree", "dualtree-covertree", "naive" }, true,
"unknown k-means algorithm");
const string algorithm = params.Get<string>("algorithm");
if (algorithm == "elkan")
{
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, ElkanKMeans>(params,
timers, ipp);
}
else if (algorithm == "hamerly")
{
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, HamerlyKMeans>(
params, timers, ipp);
}
else if (algorithm == "pelleg-moore")
{
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy,
PellegMooreKMeans>(params, timers, ipp);
}
else if (algorithm == "dualtree")
{
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy,
DefaultDualTreeKMeans>(params, timers, ipp);
}
else if (algorithm == "dualtree-covertree")
{
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy,
CoverTreeDualTreeKMeans>(params, timers, ipp);
}
else if (algorithm == "naive")
{
RunKMeans<InitialPartitionPolicy, EmptyClusterPolicy, NaiveKMeans>(params,
timers, ipp);
}
}
// Given the template parameters, sanitize/load input and run k-means.
template<typename InitialPartitionPolicy,
typename EmptyClusterPolicy,
template<class, class> class LloydStepType>
void RunKMeans(util::Params& params,
util::Timers& timers,
const InitialPartitionPolicy& ipp)
{
// Now, do validation of input options.
if (!params.Has("initial_centroids"))
{
RequireParamValue<int>(params, "clusters", [](int x) { return x > 0; },
true, "number of clusters must be positive");
}
else
{
ReportIgnoredParam(params, {{ "initial_centroids", true }}, "clusters");
}
int clusters = params.Get<int>("clusters");
if (clusters == 0 && params.Has("initial_centroids"))
{
Log::Info << "Detecting number of clusters automatically from input "
<< "centroids." << endl;
}
RequireParamValue<int>(params, "max_iterations", [](int x) { return x >= 0; },
true, "maximum iterations must be positive or 0 (for no limit)");
const int maxIterations = params.Get<int>("max_iterations");
// Make sure we have an output file if we're not doing the work in-place.
RequireOnlyOnePassed(params, { "in_place", "output", "centroid" }, false,
"no results will be saved");
arma::mat dataset = params.Get<arma::mat>("input"); // Load our dataset.
arma::mat centroids;
const bool initialCentroidGuess = params.Has("initial_centroids");
// Load initial centroids if the user asked for it.
if (initialCentroidGuess)
{
centroids = std::move(params.Get<arma::mat>("initial_centroids"));
if (clusters == 0)
clusters = centroids.n_cols;
ReportIgnoredParam(params, {{ "refined_start", true }},
"initial_centroids");
if (!params.Has("refined_start"))
Log::Info << "Using initial centroid guesses." << endl;
}
timers.Start("clustering");
KMeans<metric::EuclideanDistance,
InitialPartitionPolicy,
EmptyClusterPolicy,
LloydStepType> kmeans(maxIterations, metric::EuclideanDistance(), ipp);
if (params.Has("output") || params.Has("in_place"))
{
// We need to get the assignments.
arma::Row<size_t> assignments;
kmeans.Cluster(dataset, clusters, assignments, centroids,
false, initialCentroidGuess);
timers.Stop("clustering");
// Now figure out what to do with our results.
if (params.Has("in_place"))
{
// Add the column of assignments to the dataset; but we have to convert
// them to type double first.
arma::rowvec converted(assignments.n_elem);
for (size_t i = 0; i < assignments.n_elem; ++i)
converted(i) = (double) assignments(i);
dataset.insert_rows(dataset.n_rows, converted);
// Save the dataset.
params.MakeInPlaceCopy("output", "input");
params.Get<arma::mat>("output") = std::move(dataset);
}
else
{
if (params.Has("labels_only"))
{
// Save only the labels. TODO: figure out how to get this to output an
// arma::Mat<size_t> instead of an arma::mat.
params.Get<arma::mat>("output") =
arma::conv_to<arma::mat>::from(assignments);
}
else
{
// Convert the assignments to doubles.
arma::rowvec converted(assignments.n_elem);
for (size_t i = 0; i < assignments.n_elem; ++i)
converted(i) = (double) assignments(i);
dataset.insert_rows(dataset.n_rows, converted);
// Now save, in the different file.
params.Get<arma::mat>("output") = std::move(dataset);
}
}
}
else
{
// Just save the centroids.
kmeans.Cluster(dataset, clusters, centroids, initialCentroidGuess);
timers.Stop("clustering");
}
// Should we write the centroids to a file?
if (params.Has("centroid"))
params.Get<arma::mat>("centroid") = std::move(centroids);
}
| 40.350835 | 80 | 0.684273 | oblanchet |
67b6b67284e1c04aadcc357ddfa90519f056b94b | 3,450 | cpp | C++ | Source/NewtonPhysics/Newton6DOFConstraint.cpp | TrevorCash/rbfx-newton | a8465870a85d69386709a4d65d758fa28b69918b | [
"MIT"
] | 9 | 2019-05-07T00:23:10.000Z | 2022-03-15T20:54:03.000Z | Source/NewtonPhysics/Newton6DOFConstraint.cpp | TrevorCash/rbfx-newton | a8465870a85d69386709a4d65d758fa28b69918b | [
"MIT"
] | null | null | null | Source/NewtonPhysics/Newton6DOFConstraint.cpp | TrevorCash/rbfx-newton | a8465870a85d69386709a4d65d758fa28b69918b | [
"MIT"
] | 2 | 2019-11-10T06:56:14.000Z | 2020-07-05T11:32:21.000Z | #include "Newton6DOFConstraint.h"
#include "NewtonPhysicsWorld.h"
#include "UrhoNewtonConversions.h"
#include "dCustomSixdof.h"
#include "Urho3D/Core/Context.h"
namespace Urho3D {
NewtonSixDofConstraint::NewtonSixDofConstraint(Context* context) : NewtonConstraint(context)
{
}
NewtonSixDofConstraint::~NewtonSixDofConstraint()
{
}
void NewtonSixDofConstraint::RegisterObject(Context* context)
{
context->RegisterFactory<NewtonSixDofConstraint>(DEF_PHYSICS_CATEGORY.c_str());
URHO3D_COPY_BASE_ATTRIBUTES(NewtonConstraint);
}
void NewtonSixDofConstraint::SetPitchLimits(float minLimit, float maxLimit)
{
if (pitchLimits_ != Vector2(minLimit, maxLimit)) {
pitchLimits_.x_ = minLimit;
pitchLimits_.y_ = maxLimit;
if (newtonJoint_)
{
static_cast<dCustomSixdof*>(newtonJoint_)->SetPitchLimits(pitchLimits_.x_, pitchLimits_.y_);
}
else
MarkDirty();
}
}
void NewtonSixDofConstraint::SetPitchLimits(const Vector3& limits)
{
SetPitchLimits(limits.x_, limits.y_);
}
void NewtonSixDofConstraint::SetYawLimits(float minLimit, float maxLimit)
{
if (yawLimits_ != Vector2(minLimit, maxLimit)) {
yawLimits_.x_ = minLimit;
yawLimits_.y_ = maxLimit;
if (newtonJoint_)
{
static_cast<dCustomSixdof*>(newtonJoint_)->SetYawLimits(yawLimits_.x_, yawLimits_.y_);
}
else
MarkDirty();
}
}
void NewtonSixDofConstraint::SetYawLimits(const Vector3& limits)
{
SetYawLimits(limits.x_, limits.y_);
}
void NewtonSixDofConstraint::SetRollLimits(float minLimit, float maxLimit)
{
if (rollLimits_ != Vector2(minLimit, maxLimit)) {
rollLimits_.x_ = minLimit;
rollLimits_.y_ = maxLimit;
if (newtonJoint_)
{
static_cast<dCustomSixdof*>(newtonJoint_)->SetRollLimits(rollLimits_.x_, rollLimits_.y_);
}
else
MarkDirty();
}
}
void NewtonSixDofConstraint::SetRollLimits(const Vector3& limits)
{
SetRollLimits(limits.x_, limits.y_);
}
void NewtonSixDofConstraint::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
{
NewtonConstraint::DrawDebugGeometry(debug, depthTest);
}
void NewtonSixDofConstraint::buildConstraint()
{
newtonJoint_ = new dCustomSixdof(UrhoToNewton(GetOwnBuildWorldFrame()), UrhoToNewton(GetOtherBuildWorldFrame()), GetOwnNewtonBody(), GetOtherNewtonBody());
}
bool NewtonSixDofConstraint::applyAllJointParams()
{
if (!NewtonConstraint::applyAllJointParams())
return false;
static_cast<dCustomSixdof*>(newtonJoint_)->SetLinearLimits(dVector(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE)*-1.0f, dVector(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE));
static_cast<dCustomSixdof*>(newtonJoint_)->SetPitchLimits(pitchLimits_.x_ * dDegreeToRad, pitchLimits_.y_* dDegreeToRad);
static_cast<dCustomSixdof*>(newtonJoint_)->SetYawLimits(yawLimits_.x_* dDegreeToRad, yawLimits_.y_* dDegreeToRad);
static_cast<dCustomSixdof*>(newtonJoint_)->SetRollLimits(rollLimits_.x_* dDegreeToRad, rollLimits_.y_* dDegreeToRad);
return true;
}
}
| 29.237288 | 181 | 0.656812 | TrevorCash |
67bc50a40b2e0bebd13a71c214d38e24f8dad1eb | 1,247 | cpp | C++ | test/MathTest.cpp | helmertz/noxoscope | 2c663e12ef5a54e61eae7b60f4efa934f84a1814 | [
"CC-BY-3.0",
"Apache-2.0"
] | null | null | null | test/MathTest.cpp | helmertz/noxoscope | 2c663e12ef5a54e61eae7b60f4efa934f84a1814 | [
"CC-BY-3.0",
"Apache-2.0"
] | null | null | null | test/MathTest.cpp | helmertz/noxoscope | 2c663e12ef5a54e61eae7b60f4efa934f84a1814 | [
"CC-BY-3.0",
"Apache-2.0"
] | null | null | null | //===----------------------------------------------------------------------===//
//
// This file is part of the Noxoscope project
//
// Copyright (c) 2016 Niklas Helmertz
//
//===----------------------------------------------------------------------===//
#include "TestShared.h"
#include <Logging.h>
#include <GeometryMath.h>
TEST_CASE("Example test") {
REQUIRE(1 + 1 == 2);
}
TEST_CASE("Test converting spherical and back") {
using namespace glm;
rc::prop("", []() {
float radius = floatInRange(0.01f, 100.0f);
float inclination = floatInRange(0.0f, PI_F);
float azimuth = floatInRange(0.0f, 2.0f * PI_F);
vec3 cartesian = sphericalToCartesian(radius, inclination, azimuth);
vec3 sphericalRes = cartesianToSpherical(cartesian);
float resRadius = sphericalRes.x;
float resInclination = sphericalRes.y;
float resAzimuth = fmod(sphericalRes.z + 2.0f * PI_F, 2.0f * PI_F); // Convert from [-pi,pi] to [0,2*pi]
RC_ASSERT(approxEqual(radius, resRadius));
RC_ASSERT(approxEqual(inclination, resInclination));
// If inclination is either straight up or down, any azimuth would be valid
if (!approxEqual(inclination, 0.0f) && !approxEqual(inclination, PI_F)) {
RC_ASSERT(approxEqual(azimuth, resAzimuth));
}
});
}
| 30.414634 | 106 | 0.614274 | helmertz |
67bdb2c9ac5fa996f5b6f89308f2fe7b25c86705 | 2,376 | cpp | C++ | cpp/test/sg/fnv_hash_test.cpp | Nicholas-7/cuml | 324d4490dc5254e1188d1678e704622eb69678cb | [
"Apache-2.0"
] | 2,743 | 2018-10-11T17:28:58.000Z | 2022-03-31T19:20:50.000Z | cpp/test/sg/fnv_hash_test.cpp | Nicholas-7/cuml | 324d4490dc5254e1188d1678e704622eb69678cb | [
"Apache-2.0"
] | 4,280 | 2018-10-11T22:29:57.000Z | 2022-03-31T22:02:44.000Z | cpp/test/sg/fnv_hash_test.cpp | Nicholas-7/cuml | 324d4490dc5254e1188d1678e704622eb69678cb | [
"Apache-2.0"
] | 454 | 2018-10-11T17:40:56.000Z | 2022-03-25T17:07:09.000Z | /*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cuml/fil/fnv_hash.h>
#include <gtest/gtest.h>
#include <raft/error.hpp>
struct fnv_vec_t {
std::vector<char> input;
unsigned long long correct_64bit;
uint32_t correct_32bit;
};
class FNVHashTest : public testing::TestWithParam<fnv_vec_t> {
protected:
void SetUp() override { param = GetParam(); }
void check()
{
unsigned long long hash_64bit =
fowler_noll_vo_fingerprint64(param.input.begin(), param.input.end());
ASSERT(hash_64bit == param.correct_64bit, "Wrong hash computed");
unsigned long hash_32bit =
fowler_noll_vo_fingerprint64_32(param.input.begin(), param.input.end());
ASSERT(hash_32bit == param.correct_32bit, "Wrong xor-folded hash computed");
}
fnv_vec_t param;
};
std::vector<fnv_vec_t> fnv_vecs = {
{{}, 14695981039346656037ull, 0xcbf29ce4 ^ 0x84222325}, // test #0
// 32-bit output is xor-folded 64-bit output. The format below makes this obvious.
{{0}, 0xaf63bd4c8601b7df, 0xaf63bd4c ^ 0x8601b7df},
{{1}, 0xaf63bd4c8601b7de, 0xaf63bd4c ^ 0x8601b7de},
{{2}, 0xaf63bd4c8601b7dd, 0xaf63bd4c ^ 0x8601b7dd},
{{3}, 0xaf63bd4c8601b7dc, 0xaf63bd4c ^ 0x8601b7dc},
{{1, 2}, 0x08328707b4eb6e38, 0x08328707 ^ 0xb4eb6e38}, // test #5
{{2, 1}, 0x08328607b4eb6c86, 0x08328607 ^ 0xb4eb6c86},
{{1, 2, 3}, 0xd949aa186c0c492b, 0xd949aa18 ^ 0x6c0c492b},
{{1, 3, 2}, 0xd949ab186c0c4ad9, 0xd949ab18 ^ 0x6c0c4ad9},
{{2, 1, 3}, 0xd94645186c0967b1, 0xd9464518 ^ 0x6c0967b1},
{{2, 3, 1}, 0xd94643186c09644d, 0xd9464318 ^ 0x6c09644d}, // test #10
{{3, 1, 2}, 0xd942e1186c0687ed, 0xd942e118 ^ 0x6c0687ed},
{{3, 2, 1}, 0xd942e2186c0689a3, 0xd942e218 ^ 0x6c0689a3},
};
TEST_P(FNVHashTest, Import) { check(); }
INSTANTIATE_TEST_CASE_P(FilTests, FNVHashTest, testing::ValuesIn(fnv_vecs));
| 37.714286 | 84 | 0.715488 | Nicholas-7 |
67be146857546dffe08c50450f7a2e344235fa03 | 5,506 | cpp | C++ | Game/Source/GameObjects/Trainer.cpp | Crewbee/Pokemon-Clone-DX12 | 188bdde03d5078899a1532305a87d15c611c6c13 | [
"CC0-1.0"
] | null | null | null | Game/Source/GameObjects/Trainer.cpp | Crewbee/Pokemon-Clone-DX12 | 188bdde03d5078899a1532305a87d15c611c6c13 | [
"CC0-1.0"
] | null | null | null | Game/Source/GameObjects/Trainer.cpp | Crewbee/Pokemon-Clone-DX12 | 188bdde03d5078899a1532305a87d15c611c6c13 | [
"CC0-1.0"
] | null | null | null | #include "GamePCH.h"
#include "GameObjects/GameObject.h"
#include "Trainer.h"
#include "Controllers/PlayerController.h"
#include "Sprites/AnimatedSprite.h"
#include "GameplayHelpers/ResourceManager.h"
#include "GameplayHelpers/TileMap.h"
#include "Mesh/Mesh.h"
#include "GameplayHelpers/SceneManager.h"
#include "Scenes/Scene.h"
#include "Scenes/OakLab.h"
#include "Scenes/PalletTown.h"
Trainer::Trainer(ResourceManager * aResourceManager, GameCore * myGame, Mesh * myMesh, GLuint aTexture) :GameObject(myGame, myMesh, aTexture)
{
myDirection = SpriteWalkDown;
myResourceManager = aResourceManager;
m_pMesh->GenerateFrameMesh();
//Initialize the animated sprites
for (int i = 0; i < NUM_DIRECTIONS; i++)
{
m_Animations[i] = new AnimatedSprite(myResourceManager, myGame, myMesh, 2, aTexture);
m_Animations[i]->AddFrame(AnimationKeys[i] + "1.png");
m_Animations[i]->AddFrame(AnimationKeys[i] + "2.png");
m_Animations[i]->AddFrame(AnimationKeys[i] + "1.png");
m_Animations[i]->AddFrame(AnimationKeys[i] + "3.png");
m_Animations[i]->SetFrameSpeed(6.0f);
m_Animations[i]->SetLoop(true);
m_Animations[i]->SetPosition(m_Position);
}
m_Stop = false;
m_InTransition = false;
}
Trainer::~Trainer()
{
for (int i = 0; i < NUM_DIRECTIONS; i++)
{
delete m_Animations[i];
m_Animations[i] = nullptr;
}
myResourceManager = nullptr;
}
void Trainer::Update(float deltatime)
{
Pause();
if (m_InTransition == false)
{
if (myController)
{
if (m_Stop == false)
{
if (myController->IsForwardHeld())
{
Move(SpriteWalkUp, deltatime);
}
if (myController->IsReverseHeld())
{
Move(SpriteWalkDown, deltatime);
}
if (myController->IsTurnRightHeld())
{
Move(SpriteWalkRight, deltatime);
}
if (myController->IsTurnLeftHeld())
{
Move(SpriteWalkLeft, deltatime);
}
if (myController->IsInputReleased())
{
for (int i = 0; i < NUM_DIRECTIONS; i++)
{
m_Animations[i]->SetFrameIndex(0);
}
}
}
}
}
if (m_InTransition == true)
{
if (myDirection == SpriteWalkUp || myDirection == SpriteWalkRight)
{
if (m_Position.y < aTransitionDestination.y)
{
Move(myDirection, deltatime);
}
else if (m_Position.x < aTransitionDestination.x)
{
Move(myDirection, deltatime);
}
else
{
m_InTransition = false;
}
}
if (myDirection == SpriteWalkDown || myDirection == SpriteWalkLeft)
{
if (m_Position.y > aTransitionDestination.y)
{
Move(myDirection, deltatime);
}
else if (m_Position.x > aTransitionDestination.x)
{
Move(myDirection, deltatime);
}
else
{
m_InTransition = false;
}
}
}
for (int i = 0; i < NUM_DIRECTIONS; i++)
{
m_Animations[i]->SetPosition(GetPosition());
m_Animations[i]->Update(deltatime);
}
}
void Trainer::Draw(vec2 camPos, vec2 projecScale)
{
m_Animations[myDirection]->Draw(camPos, projecScale);
}
void Trainer::Move(SpriteDirection dir, float deltatime)
{
NewPosition = m_Position;
Resume();
if (myDirection != dir)
{
myDirection = dir;
}
vec2 velocity = DIRECTIONVECTOR[dir] * PLAYER_SPEED;
NewPosition += velocity * deltatime;
if (m_InTransition == false)
{
if (CheckForCollision(NewPosition) == true)
{
SetPosition(NewPosition);
}
}
else
{
SetPosition(NewPosition);
}
}
void Trainer::Pause()
{
for (int i = 0; i < NUM_DIRECTIONS; i++)
{
m_Animations[i]->Pause();
}
}
void Trainer::Resume()
{
for (int i = 0; i < NUM_DIRECTIONS; i++)
{
m_Animations[i]->Resume();
}
}
void Trainer::SetStop(bool StopPlayer)
{
if (m_Stop != StopPlayer)
{
m_Stop = StopPlayer;
}
}
void Trainer::OnEvent(Event * anEvent)
{
DoorEvent* e = (DoorEvent*)anEvent;
if (e->GetDoorType() == 11)
{
myDirection = SpriteWalkUp;
SetPosition(m_pGame->GetSceneManager()->GetActiveScene()->GetPlayerStart());
PlayerTransition();
}
if (e->GetDoorType() == 10)
{
myDirection = SpriteWalkDown;
SetPosition(m_pGame->GetSceneManager()->GetActiveScene()->GetPlayerStart());
PlayerTransition();
}
}
void Trainer::PlayerTransition()
{
m_InTransition = true;
aTransitionDestination = GetPosition() + vec2(DIRECTIONVECTOR[myDirection] * (TILESIZE / 4));
}
SpriteDirection Trainer::GetMyDirection()
{
return myDirection;
}
bool Trainer::CheckForCollision(vec2 playerNewPosition)
{
//Get the location of each point of collision on the player and then truncate it to a row and column
ivec2 OriginIndex = ivec2((playerNewPosition.x / TILESIZE), ((playerNewPosition.y - 0.3f) / TILESIZE));
ivec2 TopLeftIndex = ivec2((playerNewPosition.x / TILESIZE), (((playerNewPosition.y - 0.5f) + (TILESIZE / 2)) / TILESIZE));
ivec2 TopRightIndex = ivec2(((playerNewPosition.x + (TILESIZE / 2)) / TILESIZE), (((playerNewPosition.y - 0.5f) + (TILESIZE / 2)) / TILESIZE));
ivec2 BottomRightIndex = ivec2(((playerNewPosition.x + (TILESIZE / 2)) / TILESIZE), ((playerNewPosition.y - 0.3f) / TILESIZE));
//Check each index for whether the tile it lands on is walkable
bool CheckOrigin = m_pGame->GetTileMap()->GetTileAtPlayer(OriginIndex);
bool CheckTopLeft = m_pGame->GetTileMap()->GetTileAtPlayer(TopLeftIndex);
bool CheckTopRight = m_pGame->GetTileMap()->GetTileAtPlayer(TopRightIndex);
bool CheckBottomRight = m_pGame->GetTileMap()->GetTileAtPlayer(BottomRightIndex);
//If all the point land on walkable tile return true else return false
bool Collision = (CheckOrigin && CheckTopLeft && CheckTopRight && CheckBottomRight);
return Collision;
}
| 23.429787 | 144 | 0.689248 | Crewbee |
67bee141c7cf9e3b007eac22c03c6430698db2f2 | 4,104 | cxx | C++ | TRD/TRDbase/AliTRDUshortInfo.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | TRD/TRDbase/AliTRDUshortInfo.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | TRD/TRDbase/AliTRDUshortInfo.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id: AliTRDUshortInfo.cxx 27946 2008-08-13 15:26:24Z cblume $ */
///////////////////////////////////////////////////////////////////////////////
// //
// Calibration base class for a single ROC //
// Contains one UShort_t value per pad //
// However, values are set and get as float, there are stored internally as //
// (UShort_t) value * 10000 //
// //
///////////////////////////////////////////////////////////////////////////////
#include "AliTRDUshortInfo.h"
ClassImp(AliTRDUshortInfo)
//_____________________________________________________________________________
AliTRDUshortInfo::AliTRDUshortInfo()
:TObject()
,fSize(0)
,fData(0)
{
//
// Default constructor
//
}
//_____________________________________________________________________________
AliTRDUshortInfo::AliTRDUshortInfo(Int_t n)
:TObject()
,fSize(n)
,fData(0)
{
//
// Constructor that initializes a given size
//
fData = new UShort_t[fSize];
for(Int_t k = 0; k < fSize; k++){
fData[k] = 0;
}
}
//_____________________________________________________________________________
AliTRDUshortInfo::AliTRDUshortInfo(const AliTRDUshortInfo &c)
:TObject(c)
,fSize(c.fSize)
,fData(0)
{
//
// AliTRDUshortInfo copy constructor
//
Int_t iBin = 0;
fData = new UShort_t[fSize];
for (iBin = 0; iBin < fSize; iBin++) {
fData[iBin] = ((AliTRDUshortInfo &) c).fData[iBin];
}
}
//_____________________________________________________________________________
AliTRDUshortInfo::~AliTRDUshortInfo()
{
//
// AliTRDUshortInfo destructor
//
if (fData) {
delete [] fData;
fData = 0;
}
}
//_____________________________________________________________________________
AliTRDUshortInfo &AliTRDUshortInfo::operator=(const AliTRDUshortInfo &c)
{
//
// Assignment operator
//
if (this == &c) {
return *this;
}
fSize = c.fSize;
if (fData) {
delete [] fData;
}
fData = new UShort_t[fSize];
for (Int_t iBin = 0; iBin < fSize; iBin++) {
fData[iBin] = c.fData[iBin];
}
return *this;
}
//_____________________________________________________________________________
void AliTRDUshortInfo::Copy(TObject &c) const
{
//
// Copy function
//
Int_t iBin = 0;
((AliTRDUshortInfo &) c).fSize = fSize;
if (((AliTRDUshortInfo &) c).fData) delete [] ((AliTRDUshortInfo &) c).fData;
((AliTRDUshortInfo &) c).fData = new UShort_t[fSize];
for (iBin = 0; iBin < fSize; iBin++) {
((AliTRDUshortInfo &) c).fData[iBin] = fData[iBin];
}
TObject::Copy(c);
}
//_____________________________________________________________________________
void AliTRDUshortInfo::SetSize(Int_t n)
{
//
// Set the size
//
if(fData) delete [] fData;
fData = new UShort_t[n];
fSize = n;
}
| 27 | 79 | 0.560916 | AllaMaevskaya |
67bf9fd281c5a33d46fc6ad91bcc93eba4fd8984 | 497 | hpp | C++ | src/ipmiblob/test/crc_mock.hpp | openbmc/ipmi-blob-tool | d46530fd76038ba22298155047e07f14f7f8793f | [
"Apache-2.0"
] | null | null | null | src/ipmiblob/test/crc_mock.hpp | openbmc/ipmi-blob-tool | d46530fd76038ba22298155047e07f14f7f8793f | [
"Apache-2.0"
] | null | null | null | src/ipmiblob/test/crc_mock.hpp | openbmc/ipmi-blob-tool | d46530fd76038ba22298155047e07f14f7f8793f | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <cstdint>
#include <vector>
#include <gmock/gmock.h>
namespace ipmiblob
{
class CrcInterface
{
public:
virtual ~CrcInterface() = default;
virtual std::uint16_t
generateCrc(const std::vector<std::uint8_t>& data) const = 0;
};
class CrcMock : public CrcInterface
{
public:
virtual ~CrcMock() = default;
MOCK_METHOD(std::uint16_t, generateCrc, (const std::vector<std::uint8_t>&),
(const, override));
};
} // namespace ipmiblob
| 17.137931 | 79 | 0.65996 | openbmc |
67c2ed22ce772cf5cae511a18773d95cee84490c | 9,458 | cpp | C++ | cpp/atomsciflow/src/atomsciflow/abinit/variable_v1.cpp | DeqiTang/pymatflow | bd8776feb40ecef0e6704ee898d9f42ded3b0186 | [
"MIT"
] | 6 | 2020-03-06T16:13:08.000Z | 2022-03-09T07:53:34.000Z | cpp/atomsciflow/src/atomsciflow/abinit/variable_v1.cpp | DeqiTang/pymatflow | bd8776feb40ecef0e6704ee898d9f42ded3b0186 | [
"MIT"
] | 1 | 2021-10-02T02:23:08.000Z | 2021-11-08T13:29:37.000Z | cpp/atomsciflow/src/atomsciflow/abinit/variable_v1.cpp | DeqiTang/pymatflow | bd8776feb40ecef0e6704ee898d9f42ded3b0186 | [
"MIT"
] | 1 | 2021-07-10T16:28:14.000Z | 2021-07-10T16:28:14.000Z | /************************************************************************
> File Name: variable_v1.cpp
> Author: deqi
> Mail: deqi_tang@163.com
> Created Time: Sat 30 Jan 2021 01:11:54 PM CST
************************************************************************/
//#include "atomsciflow/abinit/utils.h"
#include "atomsciflow/abinit/variable_v1.h"
#include <string>
//#include <vector>
namespace atomsciflow {
using namespace utils;
// inline functions
//
inline std::string to_string_same_line(const AbinitVariableV1& var, std::string indent, int n) {
if (false == var.status) {
return "";
}
std::string out = "";
if (0 == var.value.size()) {
return out + var.key;
}
if (1 == var.value.size()) {
if (1 == var.value[0].size()) {
out += indent + var.key + n_to_string(n) + " " + var.value[0][0];
} else {
out += indent + var.key + n_to_string(n);
for (auto item : var.value[0]) {
out += " " + item;
}
}
} else {
out += indent + var.key + n_to_string(n);
for (auto val : var.value[0]) {
out += " " + val;
}
out += "\n";
for (int row = 1; row < var.value.size() - 1; ++row) {
out += indent;
for (auto val : var.value[row]) {
out += " " + val;
}
out += "\n";
}
out += indent;
for (auto val : var.value[var.value.size()-1]) {
out += " " + val;
}
}
return out;
}
inline std::string to_string_second_line(const AbinitVariableV1& var, std::string indent, int n) {
if (false == var.status) {
return "";
}
std::string out = "";
if (0 == var.value.size()) {
return out + var.key;
}
if (1 == var.value.size()) {
if (1 == var.value[0].size()) {
out += indent + var.key + n_to_string(n) + " " + var.value[0][0];
} else {
out += indent + var.key + n_to_string(n) + "\n";
out += indent;
for (auto item : var.value[0]) {
out += " " + item;
}
}
} else {
out += indent + var.key + n_to_string(n) + "\n";
for (auto row : var.value) {
out += indent;
for (auto val : row) {
out += " " + val;
}
out += "\n";
}
}
return out;
}
void AbinitVariableV1::set(std::string key, int value) {
this->key = key;
this->value.clear();
this->value.push_back(std::vector<std::string>{std::to_string(value)});
}
void AbinitVariableV1::set(std::string key, double value) {
this->key = key;
this->value.clear();
this->value.push_back(std::vector<std::string>{std::to_string(value)});
}
void AbinitVariableV1::set(std::string key, std::string value) {
this->key = key;
this->value.clear();
this->value.push_back(std::vector<std::string>{value});
}
void AbinitVariableV1::set(std::string key, std::vector<int> value) {
this->key = key;
this->value.clear();
std::vector<std::string> vec_str;
for (auto& i : value) {
vec_str.push_back(std::to_string(i));
}
this->value.push_back(vec_str);
}
void AbinitVariableV1::set(std::string key, std::vector<double> value) {
this->key = key;
this->value.clear();
std::vector<std::string> vec_str;
for (auto& i : value) {
vec_str.push_back(std::to_string(i));
}
this->value.push_back(vec_str);
}
void AbinitVariableV1::set(std::string key, std::vector<std::string> value) {
this->key = key;
this->value.clear();
std::vector<std::string> vec_str;
for (auto& val : value) {
vec_str.push_back(val);
}
this->value.push_back(vec_str);
}
void AbinitVariableV1::set(std::string key, std::vector<std::vector<int> > value) {
this->key = key;
this->value.clear();
std::vector<std::string> vec_str;
for (auto& row : value) {
vec_str.clear();
for (auto& val : row) {
vec_str.push_back(std::to_string(val));
}
this->value.push_back(vec_str);
}
}
void AbinitVariableV1::set(std::string key, std::vector<std::vector<double> > value) {
this->key = key;
this->value.clear();
std::vector<std::string> vec_str;
for (auto& row : value) {
vec_str.clear();
for (auto& val : row) {
vec_str.push_back(std::to_string(val));
}
this->value.push_back(vec_str);
}
}
void AbinitVariableV1::set(std::string key, std::vector<std::vector<std::string> > value) {
this->key = key;
this->value.clear();
std::vector<std::string> vec_str;
for (auto& row : value) {
vec_str.clear();
for (auto& val : row) {
vec_str.push_back(val);
}
this->value.push_back(vec_str);
}
}
void AbinitVariableV1::to(int& value) {
value = std::atoi(this->value[0][0].c_str());
}
void AbinitVariableV1::to(double& value) {
value = std::atof(this->value[0][0].c_str());
}
void AbinitVariableV1::to(std::string& value) {
value = this->value[0][0];
}
void AbinitVariableV1::to(std::vector<int>& value) {
value.clear();
for (auto& val : this->value[0]) {
value.push_back(std::atoi(val.c_str()));
}
}
void AbinitVariableV1::to(std::vector<double>& value) {
value.clear();
for (auto& val : this->value[0]) {
value.push_back(std::atof(val.c_str()));
}
}
void AbinitVariableV1::to(std::vector<std::string>& value) {
value.clear();
//for (auto& val : this->value[0]) {
// value.push_back(val);
//}
value = this->value[0];
}
void AbinitVariableV1::to(std::vector<std::vector<int>>& value) {
value.clear();
std::vector<int> vec_int;
for (auto& row : this->value) {
vec_int.clear();
for (auto& val : row) {
vec_int.push_back(std::atoi(val.c_str()));
}
value.push_back(vec_int);
}
}
void AbinitVariableV1::to(std::vector<std::vector<double>>& value) {
value.clear();
std::vector<double> vec_double;
for (auto& row : this->value) {
vec_double.clear();
for (auto& val : row) {
vec_double.push_back(std::atof(val.c_str()));
}
value.push_back(vec_double);
}
}
void AbinitVariableV1::to(std::vector<std::vector<std::string>>& value) {
value.clear();
//std::vector<std::string> vec_str;
//for (auto& row : this->value) {
// vec_double.clear();
// for (auto& val : row) {
// vec_double.push_back(val);
// }
// value.push_back(vec_str);
//}
value = this->value;
}
std::string AbinitVariableV1::to_string() {
if (false == this->status) {
return "";
}
return this->to_string(0);
}
std::string AbinitVariableV1::to_string(int n) {
if (false == this->status) {
return "";
}
std::string out = "";
if (9 == this->value.size()) {
return out + this->key;
}
if (this->value.size() == 1) {
if (this->value[0].size() == 1) {
out += this->key + n_to_string(n) + " " + this->value[0][0];
} else {
out += this->key + n_to_string(n) + "\n";
for (auto item : this->value[0]) {
out += " " + item;
}
}
} else {
out += this->key + n_to_string(n) + "\n";
for (auto row : this->value) {
for (auto val : row) {
out += " " + val;
}
out += "\n";
}
}
return out;
}
std::string AbinitVariableV1::to_string(std::string layout, std::string indent) {
if (false == this->status) {
return "";
}
return this->to_string(layout, indent, 0);
}
std::string AbinitVariableV1::to_string(std::string layout, std::string indent, int n) {
/*
* layout:
* "same-line";
* "second-line"''
*/
if (false == this->status) {
return "";
}
if ("same-line" == layout) {
return to_string_same_line(*this, indent, n);
} else if ("second-line" == layout) {
return to_string_second_line(*this, indent, n);
} else {
return to_string(n);
}
}
//
} // namespace atomsciflow
| 29.01227 | 102 | 0.457813 | DeqiTang |
67c46a12c1c714b253ed223108bbbf49550c0c9a | 3,744 | cc | C++ | algo/acm/codeforces/1-14/2b.cc | seckcoder/lang-learn | 1e0d6f412bbd7f89b1af00293fd907ddb3c1b571 | [
"Unlicense"
] | 1 | 2017-10-14T04:23:45.000Z | 2017-10-14T04:23:45.000Z | algo/acm/codeforces/1-14/2b.cc | seckcoder/lang-learn | 1e0d6f412bbd7f89b1af00293fd907ddb3c1b571 | [
"Unlicense"
] | null | null | null | algo/acm/codeforces/1-14/2b.cc | seckcoder/lang-learn | 1e0d6f412bbd7f89b1af00293fd907ddb3c1b571 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <string>
#include <iomanip>
#include <cmath>
#include <map>
#include <set>
using std::cout;
using std::endl;
using std::vector;
using std::set;
using std::cin;
using std::string;
using std::map;
#define PI 3.14159265359
#define N 1000
#define M 2*N+1
int fact2_min_dp[N][N];
int fact5_min_dp[N][N];
typedef struct Point {
int x, y;
};
// p is prime
int fact(int v, int p) {
int c = 0;
while ( v % p == 0 ) {
v = v / p;
c += 1;
}
return c;
}
int fact5(int v) {
return fact(v, 5);
}
int fact2(int v) {
return fact(v, 2);
}
int calcFact(int A[N][N], int n, int dp[N][N], int prime) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
dp[i][j] = fact(A[i][j], prime);
} else if (i == 0) {
dp[i][j] = fact(A[i][j], prime) + dp[i][j-1];
} else if (j == 0) {
dp[i][j] = fact(A[i][j], prime) + dp[i-1][j];
} else {
dp[i][j] = fact(A[i][j], prime) + std::min(dp[i][j-1], dp[i-1][j]);
}
}
}
return dp[n-1][n-1];
}
void lookForPath(int dp[N][N], int n, char *path) {
// look for path
int x = n-1, y = n-1;
int path_k = 2*n-3; // 2(n-1) elements + \0
path[path_k+1] = '\0';
while (x > 0 && y > 0) {
//cout << x << " " << y << " " << dp[x-1][y] << " " << dp[x][y-1] << " ";
if (dp[y-1][x] < dp[y][x-1]) {
path[path_k] = 'D';
path_k -= 1;
y = y-1;
} else {
path[path_k] = 'R';
path_k -= 1;
x = x - 1;
}
//cout << path[path_k+1] << " " << endl;
}
while (x > 0) {
path[path_k] = 'R';
path_k -= 1;
x -= 1;
}
while (y > 0) {
path[path_k] = 'D';
path_k -= 1;
y -= 1;
}
}
int calcFactBy2Min(int A[N][N], int n, int dp[N][N]) {
return calcFact(A, n, dp, 2);
}
int calcFactBy5Min(int A[N][N], int n, int dp[N][N]) {
return calcFact(A, n, dp, 5);
}
void pathThroughZero(const Point &zero_pos, int n, char *path) {
int path_k = 0;
for(int i = 0; i < zero_pos.x; i++) {
path[path_k] = 'R';
path_k += 1;
}
for(int i = 0; i < n-1; i++) {
path[path_k] = 'D';
path_k += 1;
}
for(int i = zero_pos.x; i < n-1; i++) {
path[path_k] = 'R';
path_k += 1;
}
path[path_k] = '\0';
}
void print_dp(int dp[][N], int n) {
for(int i = 0 ; i < n ;i++) {
for(int j = 0 ; j < n ;j++) {
cout << dp[i][j] << " ";
}
cout << endl;
}
}
void solve(int A[N][N], int n, bool has_zero, const Point &zero_pos) {
//char fact2_min_path[M], fact5_min_path[M];
char path[M];
int least_trailing_zero_num;
//cout << endl;
calcFactBy2Min(A, n, fact2_min_dp);
//print_dp(fact2_min_dp, n);
//cout << endl;
calcFactBy5Min(A, n, fact5_min_dp);
/*print_dp(fact5_min_dp, n);
cout << endl;*/
if (fact2_min_dp[n-1][n-1] < fact5_min_dp[n-1][n-1]) {
lookForPath(fact2_min_dp, n, path);
least_trailing_zero_num = fact2_min_dp[n-1][n-1];
} else {
lookForPath(fact5_min_dp, n, path);
least_trailing_zero_num = fact5_min_dp[n-1][n-1];
}
if (has_zero && least_trailing_zero_num > 1) {
pathThroughZero(zero_pos, n, path);
cout << 1 << "\n" << path << endl;
} else {
cout << least_trailing_zero_num << "\n" << path << endl;
}
}
int main(int argc, const char *argv[])
{
int A[N][N];
int n;
cin >> n;
bool has_zero = false;
Point zero_pos;
// ---> x(j:0->n);
// |
// |
// |
// V y (i:0->n);
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
cin >> A[i][j];
if (A[i][j] == 0) {
A[i][j] = 10;
has_zero = true;
zero_pos.x = j;
zero_pos.y = i;
}
}
}
solve(A, n, has_zero, zero_pos);
return 0;
}
| 20.571429 | 77 | 0.497062 | seckcoder |
67c481fe1199d336a5cfdd36015c7ab76c7987bd | 23,649 | cpp | C++ | src/libSBML/src/sbml/packages/multi/sbml/InSpeciesTypeBond.cpp | copasi/copasi-dependencies | c01dd455c843522375c32c2989aa8675f59bb810 | [
"Unlicense"
] | 5 | 2015-04-16T14:27:38.000Z | 2021-11-30T14:54:39.000Z | src/libSBML/src/sbml/packages/multi/sbml/InSpeciesTypeBond.cpp | copasi/copasi-dependencies | c01dd455c843522375c32c2989aa8675f59bb810 | [
"Unlicense"
] | 8 | 2017-05-30T16:58:39.000Z | 2022-02-22T16:51:34.000Z | src/libSBML/src/sbml/packages/multi/sbml/InSpeciesTypeBond.cpp | copasi/copasi-dependencies | c01dd455c843522375c32c2989aa8675f59bb810 | [
"Unlicense"
] | 7 | 2016-05-29T08:12:59.000Z | 2019-05-02T13:39:25.000Z | /**
* @file: InSpeciesTypeBond.cpp
* @brief: Implementation of the InSpeciesTypeBond class
* @author: SBMLTeam
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2020 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. University of Heidelberg, Heidelberg, Germany
* 3. University College London, London, UK
*
* Copyright (C) 2009-2013 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
*
* Copyright (C) 2006-2008 by the California Institute of Technology,
* Pasadena, CA, USA
*
* Copyright (C) 2002-2005 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. Japan Science and Technology Agency, Japan
*
* 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. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* ------------------------------------------------------------------------ -->
*/
#include <sbml/packages/multi/sbml/InSpeciesTypeBond.h>
#include <sbml/packages/multi/validator/MultiSBMLError.h>
using namespace std;
#ifdef __cplusplus
LIBSBML_CPP_NAMESPACE_BEGIN
/*
* Creates a new InSpeciesTypeBond with the given level, version, and package version.
*/
InSpeciesTypeBond::InSpeciesTypeBond (unsigned int level, unsigned int version, unsigned int pkgVersion)
: SBase(level, version)
//// ,mId ("")
//// ,mName ("")
,mBindingSite1 ("")
,mBindingSite2 ("")
{
// set an SBMLNamespaces derived object of this package
setSBMLNamespacesAndOwn(new MultiPkgNamespaces(level, version, pkgVersion));
}
/*
* Creates a new InSpeciesTypeBond with the given MultiPkgNamespaces object.
*/
InSpeciesTypeBond::InSpeciesTypeBond (MultiPkgNamespaces* multins)
: SBase(multins)
//// ,mId ("")
//// ,mName ("")
,mBindingSite1 ("")
,mBindingSite2 ("")
{
// set the element namespace of this object
setElementNamespace(multins->getURI());
// load package extensions bound with this object (if any)
loadPlugins(multins);
}
/*
* Copy constructor for InSpeciesTypeBond.
*/
InSpeciesTypeBond::InSpeciesTypeBond (const InSpeciesTypeBond& orig)
: SBase(orig)
// , mId ( orig.mId)
// , mName ( orig.mName)
, mBindingSite1 ( orig.mBindingSite1)
, mBindingSite2 ( orig.mBindingSite2)
{
}
/*
* Assignment for InSpeciesTypeBond.
*/
InSpeciesTypeBond&
InSpeciesTypeBond::operator=(const InSpeciesTypeBond& rhs)
{
if (&rhs != this)
{
SBase::operator=(rhs);
mId = rhs.mId;
mName = rhs.mName;
mBindingSite1 = rhs.mBindingSite1;
mBindingSite2 = rhs.mBindingSite2;
}
return *this;
}
/*
* Clone for InSpeciesTypeBond.
*/
InSpeciesTypeBond*
InSpeciesTypeBond::clone () const
{
return new InSpeciesTypeBond(*this);
}
/*
* Destructor for InSpeciesTypeBond.
*/
InSpeciesTypeBond::~InSpeciesTypeBond ()
{
}
/*
* Returns the value of the "id" attribute of this InSpeciesTypeBond.
*/
const std::string&
InSpeciesTypeBond::getId() const
{
return mId;
}
/*
* Returns the value of the "name" attribute of this InSpeciesTypeBond.
*/
const std::string&
InSpeciesTypeBond::getName() const
{
return mName;
}
/*
* Returns the value of the "bindingSite1" attribute of this InSpeciesTypeBond.
*/
const std::string&
InSpeciesTypeBond::getBindingSite1() const
{
return mBindingSite1;
}
/*
* Returns the value of the "bindingSite2" attribute of this InSpeciesTypeBond.
*/
const std::string&
InSpeciesTypeBond::getBindingSite2() const
{
return mBindingSite2;
}
/*
* Returns true/false if id is set.
*/
bool
InSpeciesTypeBond::isSetId() const
{
return (mId.empty() == false);
}
/*
* Returns true/false if name is set.
*/
bool
InSpeciesTypeBond::isSetName() const
{
return (mName.empty() == false);
}
/*
* Returns true/false if bindingSite1 is set.
*/
bool
InSpeciesTypeBond::isSetBindingSite1() const
{
return (mBindingSite1.empty() == false);
}
/*
* Returns true/false if bindingSite2 is set.
*/
bool
InSpeciesTypeBond::isSetBindingSite2() const
{
return (mBindingSite2.empty() == false);
}
/*
* Sets id and returns value indicating success.
*/
int
InSpeciesTypeBond::setId(const std::string& id)
{
return SyntaxChecker::checkAndSetSId(id, mId);
}
/*
* Sets name and returns value indicating success.
*/
int
InSpeciesTypeBond::setName(const std::string& name)
{
mName = name;
return LIBSBML_OPERATION_SUCCESS;
}
/*
* Sets bindingSite1 and returns value indicating success.
*/
int
InSpeciesTypeBond::setBindingSite1(const std::string& bindingSite1)
{
if (!(SyntaxChecker::isValidInternalSId(bindingSite1)))
{
return LIBSBML_INVALID_ATTRIBUTE_VALUE;
}
else
{
mBindingSite1 = bindingSite1;
return LIBSBML_OPERATION_SUCCESS;
}
}
/*
* Sets bindingSite2 and returns value indicating success.
*/
int
InSpeciesTypeBond::setBindingSite2(const std::string& bindingSite2)
{
if (!(SyntaxChecker::isValidInternalSId(bindingSite2)))
{
return LIBSBML_INVALID_ATTRIBUTE_VALUE;
}
else
{
mBindingSite2 = bindingSite2;
return LIBSBML_OPERATION_SUCCESS;
}
}
/*
* Unsets id and returns value indicating success.
*/
int
InSpeciesTypeBond::unsetId()
{
mId.erase();
if (mId.empty() == true)
{
return LIBSBML_OPERATION_SUCCESS;
}
else
{
return LIBSBML_OPERATION_FAILED;
}
}
/*
* Unsets name and returns value indicating success.
*/
int
InSpeciesTypeBond::unsetName()
{
mName.erase();
if (mName.empty() == true)
{
return LIBSBML_OPERATION_SUCCESS;
}
else
{
return LIBSBML_OPERATION_FAILED;
}
}
/*
* Unsets bindingSite1 and returns value indicating success.
*/
int
InSpeciesTypeBond::unsetBindingSite1()
{
mBindingSite1.erase();
if (mBindingSite1.empty() == true)
{
return LIBSBML_OPERATION_SUCCESS;
}
else
{
return LIBSBML_OPERATION_FAILED;
}
}
/*
* Unsets bindingSite2 and returns value indicating success.
*/
int
InSpeciesTypeBond::unsetBindingSite2()
{
mBindingSite2.erase();
if (mBindingSite2.empty() == true)
{
return LIBSBML_OPERATION_SUCCESS;
}
else
{
return LIBSBML_OPERATION_FAILED;
}
}
/*
* rename attributes that are SIdRefs or instances in math
*/
void
InSpeciesTypeBond::renameSIdRefs(const std::string& oldid, const std::string& newid)
{
SBase::renameSIdRefs(oldid, newid);
if (isSetBindingSite1() == true && mBindingSite1 == oldid)
{
setBindingSite1(newid);
}
if (isSetBindingSite2() == true && mBindingSite2 == oldid)
{
setBindingSite2(newid);
}
}
/*
* Returns the XML element name of this object
*/
const std::string&
InSpeciesTypeBond::getElementName () const
{
static const string name = "inSpeciesTypeBond";
return name;
}
/*
* Returns the libSBML type code for this SBML object.
*/
int
InSpeciesTypeBond::getTypeCode () const
{
return SBML_MULTI_IN_SPECIES_TYPE_BOND;
}
/*
* check if all the required attributes are set
*/
bool
InSpeciesTypeBond::hasRequiredAttributes () const
{
bool allPresent = true;
if (isSetBindingSite1() == false)
allPresent = false;
if (isSetBindingSite2() == false)
allPresent = false;
return allPresent;
}
/** @cond doxygenLibsbmlInternal */
/*
* write contained elements
*/
void
InSpeciesTypeBond::writeElements (XMLOutputStream& stream) const
{
SBase::writeElements(stream);
SBase::writeExtensionElements(stream);
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Accepts the given SBMLVisitor.
*/
bool
InSpeciesTypeBond::accept (SBMLVisitor& v) const
{
return v.visit(*this);
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Sets the parent SBMLDocument.
*/
void
InSpeciesTypeBond::setSBMLDocument (SBMLDocument* d)
{
SBase::setSBMLDocument(d);
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Enables/Disables the given package with this element.
*/
void
InSpeciesTypeBond::enablePackageInternal(const std::string& pkgURI,
const std::string& pkgPrefix, bool flag)
{
SBase::enablePackageInternal(pkgURI, pkgPrefix, flag);
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Get the list of expected attributes for this element.
*/
void
InSpeciesTypeBond::addExpectedAttributes(ExpectedAttributes& attributes)
{
SBase::addExpectedAttributes(attributes);
attributes.add("id");
attributes.add("name");
attributes.add("bindingSite1");
attributes.add("bindingSite2");
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Read values from the given XMLAttributes set into their specific fields.
*/
void
InSpeciesTypeBond::readAttributes (const XMLAttributes& attributes,
const ExpectedAttributes& expectedAttributes)
{
const unsigned int sbmlLevel = getLevel ();
const unsigned int sbmlVersion = getVersion();
unsigned int numErrs;
/* look to see whether an unknown attribute error was logged
* during the read of the listOfInSpeciesTypeBonds - which will have
* happened immediately prior to this read
*/
ListOfInSpeciesTypeBonds * parentListOf =
static_cast<ListOfInSpeciesTypeBonds*>(getParentSBMLObject());
if (getErrorLog() != NULL &&
parentListOf->size() < 2)
{
numErrs = getErrorLog()->getNumErrors();
for (int n = numErrs-1; n >= 0; n--)
{
if (getErrorLog()->getError(n)->getErrorId() == UnknownPackageAttribute)
{
const std::string details =
getErrorLog()->getError(n)->getMessage();
getErrorLog()->remove(UnknownPackageAttribute);
getErrorLog()->logPackageError("multi", MultiLofInSptBnds_AllowedAtts,
getPackageVersion(), sbmlLevel, sbmlVersion, details,
parentListOf->getLine(), parentListOf->getColumn());
}
else if (getErrorLog()->getError(n)->getErrorId() == UnknownCoreAttribute)
{
const std::string details =
getErrorLog()->getError(n)->getMessage();
getErrorLog()->remove(UnknownCoreAttribute);
getErrorLog()->logPackageError("multi", MultiLofInSptBnds_AllowedAtts,
getPackageVersion(), sbmlLevel, sbmlVersion, details,
parentListOf->getLine(), parentListOf->getColumn());
}
}
}
SBase::readAttributes(attributes, expectedAttributes);
// look to see whether an unknown attribute error was logged
if (getErrorLog() != NULL)
{
numErrs = getErrorLog()->getNumErrors();
for (int n = numErrs-1; n >= 0; n--)
{
if (getErrorLog()->getError(n)->getErrorId() == UnknownPackageAttribute)
{
const std::string details =
getErrorLog()->getError(n)->getMessage();
getErrorLog()->remove(UnknownPackageAttribute);
getErrorLog()->logPackageError("multi", MultiInSptBnd_AllowedMultiAtts,
getPackageVersion(), sbmlLevel, sbmlVersion, details,
getLine(), getColumn());
}
else if (getErrorLog()->getError(n)->getErrorId() == UnknownCoreAttribute)
{
const std::string details =
getErrorLog()->getError(n)->getMessage();
getErrorLog()->remove(UnknownCoreAttribute);
getErrorLog()->logPackageError("multi", MultiInSptBnd_AllowedCoreAtts,
getPackageVersion(), sbmlLevel, sbmlVersion, details,
getLine(), getColumn());
}
}
}
bool assigned = false;
//
// id SId ( use = "optional" )
//
assigned = attributes.readInto("id", mId);
if (assigned == true)
{
// check string is not empty and correct syntax
if (mId.empty() == true)
{
logEmptyString(mId, getLevel(), getVersion(), "<InSpeciesTypeBond>");
}
else if (SyntaxChecker::isValidSBMLSId(mId) == false && getErrorLog() != NULL)
{
std::string details = "The syntax of the attribute id='" + mId + "' does not conform.";
getErrorLog()->logPackageError("multi", MultiInvSIdSyn,
getPackageVersion(), sbmlLevel, sbmlVersion, details,
getLine(), getColumn());
}
}
//
// name string ( use = "optional" )
//
assigned = attributes.readInto("name", mName);
if (assigned == true)
{
// check string is not empty
if (mName.empty() == true)
{
logEmptyString(mName, getLevel(), getVersion(), "<InSpeciesTypeBond>");
}
}
//
// bindingSite1 SIdRef ( use = "required" )
//
assigned = attributes.readInto("bindingSite1", mBindingSite1);
if (assigned == true)
{
// check string is not empty and correct syntax
if (mBindingSite1.empty() == true)
{
logEmptyString(mBindingSite1, getLevel(), getVersion(), "<InSpeciesTypeBond>");
}
else if (SyntaxChecker::isValidSBMLSId(mBindingSite1) == false && getErrorLog() != NULL)
{
std::string details = "The syntax of the attribute bindingSite1='" + mBindingSite1 + "' does not conform.";
getErrorLog()->logPackageError("multi", MultiInvSIdSyn,
getPackageVersion(), sbmlLevel, sbmlVersion, details,
getLine(), getColumn());
}
}
else
{
std::string message = "Multi attribute 'bindingSite1' is missing.";
getErrorLog()->logPackageError("multi", MultiInSptBnd_AllowedMultiAtts,
getPackageVersion(), sbmlLevel, sbmlVersion, message,
getLine(), getColumn());
}
//
// bindingSite2 SIdRef ( use = "required" )
//
assigned = attributes.readInto("bindingSite2", mBindingSite2);
if (assigned == true)
{
// check string is not empty and correct syntax
if (mBindingSite2.empty() == true)
{
logEmptyString(mBindingSite2, getLevel(), getVersion(), "<InSpeciesTypeBond>");
}
else if (SyntaxChecker::isValidSBMLSId(mBindingSite2) == false && getErrorLog() != NULL)
{
std::string details = "The syntax of the attribute bindingSite2='" + mBindingSite2 + "' does not conform.";
getErrorLog()->logPackageError("multi", MultiInvSIdSyn,
getPackageVersion(), sbmlLevel, sbmlVersion, details,
getLine(), getColumn());
}
}
else
{
std::string message = "Multi attribute 'bindingSite2' is missing.";
getErrorLog()->logPackageError("multi", MultiInSptBnd_AllowedMultiAtts,
getPackageVersion(), sbmlLevel, sbmlVersion, message,
getLine(), getColumn());
}
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Write values of XMLAttributes to the output stream.
*/
void
InSpeciesTypeBond::writeAttributes (XMLOutputStream& stream) const
{
SBase::writeAttributes(stream);
if (isSetId() == true)
stream.writeAttribute("id", getPrefix(), mId);
if (isSetName() == true)
stream.writeAttribute("name", getPrefix(), mName);
if (isSetBindingSite1() == true)
stream.writeAttribute("bindingSite1", getPrefix(), mBindingSite1);
if (isSetBindingSite2() == true)
stream.writeAttribute("bindingSite2", getPrefix(), mBindingSite2);
SBase::writeExtensionAttributes(stream);
}
/** @endcond */
/*
* Constructor
*/
ListOfInSpeciesTypeBonds::ListOfInSpeciesTypeBonds(unsigned int level,
unsigned int version,
unsigned int pkgVersion)
: ListOf(level, version)
{
setSBMLNamespacesAndOwn(new MultiPkgNamespaces(level, version, pkgVersion));
}
/*
* Constructor
*/
ListOfInSpeciesTypeBonds::ListOfInSpeciesTypeBonds(MultiPkgNamespaces* multins)
: ListOf(multins)
{
setElementNamespace(multins->getURI());
}
/*
* Returns a deep copy of this ListOfInSpeciesTypeBonds
*/
ListOfInSpeciesTypeBonds*
ListOfInSpeciesTypeBonds::clone () const
{
return new ListOfInSpeciesTypeBonds(*this);
}
/*
* Get a InSpeciesTypeBond from the ListOfInSpeciesTypeBonds by index.
*/
InSpeciesTypeBond*
ListOfInSpeciesTypeBonds::get(unsigned int n)
{
return static_cast<InSpeciesTypeBond*>(ListOf::get(n));
}
/*
* Get a InSpeciesTypeBond from the ListOfInSpeciesTypeBonds by index.
*/
const InSpeciesTypeBond*
ListOfInSpeciesTypeBonds::get(unsigned int n) const
{
return static_cast<const InSpeciesTypeBond*>(ListOf::get(n));
}
/*
* Get a InSpeciesTypeBond from the ListOfInSpeciesTypeBonds by id.
*/
InSpeciesTypeBond*
ListOfInSpeciesTypeBonds::get(const std::string& sid)
{
return const_cast<InSpeciesTypeBond*>(
static_cast<const ListOfInSpeciesTypeBonds&>(*this).get(sid));
}
/*
* Get a InSpeciesTypeBond from the ListOfInSpeciesTypeBonds by id.
*/
const InSpeciesTypeBond*
ListOfInSpeciesTypeBonds::get(const std::string& sid) const
{
vector<SBase*>::const_iterator result;
result = find_if( mItems.begin(), mItems.end(), IdEq<InSpeciesTypeBond>(sid) );
return (result == mItems.end()) ? 0 : static_cast <InSpeciesTypeBond*> (*result);
}
/*
* Removes the nth InSpeciesTypeBond from this ListOfInSpeciesTypeBonds
*/
InSpeciesTypeBond*
ListOfInSpeciesTypeBonds::remove(unsigned int n)
{
return static_cast<InSpeciesTypeBond*>(ListOf::remove(n));
}
/*
* Removes the InSpeciesTypeBond from this ListOfInSpeciesTypeBonds with the given identifier
*/
InSpeciesTypeBond*
ListOfInSpeciesTypeBonds::remove(const std::string& sid)
{
SBase* item = NULL;
vector<SBase*>::iterator result;
result = find_if( mItems.begin(), mItems.end(), IdEq<InSpeciesTypeBond>(sid) );
if (result != mItems.end())
{
item = *result;
mItems.erase(result);
}
return static_cast <InSpeciesTypeBond*> (item);
}
/*
* Returns the XML element name of this object
*/
const std::string&
ListOfInSpeciesTypeBonds::getElementName () const
{
static const string name = "listOfInSpeciesTypeBonds";
return name;
}
/*
* Returns the libSBML type code for this SBML object.
*/
int
ListOfInSpeciesTypeBonds::getTypeCode () const
{
return SBML_LIST_OF;
}
/*
* Returns the libSBML type code for the objects in this LIST_OF.
*/
int
ListOfInSpeciesTypeBonds::getItemTypeCode () const
{
return SBML_MULTI_IN_SPECIES_TYPE_BOND;
}
/** @cond doxygenLibsbmlInternal */
/*
* Creates a new InSpeciesTypeBond in this ListOfInSpeciesTypeBonds
*/
SBase*
ListOfInSpeciesTypeBonds::createObject(XMLInputStream& stream)
{
const std::string& name = stream.peek().getName();
SBase* object = NULL;
if (name == "inSpeciesTypeBond")
{
MULTI_CREATE_NS(multins, getSBMLNamespaces());
object = new InSpeciesTypeBond(multins);
appendAndOwn(object);
delete multins;
}
return object;
}
/** @endcond */
/** @cond doxygenLibsbmlInternal */
/*
* Write the namespace for the Multi package.
*/
void
ListOfInSpeciesTypeBonds::writeXMLNS(XMLOutputStream& stream) const
{
XMLNamespaces xmlns;
std::string prefix = getPrefix();
if (prefix.empty())
{
XMLNamespaces* thisxmlns = getNamespaces();
if (thisxmlns && thisxmlns->hasURI(MultiExtension::getXmlnsL3V1V1()))
{
xmlns.add(MultiExtension::getXmlnsL3V1V1(),prefix);
}
}
stream << xmlns;
}
/** @endcond */
LIBSBML_EXTERN
InSpeciesTypeBond_t *
InSpeciesTypeBond_create(unsigned int level, unsigned int version,
unsigned int pkgVersion)
{
return new InSpeciesTypeBond(level, version, pkgVersion);
}
LIBSBML_EXTERN
void
InSpeciesTypeBond_free(InSpeciesTypeBond_t * istb)
{
if (istb != NULL)
delete istb;
}
LIBSBML_EXTERN
InSpeciesTypeBond_t *
InSpeciesTypeBond_clone(InSpeciesTypeBond_t * istb)
{
if (istb != NULL)
{
return static_cast<InSpeciesTypeBond_t*>(istb->clone());
}
else
{
return NULL;
}
}
LIBSBML_EXTERN
char *
InSpeciesTypeBond_getId(InSpeciesTypeBond_t * istb)
{
if (istb == NULL)
return NULL;
return istb->getId().empty() ? NULL : safe_strdup(istb->getId().c_str());
}
LIBSBML_EXTERN
char *
InSpeciesTypeBond_getName(InSpeciesTypeBond_t * istb)
{
if (istb == NULL)
return NULL;
return istb->getName().empty() ? NULL : safe_strdup(istb->getName().c_str());
}
LIBSBML_EXTERN
char *
InSpeciesTypeBond_getBindingSite1(InSpeciesTypeBond_t * istb)
{
if (istb == NULL)
return NULL;
return istb->getBindingSite1().empty() ? NULL : safe_strdup(istb->getBindingSite1().c_str());
}
LIBSBML_EXTERN
char *
InSpeciesTypeBond_getBindingSite2(InSpeciesTypeBond_t * istb)
{
if (istb == NULL)
return NULL;
return istb->getBindingSite2().empty() ? NULL : safe_strdup(istb->getBindingSite2().c_str());
}
LIBSBML_EXTERN
int
InSpeciesTypeBond_isSetId(InSpeciesTypeBond_t * istb)
{
return (istb != NULL) ? static_cast<int>(istb->isSetId()) : 0;
}
LIBSBML_EXTERN
int
InSpeciesTypeBond_isSetName(InSpeciesTypeBond_t * istb)
{
return (istb != NULL) ? static_cast<int>(istb->isSetName()) : 0;
}
LIBSBML_EXTERN
int
InSpeciesTypeBond_isSetBindingSite1(InSpeciesTypeBond_t * istb)
{
return (istb != NULL) ? static_cast<int>(istb->isSetBindingSite1()) : 0;
}
LIBSBML_EXTERN
int
InSpeciesTypeBond_isSetBindingSite2(InSpeciesTypeBond_t * istb)
{
return (istb != NULL) ? static_cast<int>(istb->isSetBindingSite2()) : 0;
}
LIBSBML_EXTERN
int
InSpeciesTypeBond_setId(InSpeciesTypeBond_t * istb, const char * id)
{
return (istb != NULL) ? istb->setId(id) : LIBSBML_INVALID_OBJECT;
}
LIBSBML_EXTERN
int
InSpeciesTypeBond_setName(InSpeciesTypeBond_t * istb, const char * name)
{
return (istb != NULL) ? istb->setName(name) : LIBSBML_INVALID_OBJECT;
}
LIBSBML_EXTERN
int
InSpeciesTypeBond_setBindingSite1(InSpeciesTypeBond_t * istb, const char * bindingSite1)
{
return (istb != NULL) ? istb->setBindingSite1(bindingSite1) : LIBSBML_INVALID_OBJECT;
}
LIBSBML_EXTERN
int
InSpeciesTypeBond_setBindingSite2(InSpeciesTypeBond_t * istb, const char * bindingSite2)
{
return (istb != NULL) ? istb->setBindingSite2(bindingSite2) : LIBSBML_INVALID_OBJECT;
}
LIBSBML_EXTERN
int
InSpeciesTypeBond_unsetId(InSpeciesTypeBond_t * istb)
{
return (istb != NULL) ? istb->unsetId() : LIBSBML_INVALID_OBJECT;
}
LIBSBML_EXTERN
int
InSpeciesTypeBond_unsetName(InSpeciesTypeBond_t * istb)
{
return (istb != NULL) ? istb->unsetName() : LIBSBML_INVALID_OBJECT;
}
LIBSBML_EXTERN
int
InSpeciesTypeBond_unsetBindingSite1(InSpeciesTypeBond_t * istb)
{
return (istb != NULL) ? istb->unsetBindingSite1() : LIBSBML_INVALID_OBJECT;
}
LIBSBML_EXTERN
int
InSpeciesTypeBond_unsetBindingSite2(InSpeciesTypeBond_t * istb)
{
return (istb != NULL) ? istb->unsetBindingSite2() : LIBSBML_INVALID_OBJECT;
}
LIBSBML_EXTERN
int
InSpeciesTypeBond_hasRequiredAttributes(InSpeciesTypeBond_t * istb)
{
return (istb != NULL) ? static_cast<int>(istb->hasRequiredAttributes()) : 0;
}
LIBSBML_EXTERN
InSpeciesTypeBond_t *
ListOfInSpeciesTypeBonds_getById(ListOf_t * lo, const char * sid)
{
if (lo == NULL)
return NULL;
return (sid != NULL) ? static_cast <ListOfInSpeciesTypeBonds *>(lo)->get(sid) : NULL;
}
LIBSBML_EXTERN
InSpeciesTypeBond_t *
ListOfInSpeciesTypeBonds_removeById(ListOf_t * lo, const char * sid)
{
if (lo == NULL)
return NULL;
return (sid != NULL) ? static_cast <ListOfInSpeciesTypeBonds *>(lo)->remove(sid) : NULL;
}
LIBSBML_CPP_NAMESPACE_END
#endif /*__cplusplus */
| 21.557885 | 113 | 0.687471 | copasi |
67c679ada7f5c2e8d2abfd8dc0dd3e79bd7377de | 23,992 | cpp | C++ | codes/algorithms/a_search/cpp/a_star.cpp | shuvamkumar/first-pr-Hacktoberfest--2019 | 39a4c2e64fca58ea530263f9c4f50cbf55aaf883 | [
"MIT"
] | 8 | 2019-10-09T18:55:05.000Z | 2020-09-18T05:44:00.000Z | codes/algorithms/a_search/cpp/a_star.cpp | shuvamkumar/first-pr-Hacktoberfest--2019 | 39a4c2e64fca58ea530263f9c4f50cbf55aaf883 | [
"MIT"
] | 2 | 2019-10-18T14:22:30.000Z | 2020-09-30T08:36:36.000Z | codes/algorithms/a_search/cpp/a_star.cpp | shuvamkumar/first-pr-Hacktoberfest--2019 | 39a4c2e64fca58ea530263f9c4f50cbf55aaf883 | [
"MIT"
] | 55 | 2019-10-09T18:11:17.000Z | 2021-02-01T18:06:20.000Z | // A C++ Program to implement A* Search Algorithm
#include <bits/stdc++.h>
using namespace std;
#define ROW 9
#define COL 10
// Creating a shortcut for int, int pair type
typedef pair<int, int> Pair;
// Creating a shortcut for pair<int, pair<int, int>> type
typedef pair<double, pair<int, int>> pPair;
// A structure to hold the neccesary parameters
struct cell
{
// Row and Column index of its parent
// Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1
int parent_i, parent_j;
// f = g + h
double f, g, h;
};
// A Utility Function to check whether given cell (row, col)
// is a valid cell or not.
bool isValid(int row, int col)
{
// Returns true if row number and column number
// is in range
return (row >= 0) && (row < ROW) &&
(col >= 0) && (col < COL);
}
// A Utility Function to check whether the given cell is
// blocked or not
bool isUnBlocked(int grid[][COL], int row, int col)
{
// Returns true if the cell is not blocked else false
if (grid[row][col] == 1)
return (true);
else
return (false);
}
// A Utility Function to check whether destination cell has
// been reached or not
bool isDestination(int row, int col, Pair dest)
{
if (row == dest.first && col == dest.second)
return (true);
else
return (false);
}
// A Utility Function to calculate the 'h' heuristics.
double calculateHValue(int row, int col, Pair dest)
{
// Return using the distance formula
return ((double)sqrt ((row-dest.first)*(row-dest.first)
+ (col-dest.second)*(col-dest.second)));
}
// A Utility Function to trace the path from the source
// to destination
void tracePath(cell cellDetails[][COL], Pair dest)
{
printf ("\nThe Path is ");
int row = dest.first;
int col = dest.second;
stack<Pair> Path;
while (!(cellDetails[row][col].parent_i == row
&& cellDetails[row][col].parent_j == col ))
{
Path.push (make_pair (row, col));
int temp_row = cellDetails[row][col].parent_i;
int temp_col = cellDetails[row][col].parent_j;
row = temp_row;
col = temp_col;
}
Path.push (make_pair (row, col));
while (!Path.empty())
{
pair<int,int> p = Path.top();
Path.pop();
printf("-> (%d,%d) ",p.first,p.second);
}
return;
}
// A Function to find the shortest path between
// a given source cell to a destination cell according
// to A* Search Algorithm
void aStarSearch(int grid[][COL], Pair src, Pair dest)
{
// If the source is out of range
if (isValid (src.first, src.second) == false)
{
printf ("Source is invalid\n");
return;
}
// If the destination is out of range
if (isValid (dest.first, dest.second) == false)
{
printf ("Destination is invalid\n");
return;
}
// Either the source or the destination is blocked
if (isUnBlocked(grid, src.first, src.second) == false ||
isUnBlocked(grid, dest.first, dest.second) == false)
{
printf ("Source or the destination is blocked\n");
return;
}
// If the destination cell is the same as source cell
if (isDestination(src.first, src.second, dest) == true)
{
printf ("We are already at the destination\n");
return;
}
// Create a closed list and initialise it to false which means
// that no cell has been included yet
// This closed list is implemented as a boolean 2D array
bool closedList[ROW][COL];
memset(closedList, false, sizeof (closedList));
// Declare a 2D array of structure to hold the details
//of that cell
cell cellDetails[ROW][COL];
int i, j;
for (i=0; i<ROW; i++)
{
for (j=0; j<COL; j++)
{
cellDetails[i][j].f = FLT_MAX;
cellDetails[i][j].g = FLT_MAX;
cellDetails[i][j].h = FLT_MAX;
cellDetails[i][j].parent_i = -1;
cellDetails[i][j].parent_j = -1;
}
}
// Initialising the parameters of the starting node
i = src.first, j = src.second;
cellDetails[i][j].f = 0.0;
cellDetails[i][j].g = 0.0;
cellDetails[i][j].h = 0.0;
cellDetails[i][j].parent_i = i;
cellDetails[i][j].parent_j = j;
/*
Create an open list having information as-
<f, <i, j>>
where f = g + h,
and i, j are the row and column index of that cell
Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1
This open list is implenented as a set of pair of pair.*/
set<pPair> openList;
// Put the starting cell on the open list and set its
// 'f' as 0
openList.insert(make_pair (0.0, make_pair (i, j)));
// We set this boolean value as false as initially
// the destination is not reached.
bool foundDest = false;
while (!openList.empty())
{
pPair p = *openList.begin();
// Remove this vertex from the open list
openList.erase(openList.begin());
// Add this vertex to the open list
i = p.second.first;
j = p.second.second;
closedList[i][j] = true;
/*
Generating all the 8 successor of this cell
N.W N N.E
\ | /
\ | /
W----Cell----E
/ | \
/ | \
S.W S S.E
Cell-->Popped Cell (i, j)
N --> North (i-1, j)
S --> South (i+1, j)
E --> East (i, j+1)
W --> West (i, j-1)
N.E--> North-East (i-1, j+1)
N.W--> North-West (i-1, j-1)
S.E--> South-East (i+1, j+1)
S.W--> South-West (i+1, j-1)*/
// To store the 'g', 'h' and 'f' of the 8 successors
double gNew, hNew, fNew;
//----------- 1st Successor (North) ------------
// Only process this cell if this is a valid one
if (isValid(i-1, j) == true)
{
// If the destination cell is the same as the
// current successor
if (isDestination(i-1, j, dest) == true)
{
// Set the Parent of the destination cell
cellDetails[i-1][j].parent_i = i;
cellDetails[i-1][j].parent_j = j;
printf ("The destination cell is found\n");
tracePath (cellDetails, dest);
foundDest = true;
return;
}
// If the successor is already on the closed
// list or if it is blocked, then ignore it.
// Else do the following
else if (closedList[i-1][j] == false &&
isUnBlocked(grid, i-1, j) == true)
{
gNew = cellDetails[i][j].g + 1.0;
hNew = calculateHValue (i-1, j, dest);
fNew = gNew + hNew;
// If it isn’t on the open list, add it to
// the open list. Make the current square
// the parent of this square. Record the
// f, g, and h costs of the square cell
// OR
// If it is on the open list already, check
// to see if this path to that square is better,
// using 'f' cost as the measure.
if (cellDetails[i-1][j].f == FLT_MAX ||
cellDetails[i-1][j].f > fNew)
{
openList.insert( make_pair(fNew,
make_pair(i-1, j)));
// Update the details of this cell
cellDetails[i-1][j].f = fNew;
cellDetails[i-1][j].g = gNew;
cellDetails[i-1][j].h = hNew;
cellDetails[i-1][j].parent_i = i;
cellDetails[i-1][j].parent_j = j;
}
}
}
//----------- 2nd Successor (South) ------------
// Only process this cell if this is a valid one
if (isValid(i+1, j) == true)
{
// If the destination cell is the same as the
// current successor
if (isDestination(i+1, j, dest) == true)
{
// Set the Parent of the destination cell
cellDetails[i+1][j].parent_i = i;
cellDetails[i+1][j].parent_j = j;
printf("The destination cell is found\n");
tracePath(cellDetails, dest);
foundDest = true;
return;
}
// If the successor is already on the closed
// list or if it is blocked, then ignore it.
// Else do the following
else if (closedList[i+1][j] == false &&
isUnBlocked(grid, i+1, j) == true)
{
gNew = cellDetails[i][j].g + 1.0;
hNew = calculateHValue(i+1, j, dest);
fNew = gNew + hNew;
// If it isn’t on the open list, add it to
// the open list. Make the current square
// the parent of this square. Record the
// f, g, and h costs of the square cell
// OR
// If it is on the open list already, check
// to see if this path to that square is better,
// using 'f' cost as the measure.
if (cellDetails[i+1][j].f == FLT_MAX ||
cellDetails[i+1][j].f > fNew)
{
openList.insert( make_pair (fNew, make_pair (i+1, j)));
// Update the details of this cell
cellDetails[i+1][j].f = fNew;
cellDetails[i+1][j].g = gNew;
cellDetails[i+1][j].h = hNew;
cellDetails[i+1][j].parent_i = i;
cellDetails[i+1][j].parent_j = j;
}
}
}
//----------- 3rd Successor (East) ------------
// Only process this cell if this is a valid one
if (isValid (i, j+1) == true)
{
// If the destination cell is the same as the
// current successor
if (isDestination(i, j+1, dest) == true)
{
// Set the Parent of the destination cell
cellDetails[i][j+1].parent_i = i;
cellDetails[i][j+1].parent_j = j;
printf("The destination cell is found\n");
tracePath(cellDetails, dest);
foundDest = true;
return;
}
// If the successor is already on the closed
// list or if it is blocked, then ignore it.
// Else do the following
else if (closedList[i][j+1] == false &&
isUnBlocked (grid, i, j+1) == true)
{
gNew = cellDetails[i][j].g + 1.0;
hNew = calculateHValue (i, j+1, dest);
fNew = gNew + hNew;
// If it isn’t on the open list, add it to
// the open list. Make the current square
// the parent of this square. Record the
// f, g, and h costs of the square cell
// OR
// If it is on the open list already, check
// to see if this path to that square is better,
// using 'f' cost as the measure.
if (cellDetails[i][j+1].f == FLT_MAX ||
cellDetails[i][j+1].f > fNew)
{
openList.insert( make_pair(fNew,
make_pair (i, j+1)));
// Update the details of this cell
cellDetails[i][j+1].f = fNew;
cellDetails[i][j+1].g = gNew;
cellDetails[i][j+1].h = hNew;
cellDetails[i][j+1].parent_i = i;
cellDetails[i][j+1].parent_j = j;
}
}
}
//----------- 4th Successor (West) ------------
// Only process this cell if this is a valid one
if (isValid(i, j-1) == true)
{
// If the destination cell is the same as the
// current successor
if (isDestination(i, j-1, dest) == true)
{
// Set the Parent of the destination cell
cellDetails[i][j-1].parent_i = i;
cellDetails[i][j-1].parent_j = j;
printf("The destination cell is found\n");
tracePath(cellDetails, dest);
foundDest = true;
return;
}
// If the successor is already on the closed
// list or if it is blocked, then ignore it.
// Else do the following
else if (closedList[i][j-1] == false &&
isUnBlocked(grid, i, j-1) == true)
{
gNew = cellDetails[i][j].g + 1.0;
hNew = calculateHValue(i, j-1, dest);
fNew = gNew + hNew;
// If it isn’t on the open list, add it to
// the open list. Make the current square
// the parent of this square. Record the
// f, g, and h costs of the square cell
// OR
// If it is on the open list already, check
// to see if this path to that square is better,
// using 'f' cost as the measure.
if (cellDetails[i][j-1].f == FLT_MAX ||
cellDetails[i][j-1].f > fNew)
{
openList.insert( make_pair (fNew,
make_pair (i, j-1)));
// Update the details of this cell
cellDetails[i][j-1].f = fNew;
cellDetails[i][j-1].g = gNew;
cellDetails[i][j-1].h = hNew;
cellDetails[i][j-1].parent_i = i;
cellDetails[i][j-1].parent_j = j;
}
}
}
//----------- 5th Successor (North-East) ------------
// Only process this cell if this is a valid one
if (isValid(i-1, j+1) == true)
{
// If the destination cell is the same as the
// current successor
if (isDestination(i-1, j+1, dest) == true)
{
// Set the Parent of the destination cell
cellDetails[i-1][j+1].parent_i = i;
cellDetails[i-1][j+1].parent_j = j;
printf ("The destination cell is found\n");
tracePath (cellDetails, dest);
foundDest = true;
return;
}
// If the successor is already on the closed
// list or if it is blocked, then ignore it.
// Else do the following
else if (closedList[i-1][j+1] == false &&
isUnBlocked(grid, i-1, j+1) == true)
{
gNew = cellDetails[i][j].g + 1.414;
hNew = calculateHValue(i-1, j+1, dest);
fNew = gNew + hNew;
// If it isn’t on the open list, add it to
// the open list. Make the current square
// the parent of this square. Record the
// f, g, and h costs of the square cell
// OR
// If it is on the open list already, check
// to see if this path to that square is better,
// using 'f' cost as the measure.
if (cellDetails[i-1][j+1].f == FLT_MAX ||
cellDetails[i-1][j+1].f > fNew)
{
openList.insert( make_pair (fNew,
make_pair(i-1, j+1)));
// Update the details of this cell
cellDetails[i-1][j+1].f = fNew;
cellDetails[i-1][j+1].g = gNew;
cellDetails[i-1][j+1].h = hNew;
cellDetails[i-1][j+1].parent_i = i;
cellDetails[i-1][j+1].parent_j = j;
}
}
}
//----------- 6th Successor (North-West) ------------
// Only process this cell if this is a valid one
if (isValid (i-1, j-1) == true)
{
// If the destination cell is the same as the
// current successor
if (isDestination (i-1, j-1, dest) == true)
{
// Set the Parent of the destination cell
cellDetails[i-1][j-1].parent_i = i;
cellDetails[i-1][j-1].parent_j = j;
printf ("The destination cell is found\n");
tracePath (cellDetails, dest);
foundDest = true;
return;
}
// If the successor is already on the closed
// list or if it is blocked, then ignore it.
// Else do the following
else if (closedList[i-1][j-1] == false &&
isUnBlocked(grid, i-1, j-1) == true)
{
gNew = cellDetails[i][j].g + 1.414;
hNew = calculateHValue(i-1, j-1, dest);
fNew = gNew + hNew;
// If it isn’t on the open list, add it to
// the open list. Make the current square
// the parent of this square. Record the
// f, g, and h costs of the square cell
// OR
// If it is on the open list already, check
// to see if this path to that square is better,
// using 'f' cost as the measure.
if (cellDetails[i-1][j-1].f == FLT_MAX ||
cellDetails[i-1][j-1].f > fNew)
{
openList.insert( make_pair (fNew, make_pair (i-1, j-1)));
// Update the details of this cell
cellDetails[i-1][j-1].f = fNew;
cellDetails[i-1][j-1].g = gNew;
cellDetails[i-1][j-1].h = hNew;
cellDetails[i-1][j-1].parent_i = i;
cellDetails[i-1][j-1].parent_j = j;
}
}
}
//----------- 7th Successor (South-East) ------------
// Only process this cell if this is a valid one
if (isValid(i+1, j+1) == true)
{
// If the destination cell is the same as the
// current successor
if (isDestination(i+1, j+1, dest) == true)
{
// Set the Parent of the destination cell
cellDetails[i+1][j+1].parent_i = i;
cellDetails[i+1][j+1].parent_j = j;
printf ("The destination cell is found\n");
tracePath (cellDetails, dest);
foundDest = true;
return;
}
// If the successor is already on the closed
// list or if it is blocked, then ignore it.
// Else do the following
else if (closedList[i+1][j+1] == false &&
isUnBlocked(grid, i+1, j+1) == true)
{
gNew = cellDetails[i][j].g + 1.414;
hNew = calculateHValue(i+1, j+1, dest);
fNew = gNew + hNew;
// If it isn’t on the open list, add it to
// the open list. Make the current square
// the parent of this square. Record the
// f, g, and h costs of the square cell
// OR
// If it is on the open list already, check
// to see if this path to that square is better,
// using 'f' cost as the measure.
if (cellDetails[i+1][j+1].f == FLT_MAX ||
cellDetails[i+1][j+1].f > fNew)
{
openList.insert(make_pair(fNew,
make_pair (i+1, j+1)));
// Update the details of this cell
cellDetails[i+1][j+1].f = fNew;
cellDetails[i+1][j+1].g = gNew;
cellDetails[i+1][j+1].h = hNew;
cellDetails[i+1][j+1].parent_i = i;
cellDetails[i+1][j+1].parent_j = j;
}
}
}
//----------- 8th Successor (South-West) ------------
// Only process this cell if this is a valid one
if (isValid (i+1, j-1) == true)
{
// If the destination cell is the same as the
// current successor
if (isDestination(i+1, j-1, dest) == true)
{
// Set the Parent of the destination cell
cellDetails[i+1][j-1].parent_i = i;
cellDetails[i+1][j-1].parent_j = j;
printf("The destination cell is found\n");
tracePath(cellDetails, dest);
foundDest = true;
return;
}
// If the successor is already on the closed
// list or if it is blocked, then ignore it.
// Else do the following
else if (closedList[i+1][j-1] == false &&
isUnBlocked(grid, i+1, j-1) == true)
{
gNew = cellDetails[i][j].g + 1.414;
hNew = calculateHValue(i+1, j-1, dest);
fNew = gNew + hNew;
// If it isn’t on the open list, add it to
// the open list. Make the current square
// the parent of this square. Record the
// f, g, and h costs of the square cell
// OR
// If it is on the open list already, check
// to see if this path to that square is better,
// using 'f' cost as the measure.
if (cellDetails[i+1][j-1].f == FLT_MAX ||
cellDetails[i+1][j-1].f > fNew)
{
openList.insert(make_pair(fNew,
make_pair(i+1, j-1)));
// Update the details of this cell
cellDetails[i+1][j-1].f = fNew;
cellDetails[i+1][j-1].g = gNew;
cellDetails[i+1][j-1].h = hNew;
cellDetails[i+1][j-1].parent_i = i;
cellDetails[i+1][j-1].parent_j = j;
}
}
}
}
// When the destination cell is not found and the open
// list is empty, then we conclude that we failed to
// reach the destiantion cell. This may happen when the
// there is no way to destination cell (due to blockages)
if (foundDest == false)
printf("Failed to find the Destination Cell\n");
return;
}
// Driver program to test above function
int main()
{
/* Description of the Grid-
1--> The cell is not blocked
0--> The cell is blocked */
int grid[ROW][COL] =
{
{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
{ 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 }
};
// Source is the left-most bottom-most corner
Pair src = make_pair(8, 0);
// Destination is the left-most top-most corner
Pair dest = make_pair(0, 0);
aStarSearch(grid, src, dest);
return(0);
}
| 36.13253 | 77 | 0.463238 | shuvamkumar |
67c806d8a39ec9e25270f85d3196f021d26e8bc7 | 6,824 | cpp | C++ | dev/Code/Sandbox/Plugins/EditorAnimation/CharacterTool/EffectPlayer.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 1,738 | 2017-09-21T10:59:12.000Z | 2022-03-31T21:05:46.000Z | dev/Code/Sandbox/Plugins/EditorAnimation/CharacterTool/EffectPlayer.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 427 | 2017-09-29T22:54:36.000Z | 2022-02-15T19:26:50.000Z | dev/Code/Sandbox/Plugins/EditorAnimation/CharacterTool/EffectPlayer.cpp | jeikabu/lumberyard | 07228c605ce16cbf5aaa209a94a3cb9d6c1a4115 | [
"AML"
] | 671 | 2017-09-21T08:04:01.000Z | 2022-03-29T14:30:07.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#include "pch.h"
#include "stdafx.h"
#include "EffectPlayer.h"
#include <ICryAnimation.h>
#include <IEntitySystem.h>
namespace CharacterTool {
EffectPlayer::EffectPlayer()
: m_pSkeleton2(0)
, m_pSkeletonPose(0)
, m_pIDefaultSkeleton(0)
{
GetIEditor()->RegisterNotifyListener(this);
}
EffectPlayer::~EffectPlayer()
{
KillAllEffects();
GetIEditor()->UnregisterNotifyListener(this);
}
void EffectPlayer::SetSkeleton(ISkeletonAnim* pSkeletonAnim, ISkeletonPose* pSkeletonPose, IDefaultSkeleton* pIDefaultSkeleton)
{
m_pSkeleton2 = pSkeletonAnim;
m_pSkeletonPose = pSkeletonPose;
m_pIDefaultSkeleton = pIDefaultSkeleton;
}
void EffectPlayer::Update(const QuatT& rPhysEntity)
{
for (int i = 0; i < m_effects.size(); )
{
EffectEntry& entry = m_effects[i];
// If the animation has stopped, kill the effect.
bool effectStillPlaying = (entry.pEmitter ? entry.pEmitter->IsAlive() : false);
bool animStillPlaying = IsPlayingAnimation(entry.animID);
if (animStillPlaying && effectStillPlaying)
{
// Update the effect position.
Matrix34 tm;
GetEffectTM(tm, entry.boneID, entry.offset, entry.dir);
if (entry.pEmitter)
{
entry.pEmitter->SetMatrix(Matrix34(rPhysEntity) * tm);
}
++i;
}
else
{
if (m_effects[i].pEmitter)
{
m_effects[i].pEmitter->Activate(false);
}
m_effects.erase(m_effects.begin() + i);
}
}
}
void EffectPlayer::KillAllEffects()
{
for (int i = 0, count = m_effects.size(); i < count; ++i)
{
if (m_effects[i].pEmitter)
{
m_effects[i].pEmitter->Activate(false);
}
}
m_effects.clear();
}
void EffectPlayer::SpawnEffect(int animID, const char* animName, const char* effectName, const char* boneName, const Vec3& offset, const Vec3& dir)
{
// Check whether we are already playing this effect, and if so dont restart it.
bool alreadyPlayingEffect = false;
if (!gEnv->pConsole->GetCVar("ca_AllowMultipleEffectsOfSameName")->GetIVal())
{
alreadyPlayingEffect = IsPlayingEffect(effectName);
}
if (!alreadyPlayingEffect)
{
IParticleEffect* pEffect = gEnv->pParticleManager->FindEffect(effectName);
if (!pEffect)
{
CryWarning(VALIDATOR_MODULE_EDITOR, VALIDATOR_WARNING, "Anim events cannot find effect \"%s\", requested by animation \"%s\".", (effectName ? effectName : "<MISSING EFFECT NAME>"), (animName ? animName : "<MISSING ANIM NAME>"));
}
int boneID = (boneName && boneName[0] && m_pIDefaultSkeleton ? m_pIDefaultSkeleton->GetJointIDByName(boneName) : -1);
boneID = (boneID == -1 ? 0 : boneID);
Matrix34 tm;
GetEffectTM(tm, boneID, offset, dir);
IParticleEmitter* pEmitter = (pEffect ? pEffect->Spawn(tm, ePEF_Nowhere) : 0);
if (pEffect && pEmitter)
{
// Make sure the emitter is not rendered in the game.
m_effects.push_back(EffectEntry(pEffect, pEmitter, boneID, offset, dir, animID));
}
}
}
void EffectPlayer::OnEditorNotifyEvent(EEditorNotifyEvent event)
{
switch (event)
{
case eNotify_OnCloseScene:
KillAllEffects();
break;
}
}
EffectPlayer::EffectEntry::EffectEntry(const _smart_ptr<IParticleEffect>& pEffect, const _smart_ptr<IParticleEmitter>& pEmitter, int boneID, const Vec3& offset, const Vec3& dir, int animID)
: pEffect(pEffect)
, pEmitter(pEmitter)
, boneID(boneID)
, offset(offset)
, dir(dir)
, animID(animID)
{
}
EffectPlayer::EffectEntry::~EffectEntry()
{
}
void EffectPlayer::GetEffectTM(Matrix34& tm, int boneID, const Vec3& offset, const Vec3& dir)
{
if (dir.len2() > 0)
{
tm = Matrix33::CreateRotationXYZ(Ang3(dir * 3.14159f / 180.0f));
}
else
{
tm.SetIdentity();
}
tm.AddTranslation(offset);
if (m_pSkeletonPose)
{
tm = Matrix34(m_pSkeletonPose->GetAbsJointByID(boneID)) * tm;
}
}
bool EffectPlayer::IsPlayingAnimation(int animID)
{
enum
{
NUM_LAYERS = 4
};
// Check whether the animation has stopped.
bool animPlaying = false;
for (int layer = 0; layer < NUM_LAYERS; ++layer)
{
for (int animIndex = 0, animCount = (m_pSkeleton2 ? m_pSkeleton2->GetNumAnimsInFIFO(layer) : 0); animIndex < animCount; ++animIndex)
{
CAnimation& anim = m_pSkeleton2->GetAnimFromFIFO(layer, animIndex);
animPlaying = animPlaying || (anim.GetAnimationId() == animID);
}
}
return animPlaying;
}
bool EffectPlayer::IsPlayingEffect(const char* effectName)
{
bool isPlaying = false;
for (int effectIndex = 0, effectCount = m_effects.size(); effectIndex < effectCount; ++effectIndex)
{
IParticleEffect* pEffect = m_effects[effectIndex].pEffect;
if (pEffect && azstricmp(pEffect->GetName(), effectName) == 0)
{
isPlaying = true;
}
}
return isPlaying;
}
void EffectPlayer::Render(SRendParams& params, const SRenderingPassInfo& passInfo)
{
for (int effectIndex = 0, effectCount = m_effects.size(); effectIndex < effectCount; ++effectIndex)
{
IParticleEmitter* pEmitter = m_effects[effectIndex].pEmitter;
if (pEmitter)
{
pEmitter->Update();
pEmitter->Render(params, passInfo);
}
}
}
}
| 33.126214 | 244 | 0.579132 | jeikabu |
67cb0da9678791c31d058a4b20a418820681f81e | 9,190 | cpp | C++ | states/editor/editoroptions.cpp | Adriqun/Ninja2 | 98aff59bcb63928dd6894ea45e00bfe12e46e6bc | [
"MIT"
] | 5 | 2018-06-10T09:14:37.000Z | 2022-01-24T10:08:12.000Z | states/editor/editoroptions.cpp | Adriqun/Ninja2 | 98aff59bcb63928dd6894ea45e00bfe12e46e6bc | [
"MIT"
] | 2 | 2016-11-01T14:39:28.000Z | 2017-02-12T20:54:29.000Z | states/editor/editoroptions.cpp | Adriqun/Ninja2 | 98aff59bcb63928dd6894ea45e00bfe12e46e6bc | [
"MIT"
] | 1 | 2016-12-27T05:06:07.000Z | 2016-12-27T05:06:07.000Z | #include "editoroptions.h"
#include "loading.h"
#include "colors.h"
#include "definitions.h"
EditorOptions::EditorOptions()
{
free();
}
EditorOptions::~EditorOptions()
{
free();
}
void EditorOptions::free()
{
if (!keytextvec.empty())
{
for (auto &it : keytextvec)
{
delete it;
it = nullptr;
}
keytextvec.clear();
}
if (!infotextvec.empty())
{
for (auto &it : infotextvec)
{
delete it;
it = nullptr;
}
infotextvec.clear();
}
reset();
lastPage = 3;
}
void EditorOptions::reset()
{
currPage = 0;
active = false;
}
void EditorOptions::load(const float& screen_w, const float& screen_h)
{
free();
float scale_x = screen_w / 1920; if (scale_x > 1.0f) scale_x = 1;
float scale_y = screen_h / 1080; if (scale_y > 1.0f) scale_y = 1;
// Set button.
button.load("images/buttons/settings.png");
if (Loading::isError()) return;
button.setVolume(MIN_SOUND_VOLUME); // muted
button.setScale(screen_w / 2560, screen_h / 1440);
button.setPosition(screen_w - (screen_w / 256 + button.getWidth()) * 4, screen_h / 144);
// Set button label.
Loading::add(label.setFont(cmm::JCANDLE_FONT_PATH));
if (Loading::isError()) return;
label.setText("options");
label.setAlpha(MAX_ALPHA);
label.setPosition(button.getLeft() + button.getWidth() / 2 - label.getWidth() / 2.5, button.getBot() + screen_w / 300.0f);
label.setSize(screen_w / 60);
// Set board.
Loading::add(plank.load("images/other/plank.png"));
if (Loading::isError()) return;
plank.setScale(scale_x, scale_y);
plank.center(screen_w / 2, screen_h / 2);
// Set black layer.
blackLayer.setFillColor(sf::Color(0, 0, 0, 140));
blackLayer.setSize(sf::Vector2f(screen_w, screen_h));
blackLayer.setPosition(0, 0);
// Set left/right buttons.
Loading::add(leftbutton.load("images/icons/lefticon.png"));
Loading::add(rightbutton.load("images/icons/righticon.png"));
if (Loading::isError()) return;
float factor = 0.9f;
leftbutton.setScale(scale_x * factor, scale_y * factor);
rightbutton.setScale(scale_x * factor, scale_y * factor);
leftbutton.setPosition(plank.getLeft() + screen_w / 128, plank.getTop() + plank.getHeight() / 2 - leftbutton.getHeight() / 2);
rightbutton.setPosition((plank.getRight() - screen_w / 128) - rightbutton.getWidth(), leftbutton.getY());
leftbutton.setAlpha(MAX_ALPHA / 1.5);
rightbutton.setAlpha(MAX_ALPHA / 1.5);
// Set texts.
for (int i = 0; i < LABELS::AMOUNT; ++i)
{
keytextvec.push_back(new cmm::Text);
infotextvec.push_back(new cmm::Text);
Loading::add(keytextvec.back()->setFont(cmm::JAPOKKI_FONT_PATH));
Loading::add(infotextvec.back()->setFont(cmm::JAPOKKI_FONT_PATH));
if (Loading::isError()) return;
keytextvec.back()->setSize(plank.getWidth() / 25);
infotextvec.back()->setSize(plank.getWidth() / 25);
keytextvec.back()->setFillColor(cmm::DULL_IRON_COLOR);
infotextvec.back()->setFillColor(cmm::WHITISH_COLOR);
keytextvec.back()->setAlpha(MAX_ALPHA);
infotextvec.back()->setAlpha(MAX_ALPHA);
}
keytextvec[ESCAPE]->setText("[ESC]");
keytextvec[ENTER]->setText("[ENTER]");
keytextvec[CTRL_Z]->setText("[CTRL+Z]");
keytextvec[SPACE]->setText("[SPACE]");
keytextvec[LCTRL]->setText("[LCTRL]");
keytextvec[LSHIFT]->setText("[LSHIFT]");
keytextvec[A]->setText("[A]\t\t");
keytextvec[S]->setText("[S]\t\t");
keytextvec[D]->setText("[D]\t\t");
keytextvec[Z]->setText("[Z]\t\t");
keytextvec[X]->setText("[X]\t\t");
keytextvec[C]->setText("[C]\t\t");
keytextvec[LEFT]->setText("[LEFT]");
keytextvec[RIGHT]->setText("[RIGHT]");
keytextvec[UP]->setText("[UP]");
keytextvec[DOWN]->setText("[DOWN]");
keytextvec[LEFTMOUSE]->setText("[LEFT MOUSE BUTTON]");
keytextvec[RIGHTMOUSE]->setText("[RIGHT MOUSE BUTTON]");
keytextvec[SCROLLMOUSE]->setText("[MOUSE SCROLL]");
infotextvec[ESCAPE]->setText("Closes current open window. Turns off\ncurrent active mode.\nResets group and chosen entity from group.\n");
infotextvec[ENTER]->setText("Agrees with current decision in message log.\nApproves choice yes/ok.\n");
infotextvec[CTRL_Z]->setText("Undo. Back to previous world state.\nDetermines current state then goes back to\nthe previous.\n");
infotextvec[SPACE]->setText("Temporary quick mode. Does actions like\nput (place) or remove. Based on current\nmode it deletes or puts entity very fast.\n");
infotextvec[LCTRL]->setText("Temporary delete mode. Enables user to\nremove entity that mouse is pointing at.\n");
infotextvec[LSHIFT]->setText("Temporary whole collision mode. This mode\nis very useful while placing tiles.\nTurnt on checks the whole rect occupied by\nentity.\n\n");
infotextvec[A]->setText("Moves to the previous group of entities.");
infotextvec[S]->setText("Reset the chosen group to none.");
infotextvec[D]->setText("Moves to the succeding group of entities.\n");
infotextvec[Z]->setText("Goes to previous entity from the group.");
infotextvec[X]->setText("Goes to nearest middle one from the group.");
infotextvec[C]->setText("Goes to next entity from the group.\n");
infotextvec[LEFT]->setText("Moves current world content's position\nleftward (it does not change entities position).\n");
infotextvec[RIGHT]->setText("Moves current world content's position\nrightward (same as above).\n");
infotextvec[UP]->setText("Moves current world content's position upward\n(same as above).\n");
infotextvec[DOWN]->setText("Moves current world content's position\ndownward (same as above).\n");
infotextvec[LEFTMOUSE]->setText("Puts entity or removes\n(depends on current mode).\n\n");
infotextvec[RIGHTMOUSE]->setText("If mouse cursor is hovered\nabove the entity it opens\nthe options of a group.\n\n\n");
infotextvec[SCROLLMOUSE]->setText("Changes entity of chosen group\nto upward or downward one.");
// Set page text.
Loading::add(pageText.setFont(cmm::JCANDLE_FONT_PATH));
if (Loading::isError()) return;
pageText.setAlpha(MAX_ALPHA);
pageText.setSize(plank.getWidth() / 20);
setPageText();
}
void EditorOptions::handle(const sf::Event &event)
{
if (event.type == sf::Event::MouseButtonPressed)
{
if (event.mouseButton.button == sf::Mouse::Left)
{
float x = (float)event.mouseButton.x;
float y = (float)event.mouseButton.y;
if (!active && button.handle(event))
{
active = button.isActive();
if (active)
setText();
return;
}
if (!active)
return;
if (leftbutton.checkCollision(x, y))
{
if (isAbleToGoLeft())
{
--currPage;
setText();
}
}
else if (rightbutton.checkCollision(x, y))
{
if (isAbleToGoRight())
{
++currPage;
setText();
}
}
else if (!plank.checkCollision(x, y))
{
active = false;
button.setActive(false);
reset();
}
}
}
if (!active)
return;
if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::Escape)
{
active = false;
button.setActive(false);
reset();
return;
}
}
// hovering...
if (event.type == sf::Event::MouseMoved)
{
leftbutton.setAlpha(MAX_ALPHA / 1.5);
rightbutton.setAlpha(MAX_ALPHA / 1.5);
float x = (float)event.mouseMove.x;
float y = (float)event.mouseMove.y;
if (isAbleToGoLeft() && leftbutton.checkCollision(x, y))
leftbutton.setAlpha(MAX_ALPHA);
else if (isAbleToGoRight() &&rightbutton.checkCollision(x, y))
rightbutton.setAlpha(MAX_ALPHA);
}
}
void EditorOptions::drawButton(sf::RenderWindow* &window)
{
// Draw button and label always.
button.draw(window);
window->draw(label);
}
void EditorOptions::draw(sf::RenderWindow* &window)
{
if (!active)
return;
window->draw(blackLayer);
window->draw(plank);
// Draw descriptions / texts.
for (int i = first; i <= last; ++i)
{
window->draw(*keytextvec[i]);
window->draw(*infotextvec[i]);
}
// Draw left/right buttons.
if (currPage != 0)
window->draw(leftbutton);
if (currPage != lastPage)
window->draw(rightbutton);
window->draw(pageText);
}
void EditorOptions::setText()
{
setPageText();
setBorders();
// set position of current scope
keytextvec[first]->setPosition(plank.getX() + plank.getWidth() / 64, plank.getY() + plank.getHeight() / 64);
infotextvec[first]->setPosition(keytextvec[first]->getX() + keytextvec[first]->getWidth() + plank.getWidth() / 64, keytextvec[first]->getY());
for (int i = first + 1; i <= last; ++i)
{
keytextvec[i]->setPosition(keytextvec[first]->getX(), infotextvec[i - 1]->getBot());
infotextvec[i]->setPosition(keytextvec[i]->getX() + keytextvec[i]->getWidth() + plank.getWidth() / 64, infotextvec[i - 1]->getBot());
}
}
void EditorOptions::setPageText()
{
pageText.setText(std::to_string(currPage) + "/" + std::to_string(lastPage));
pageText.setPosition(plank.getLeft() + plank.getWidth() - pageText.getWidth() * 1.2, plank.getTop() + plank.getHeight() - plank.getWidth() / 15);
}
void EditorOptions::setBorders()
{
if (currPage == 0)
{
first = 0;
last = SPACE;
}
else if (currPage == 1)
{
first = LCTRL;
last = C;
}
else if (currPage == lastPage - 1)
{
first = LEFT;
last = DOWN;
}
else
{
first = LEFTMOUSE;
last = SCROLLMOUSE;
}
}
bool EditorOptions::isAbleToGoLeft()
{
return currPage > 0;
}
bool EditorOptions::isAbleToGoRight()
{
return currPage < lastPage;
} | 28.990536 | 169 | 0.685528 | Adriqun |
67cd38053c8305cacf6016b1184626d00aa1151b | 3,160 | cpp | C++ | Nummerical Methods for CSE/PS14/solutions_ps14/sdirk.cpp | valentinjacot/backupETHZ | 36605c4f532eb65efb4a391ed0f17a07102f7d5b | [
"MIT"
] | 1 | 2019-12-25T10:21:30.000Z | 2019-12-25T10:21:30.000Z | Nummerical Methods for CSE/PS14/solutions_ps14/sdirk.cpp | valentinjacot/backupETHZ | 36605c4f532eb65efb4a391ed0f17a07102f7d5b | [
"MIT"
] | null | null | null | Nummerical Methods for CSE/PS14/solutions_ps14/sdirk.cpp | valentinjacot/backupETHZ | 36605c4f532eb65efb4a391ed0f17a07102f7d5b | [
"MIT"
] | null | null | null | #include <Eigen/Dense>
#include <iostream>
#include <iomanip>
#include <cmath>
//! \brief One step of autonomous IVP y'' + y' + y = 0, [y(0), y'(0)] = z0 using SDIRK method
//! Use SDIRK method for first order ode z' = f(z). Steps of size h.
//! \tparam StateType type of solution space y and initial data y0
//! \param[in] z0 initial data z(0)
//! \param[in] h size of the step
//! \param[in] gamma parameter
//! \return next step z1
template <class StateType>
StateType sdirkStep(const StateType & z0, double h, double gamma) {
// Matrix A for evaluation of f
Eigen::Matrix2d A;
A << 0.,1.,-1.,-1.;
// Reuse factorization
auto A_lu = (Eigen::Matrix2d::Identity()-h*gamma*A).partialPivLu();
Eigen::Vector2d az = A*z0;
// Increments
Eigen::Vector2d k1 = A_lu.solve(az);
Eigen::Vector2d k2 = A_lu.solve(az + h*(1-2*gamma)*A*k1);
// Next step
return z0 + h*0.5*(k1 + k2);
}
//! \brief Solve autonomous IVP y'' + y' + y = 0, [y(0), y'(0)] = z0 using SDIRK method
//! Use SDIRK method for first order ode z' = f(z), with N equidistant steps
//! \tparam StateType type of solution space z = [y,y']! and initial data z0 = [y(0), y'(0)]
//! \param[in] z0 initial data z(0)
//! \param[in] N number of equidistant steps
//! \param[in] T final time of simulation
//! \param[in] gamma parameter
//! \return vector containing each step of z_k (y and y')
template <class StateType>
std::vector<StateType> sdirkSolve(const StateType & z0, unsigned int N, double T, double gamma) {
// Solution vector
std::vector<StateType> res(N+1);
// Equidistant step size
const double h = T/N;
// Push initial data
res.at(0) = z0;
// Main loop
for(unsigned int i = 1; i <= N; ++i) {
res.at(i) = sdirkStep(res.at(i-1), h, gamma);
}
return res;
}
int main() {
// Initial data z0 = [y(0), y'(0)]
Eigen::Vector2d z0;
z0 << 1,0;
// Final time
const double T = 10;
// Parameter
const double gamma = (3.+std::sqrt(3.)) / 6.;
// Mesh sizes
std::vector<int> N = {20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240};
// Exact solution (only y(t)) given z0 = [y(0), y'(0)] and t
auto yex = [&z0] (double t) {
return 1./3.*std::exp(-t/2.) * ( 3.*z0(0) * std::cos( std::sqrt(3.)*t/2. ) +
std::sqrt(3.)*z0(0) * std::sin( std::sqrt(3.)*t/2. ) +
2.*std::sqrt(3.)*z0(1) * std::sin( std::sqrt(3.)*t/2. ) );
};
// Store old error for rate computation
double errold = 0;
std::cout << std::setw(15) << "n" << std::setw(15) << "maxerr" << std::setw(15) << "rate" << std::endl;
// Loop over all meshes
for(unsigned int i = 0; i < N.size(); ++i) {
int n = N.at(i);
// Get solution
auto sol = sdirkSolve(z0, n, T, gamma);
// Compute error
double err = std::abs(sol.back()(0) - yex(T));
// I/O
std::cout << std::setw(15) << n << std::setw(15) << err;
if(i > 0) std::cout << std::setw(15) << std::log2(errold /err);
std::cout << std::endl;
// Store old error
errold = err;
}
}
| 32.916667 | 107 | 0.556646 | valentinjacot |
67cdc0ae701a82aad41c54182971e8d68e8d7057 | 6,580 | cpp | C++ | src/c_dd.cpp | andry81/orbittools--qd | 04be70aa8d42a34ff97e8e3a438dbbf9dc0da087 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/c_dd.cpp | andry81/orbittools--qd | 04be70aa8d42a34ff97e8e3a438dbbf9dc0da087 | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/c_dd.cpp | andry81/orbittools--qd | 04be70aa8d42a34ff97e8e3a438dbbf9dc0da087 | [
"BSD-3-Clause-LBNL"
] | null | null | null | /*
* src/c_dd.cc
*
* This work was supported by the Director, Office of Science, Division
* of Mathematical, Information, and Computational Sciences of the
* U.S. Department of Energy under contract number DE-AC03-76SF00098.
*
* Copyright (c) 2000-2001
*
* Contains the C wrapper functions for double-double precision arithmetic.
* This can be used from Fortran code.
*/
#include <cstring>
#include "config.h"
#include <qd/dd_real.h>
#include <qd/c_dd.h>
#define TO_DOUBLE_PTR(a, ptr) ptr[0] = a.x[0]; ptr[1] = a.x[1];
extern "C" {
/* add */
void c_dd_add(const double *a, const double *b, double *c) {
dd_real cc;
cc = dd_real(a) + dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
void c_dd_add_dd_d(const double *a, double b, double *c) {
dd_real cc;
cc = dd_real(a) + b;
TO_DOUBLE_PTR(cc, c);
}
void c_dd_add_d_dd(double a, const double *b, double *c) {
dd_real cc;
cc = a + dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
/* sub */
void c_dd_sub(const double *a, const double *b, double *c) {
dd_real cc;
cc = dd_real(a) - dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
void c_dd_sub_dd_d(const double *a, double b, double *c) {
dd_real cc;
cc = dd_real(a) - b;
TO_DOUBLE_PTR(cc, c);
}
void c_dd_sub_d_dd(double a, const double *b, double *c) {
dd_real cc;
cc = a - dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
/* mul */
void c_dd_mul(const double *a, const double *b, double *c) {
dd_real cc;
cc = dd_real(a) * dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
void c_dd_mul_dd_d(const double *a, double b, double *c) {
dd_real cc;
cc = dd_real(a) * b;
TO_DOUBLE_PTR(cc, c);
}
void c_dd_mul_d_dd(double a, const double *b, double *c) {
dd_real cc;
cc = a * dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
/* div */
void c_dd_div(const double *a, const double *b, double *c) {
dd_real cc;
cc = dd_real(a) / dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
void c_dd_div_dd_d(const double *a, double b, double *c) {
dd_real cc;
cc = dd_real(a) / b;
TO_DOUBLE_PTR(cc, c);
}
void c_dd_div_d_dd(double a, const double *b, double *c) {
dd_real cc;
cc = a / dd_real(b);
TO_DOUBLE_PTR(cc, c);
}
/* copy */
void c_dd_copy(const double *a, double *b) {
b[0] = a[0];
b[1] = a[1];
}
void c_dd_copy_d(double a, double *b) {
b[0] = a;
b[1] = 0.0;
}
void c_dd_sqrt(const double *a, double *b) {
dd_real bb;
bb = std::sqrt(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_sqr(const double *a, double *b) {
dd_real bb;
bb = sqr(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_abs(const double *a, double *b) {
dd_real bb;
bb = std::abs(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_npwr(const double *a, int n, double *b) {
dd_real bb;
bb = npwr(dd_real(a), n);
TO_DOUBLE_PTR(bb, b);
}
void c_dd_nroot(const double *a, int n, double *b) {
dd_real bb;
bb = nroot(dd_real(a), n);
TO_DOUBLE_PTR(bb, b);
}
void c_dd_nint(const double *a, double *b) {
dd_real bb;
bb = nint(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_aint(const double *a, double *b) {
dd_real bb;
bb = aint(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_floor(const double *a, double *b) {
dd_real bb;
bb = std::floor(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_ceil(const double *a, double *b) {
dd_real bb;
bb = std::ceil(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_log(const double *a, double *b) {
dd_real bb;
bb = std::log(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_log10(const double *a, double *b) {
dd_real bb;
bb = std::log10(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_exp(const double *a, double *b) {
dd_real bb;
bb = std::exp(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_sin(const double *a, double *b) {
dd_real bb;
bb = std::sin(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_cos(const double *a, double *b) {
dd_real bb;
bb = std::cos(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_tan(const double *a, double *b) {
dd_real bb;
bb = std::tan(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_asin(const double *a, double *b) {
dd_real bb;
bb = std::asin(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_acos(const double *a, double *b) {
dd_real bb;
bb = std::acos(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_atan(const double *a, double *b) {
dd_real bb;
bb = std::atan(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_atan2(const double *a, const double *b, double *c) {
dd_real cc;
cc = std::atan2(dd_real(a), dd_real(b));
TO_DOUBLE_PTR(cc, c);
}
void c_dd_sinh(const double *a, double *b) {
dd_real bb;
bb = std::sinh(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_cosh(const double *a, double *b) {
dd_real bb;
bb = std::cosh(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_tanh(const double *a, double *b) {
dd_real bb;
bb = std::tanh(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_asinh(const double *a, double *b) {
dd_real bb;
bb = std::asinh(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_acosh(const double *a, double *b) {
dd_real bb;
bb = std::acosh(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_atanh(const double *a, double *b) {
dd_real bb;
bb = std::atanh(dd_real(a));
TO_DOUBLE_PTR(bb, b);
}
void c_dd_sincos(const double *a, double *s, double *c) {
dd_real ss, cc;
sincos(dd_real(a), ss, cc);
TO_DOUBLE_PTR(ss, s);
TO_DOUBLE_PTR(cc, c);
}
void c_dd_sincosh(const double *a, double *s, double *c) {
dd_real ss, cc;
sincosh(dd_real(a), ss, cc);
TO_DOUBLE_PTR(ss, s);
TO_DOUBLE_PTR(cc, c);
}
void c_dd_read(const char *s, double *a) {
dd_real aa(s);
TO_DOUBLE_PTR(aa, a);
}
void c_dd_swrite(const double *a, int precision, char *s, int len) {
dd_real(a).write(s, len, precision);
}
void c_dd_write(const double *a) {
std::cout << dd_real(a).to_string(dd_real::_ndigits()) << std::endl;
}
void c_dd_neg(const double *a, double *b) {
b[0] = -a[0];
b[1] = -a[1];
}
void c_dd_rand(double *a) {
dd_real aa;
aa = ddrand();
TO_DOUBLE_PTR(aa, a);
}
void c_dd_comp(const double *a, const double *b, int *result) {
dd_real aa(a), bb(b);
if (aa < bb)
*result = -1;
else if (aa > bb)
*result = 1;
else
*result = 0;
}
void c_dd_comp_dd_d(const double *a, double b, int *result) {
dd_real aa(a), bb(b);
if (aa < bb)
*result = -1;
else if (aa > bb)
*result = 1;
else
*result = 0;
}
void c_dd_comp_d_dd(double a, const double *b, int *result) {
dd_real aa(a), bb(b);
if (aa < bb)
*result = -1;
else if (aa > bb)
*result = 1;
else
*result = 0;
}
void c_dd_pi(double *a) {
TO_DOUBLE_PTR(dd_real::_pi(), a);
}
}
| 20.888889 | 75 | 0.632371 | andry81 |
67cf47456fe54c8787600f8656b4bd933938254f | 7,007 | cpp | C++ | mptrack/ModDocTemplate.cpp | ford442/openmpt | 614c44fe665b0e1cce15092ecf0d069cbb3e1fe7 | [
"BSD-3-Clause"
] | 335 | 2017-02-25T16:39:27.000Z | 2022-03-29T17:45:42.000Z | mptrack/ModDocTemplate.cpp | ford442/openmpt | 614c44fe665b0e1cce15092ecf0d069cbb3e1fe7 | [
"BSD-3-Clause"
] | 7 | 2018-02-05T18:22:38.000Z | 2022-02-15T19:35:24.000Z | mptrack/ModDocTemplate.cpp | ford442/openmpt | 614c44fe665b0e1cce15092ecf0d069cbb3e1fe7 | [
"BSD-3-Clause"
] | 69 | 2017-04-10T00:48:09.000Z | 2022-03-20T10:24:45.000Z | /*
* ModDocTemplate.cpp
* ------------------
* Purpose: CDocTemplate and CModDocManager specialization for CModDoc.
* Notes : (currently none)
* Authors: OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "stdafx.h"
#include "FolderScanner.h"
#include "Mainfrm.h"
#include "Moddoc.h"
#include "ModDocTemplate.h"
#include "Reporting.h"
#include "SelectPluginDialog.h"
#include "../soundlib/plugins/PluginManager.h"
OPENMPT_NAMESPACE_BEGIN
#ifdef MPT_ALL_LOGGING
#define DDEDEBUG
#endif
CDocument *CModDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, BOOL addToMru, BOOL makeVisible)
{
const mpt::PathString filename = (lpszPathName ? mpt::PathString::FromCString(lpszPathName) : mpt::PathString());
// First, remove document from MRU list.
if(addToMru)
{
theApp.RemoveMruItem(filename);
}
CDocument *pDoc = CMultiDocTemplate::OpenDocumentFile(filename.empty() ? nullptr : filename.ToCString().GetString(), addToMru, makeVisible);
if(pDoc)
{
CMainFrame *pMainFrm = CMainFrame::GetMainFrame();
if (pMainFrm) pMainFrm->OnDocumentCreated(static_cast<CModDoc *>(pDoc));
} else if(!filename.empty() && CMainFrame::GetMainFrame() && addToMru)
{
// Opening the document failed
CMainFrame::GetMainFrame()->UpdateMRUList();
}
return pDoc;
}
CDocument *CModDocTemplate::OpenTemplateFile(const mpt::PathString &filename, bool isExampleTune)
{
CDocument *doc = OpenDocumentFile(filename.ToCString(), isExampleTune ? TRUE : FALSE, TRUE);
if(doc)
{
CModDoc *modDoc = static_cast<CModDoc *>(doc);
// Clear path so that saving will not take place in templates/examples folder.
modDoc->ClearFilePath();
if(!isExampleTune)
{
CMultiDocTemplate::SetDefaultTitle(modDoc);
m_nUntitledCount++;
// Name has changed...
CMainFrame::GetMainFrame()->UpdateTree(modDoc, GeneralHint().General());
// Reset edit history for template files
CSoundFile &sndFile = modDoc->GetSoundFile();
sndFile.GetFileHistory().clear();
sndFile.m_dwCreatedWithVersion = Version::Current();
sndFile.m_dwLastSavedWithVersion = Version();
sndFile.m_modFormat = ModFormatDetails();
sndFile.m_songArtist = TrackerSettings::Instance().defaultArtist;
if(sndFile.GetType() != MOD_TYPE_MPT)
{
// Always enforce most compatible playback for legacy module types
sndFile.m_playBehaviour = sndFile.GetDefaultPlaybackBehaviour(sndFile.GetType());
}
doc->UpdateAllViews(nullptr, UpdateHint().ModType().AsLPARAM());
} else
{
// Remove extension from title, so that saving the file will not suggest a filename like e.g. "example.it.it".
const CString title = modDoc->GetTitle();
const int dotPos = title.ReverseFind(_T('.'));
if(dotPos >= 0)
{
modDoc->SetTitle(title.Left(dotPos));
}
}
}
return doc;
}
void CModDocTemplate::AddDocument(CDocument *doc)
{
CMultiDocTemplate::AddDocument(doc);
m_documents.insert(static_cast<CModDoc *>(doc));
}
void CModDocTemplate::RemoveDocument(CDocument *doc)
{
CMultiDocTemplate::RemoveDocument(doc);
m_documents.erase(static_cast<CModDoc *>(doc));
}
bool CModDocTemplate::DocumentExists(const CModDoc *doc) const
{
return m_documents.count(const_cast<CModDoc *>(doc)) != 0;
}
CDocument *CModDocManager::OpenDocumentFile(LPCTSTR lpszFileName, BOOL bAddToMRU)
{
const mpt::PathString filename = (lpszFileName ? mpt::PathString::FromCString(lpszFileName) : mpt::PathString());
if(filename.IsDirectory())
{
FolderScanner scanner(filename, FolderScanner::kOnlyFiles | FolderScanner::kFindInSubDirectories);
mpt::PathString file;
CDocument *pDoc = nullptr;
while(scanner.Next(file))
{
pDoc = OpenDocumentFile(file.ToCString(), bAddToMRU);
}
return pDoc;
}
if(const auto fileExt = filename.GetFileExt(); !mpt::PathString::CompareNoCase(fileExt, P_(".dll")) || !mpt::PathString::CompareNoCase(fileExt, P_(".vst3")))
{
if(auto plugManager = theApp.GetPluginManager(); plugManager != nullptr)
{
if(auto plugLib = plugManager->AddPlugin(filename, TrackerSettings::Instance().BrokenPluginsWorkaroundVSTMaskAllCrashes); plugLib != nullptr)
{
if(!CSelectPluginDlg::VerifyPlugin(plugLib, nullptr))
{
plugManager->RemovePlugin(plugLib);
}
return nullptr;
}
}
}
CDocument *pDoc = CDocManager::OpenDocumentFile(lpszFileName, bAddToMRU);
if(pDoc == nullptr && !filename.empty())
{
if(!filename.IsFile())
{
Reporting::Error(MPT_CFORMAT("Unable to open \"{}\": file does not exist.")(filename.ToCString()));
theApp.RemoveMruItem(filename);
CMainFrame::GetMainFrame()->UpdateMRUList();
} else
{
// Case: Valid path but opening failed.
const int numDocs = theApp.GetOpenDocumentCount();
Reporting::Notification(MPT_CFORMAT("Opening \"{}\" failed. This can happen if "
"no more modules can be opened or if the file type was not "
"recognised (currently there {} {} document{} open).")(
filename.ToCString(), (numDocs == 1) ? CString(_T("is")) : CString(_T("are")), numDocs, (numDocs == 1) ? CString(_T("")) : CString(_T("s"))));
}
}
return pDoc;
}
BOOL CModDocManager::OnDDECommand(LPTSTR lpszCommand)
{
BOOL bResult, bActivate;
#ifdef DDEDEBUG
MPT_LOG_GLOBAL(LogDebug, "DDE", U_("OnDDECommand: ") + mpt::ToUnicode(mpt::winstring(lpszCommand)));
#endif
// Handle any DDE commands recognized by your application
// and return TRUE. See implementation of CWinApp::OnDDEComand
// for example of parsing the DDE command string.
bResult = FALSE;
bActivate = FALSE;
if ((lpszCommand) && lpszCommand[0] && (theApp.m_pMainWnd))
{
std::size_t len = _tcslen(lpszCommand);
std::vector<TCHAR> s(lpszCommand, lpszCommand + len + 1);
len--;
while((len > 0) && _tcschr(_T("(){}[]\'\" "), s[len]))
{
s[len--] = 0;
}
TCHAR *pszCmd = s.data();
while (pszCmd[0] == _T('[')) pszCmd++;
TCHAR *pszData = pszCmd;
while ((pszData[0] != _T('(')) && (pszData[0]))
{
if (((BYTE)pszData[0]) <= (BYTE)' ') *pszData = 0;
pszData++;
}
while ((*pszData) && (_tcschr(_T("(){}[]\'\" "), *pszData)))
{
*pszData = 0;
pszData++;
}
// Edit/Open
if ((!lstrcmpi(pszCmd, _T("Edit")))
|| (!lstrcmpi(pszCmd, _T("Open"))))
{
if (pszData[0])
{
bResult = TRUE;
bActivate = TRUE;
OpenDocumentFile(pszData);
}
} else
// New
if (!lstrcmpi(pszCmd, _T("New")))
{
OpenDocumentFile(_T(""));
bResult = TRUE;
bActivate = TRUE;
}
#ifdef DDEDEBUG
MPT_LOG_GLOBAL(LogDebug, "DDE", MPT_UFORMAT("{}({})")(mpt::winstring(pszCmd), mpt::winstring(pszData)));
#endif
if ((bActivate) && (theApp.m_pMainWnd->m_hWnd))
{
if (theApp.m_pMainWnd->IsIconic()) theApp.m_pMainWnd->ShowWindow(SW_RESTORE);
theApp.m_pMainWnd->SetActiveWindow();
}
}
// Return FALSE for any DDE commands you do not handle.
#ifdef DDEDEBUG
if (!bResult)
{
MPT_LOG_GLOBAL(LogDebug, "DDE", U_("WARNING: failure in CModDocManager::OnDDECommand()"));
}
#endif
return bResult;
}
OPENMPT_NAMESPACE_END
| 29.074689 | 158 | 0.692736 | ford442 |
67cff565a26fd1a11e1ec60ffe60331abb38a9f1 | 680 | hpp | C++ | phoenix/cocoa/widget/viewport.hpp | vgmtool/vgm2pre | f4f917df35d531512292541234a5c1722b8af96f | [
"MIT"
] | 21 | 2015-04-13T03:07:12.000Z | 2021-11-20T00:27:00.000Z | phoenix/cocoa/widget/viewport.hpp | apollolux/hello-phoenix | 71510b5f329804c525a9576fb0367fe8ab2487cd | [
"MIT"
] | 2 | 2015-10-06T14:59:48.000Z | 2022-01-27T08:57:57.000Z | phoenix/cocoa/widget/viewport.hpp | apollolux/hello-phoenix | 71510b5f329804c525a9576fb0367fe8ab2487cd | [
"MIT"
] | 2 | 2021-11-19T08:36:57.000Z | 2022-03-04T16:03:16.000Z | @interface CocoaViewport : NSView {
@public
phoenix::Viewport* viewport;
}
-(id) initWith:(phoenix::Viewport&)viewport;
-(void) drawRect:(NSRect)rect;
-(BOOL) acceptsFirstResponder;
-(NSDragOperation) draggingEntered:(id<NSDraggingInfo>)sender;
-(BOOL) performDragOperation:(id<NSDraggingInfo>)sender;
-(void) keyDown:(NSEvent*)event;
-(void) keyUp:(NSEvent*)event;
@end
namespace phoenix {
struct pViewport : public pWidget {
Viewport& viewport;
CocoaViewport* cocoaViewport = nullptr;
uintptr_t handle();
void setDroppable(bool droppable);
pViewport(Viewport& viewport) : pWidget(viewport), viewport(viewport) {}
void constructor();
void destructor();
};
}
| 23.448276 | 74 | 0.741176 | vgmtool |
67d071a55a5a9cab05bf9668523ed5eb8f689b6f | 967 | hpp | C++ | libs/core/include/fcppt/time/output_tm.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/time/output_tm.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | libs/core/include/fcppt/time/output_tm.hpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_TIME_OUTPUT_TM_HPP_INCLUDED
#define FCPPT_TIME_OUTPUT_TM_HPP_INCLUDED
#include <fcppt/detail/symbol.hpp>
#include <fcppt/io/ostream_fwd.hpp>
#include <fcppt/config/external_begin.hpp>
#include <ctime>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace time
{
/**
\brief Outputs an <code>%std::tm</code> to a stream
\ingroup fcppttime
Outputs \a tm to \a stream using the <code>std::time_put</code> locale facet,
obtained from the locale of \a stream. Example:
\snippet output_tm.cpp output_tm
\param stream The stream to output to
\param tm The time struct to output
\return \a stream
*/
FCPPT_DETAIL_SYMBOL
fcppt::io::ostream &
output_tm(
fcppt::io::ostream &stream,
std::tm const &tm
);
}
}
#endif
| 20.145833 | 77 | 0.737332 | pmiddend |
67d13caf40a7f6af65e2308488ea2268fc4c30d1 | 3,873 | cc | C++ | cc/output/renderer_unittest.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 1 | 2020-09-15T08:43:34.000Z | 2020-09-15T08:43:34.000Z | cc/output/renderer_unittest.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | cc/output/renderer_unittest.cc | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/output/delegating_renderer.h"
#include "cc/output/gl_renderer.h"
#include "cc/output/output_surface.h"
#include "cc/test/fake_output_surface_client.h"
#include "cc/test/fake_renderer_client.h"
#include "cc/test/fake_resource_provider.h"
#include "cc/test/test_context_provider.h"
#include "cc/test/test_web_graphics_context_3d.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace cc {
namespace {
class TestOutputSurface : public OutputSurface {
public:
explicit TestOutputSurface(scoped_refptr<ContextProvider> context_provider);
~TestOutputSurface() override;
// OutputSurface implementation
void SwapBuffers(CompositorFrame* frame) override;
};
TestOutputSurface::TestOutputSurface(
scoped_refptr<ContextProvider> context_provider)
: OutputSurface(std::move(context_provider)) {}
TestOutputSurface::~TestOutputSurface() {
}
void TestOutputSurface::SwapBuffers(CompositorFrame* frame) {
client_->DidSwapBuffers();
client_->DidSwapBuffersComplete();
}
class MockContextProvider : public TestContextProvider {
public:
explicit MockContextProvider(
std::unique_ptr<TestWebGraphicsContext3D> context)
: TestContextProvider(std::move(context)) {}
MOCK_METHOD0(DeleteCachedResources, void());
protected:
~MockContextProvider() {}
};
template <class T>
std::unique_ptr<Renderer> CreateRenderer(RendererClient* client,
const RendererSettings* settings,
OutputSurface* output_surface,
ResourceProvider* resource_provider);
template <>
std::unique_ptr<Renderer> CreateRenderer<DelegatingRenderer>(
RendererClient* client,
const RendererSettings* settings,
OutputSurface* output_surface,
ResourceProvider* resource_provider) {
return DelegatingRenderer::Create(
client, settings, output_surface, resource_provider);
}
template <>
std::unique_ptr<Renderer> CreateRenderer<GLRenderer>(
RendererClient* client,
const RendererSettings* settings,
OutputSurface* output_surface,
ResourceProvider* resource_provider) {
return GLRenderer::Create(
client, settings, output_surface, resource_provider, NULL, 0);
}
template <typename T>
class RendererTest : public ::testing::Test {
protected:
virtual void SetUp() {
context_provider_ =
new MockContextProvider(TestWebGraphicsContext3D::Create());
output_surface_.reset(new TestOutputSurface(context_provider_));
output_surface_->BindToClient(&output_surface_client_);
resource_provider_ =
FakeResourceProvider::Create(output_surface_.get(), nullptr);
renderer_ = CreateRenderer<T>(&renderer_client_,
&tree_settings_,
output_surface_.get(),
resource_provider_.get());
}
FakeRendererClient renderer_client_;
RendererSettings tree_settings_;
FakeOutputSurfaceClient output_surface_client_;
scoped_refptr<MockContextProvider> context_provider_;
std::unique_ptr<OutputSurface> output_surface_;
std::unique_ptr<ResourceProvider> resource_provider_;
std::unique_ptr<Renderer> renderer_;
};
typedef ::testing::Types<DelegatingRenderer, GLRenderer> RendererTypes;
TYPED_TEST_CASE(RendererTest, RendererTypes);
TYPED_TEST(RendererTest, ContextPurgedWhenRendererBecomesInvisible) {
EXPECT_CALL(*(this->context_provider_.get()), DeleteCachedResources())
.Times(1);
EXPECT_TRUE(this->renderer_->visible());
this->renderer_->SetVisible(false);
EXPECT_FALSE(this->renderer_->visible());
}
} // namespace
} // namespace cc
| 33.387931 | 78 | 0.734573 | maidiHaitai |
67d18e210a6c18d52aa2452e3ae727efa0b958f8 | 3,739 | cpp | C++ | src/systemc/tests/systemc/kernel/dynamic_processes/sc_spawn_options/test01/test01.cpp | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 765 | 2015-01-14T16:17:04.000Z | 2022-03-28T07:46:28.000Z | src/systemc/tests/systemc/kernel/dynamic_processes/sc_spawn_options/test01/test01.cpp | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 148 | 2018-07-20T00:58:36.000Z | 2021-11-16T01:52:33.000Z | src/systemc/tests/systemc/kernel/dynamic_processes/sc_spawn_options/test01/test01.cpp | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 807 | 2015-01-06T09:55:38.000Z | 2022-03-30T10:23:36.000Z | /*****************************************************************************
Licensed to Accellera Systems Initiative Inc. (Accellera) under one or
more contributor license agreements. See the NOTICE file distributed
with this work for additional information regarding copyright ownership.
Accellera licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
*****************************************************************************/
/*****************************************************************************
test01.cpp -- Demo "new" dynamic method support.
See the README file for a description of these capabilities. This demo
excercises all of the major capabilities.
Original Author: Stuart Swan, Cadence Design Systems, Inc., 2002-10-22
*****************************************************************************/
/*****************************************************************************
MODIFICATION LOG - modifiers, enter your name, affiliation, date and
changes you are making here.
Name, Affiliation, Date: Andy Goodrich, Forte Design Systems, 30 July 03
Description of Modification: Converted thread demo to method demo.
*****************************************************************************/
#define SC_INCLUDE_DYNAMIC_PROCESSES
#include <systemc.h>
int test_function(double d)
{
cout << endl << "Test_function sees " << d << endl;
return int(d);
}
void void_function(double d)
{
cout << endl << "void_function sees " << d << endl;
}
int ref_function(const double& d)
{
cout << endl << "ref_function sees " << d << endl;
return int(d);
}
class top : public sc_module
{
public:
SC_HAS_PROCESS(top);
top(sc_module_name name) : sc_module(name)
{
SC_THREAD(main);
}
void main()
{
sc_event e1, e2, e3, e4;
sc_spawn_options options1, options2, options3, options4;
int r;
cout << endl;
e1.notify(100, SC_NS);
// Spawn several methods that co-operatively execute in round robin order
options1.spawn_method();
options1.dont_initialize();
options1.set_sensitivity(&e1);
sc_spawn(&r,
sc_bind(&top::round_robin, this, "1", sc_ref(e1), sc_ref(e2), 3),
"1", &options1
);
options2.spawn_method();
options2.dont_initialize();
options2.set_sensitivity(&e2);
sc_spawn(&r,
sc_bind(&top::round_robin, this, "2", sc_ref(e2), sc_ref(e3), 3),
"2", &options2
);
options3.spawn_method();
options3.dont_initialize();
options3.set_sensitivity(&e3);
sc_spawn(&r,
sc_bind(&top::round_robin, this, "3", sc_ref(e3), sc_ref(e4), 3),
"3", &options3
);
options4.spawn_method();
options4.dont_initialize();
options4.set_sensitivity(&e4);
sc_spawn(&r,
sc_bind(&top::round_robin, this, "4", sc_ref(e4), sc_ref(e1), 3),
"4", &options4
);
wait(295, SC_NS);
cout << endl << "Done." << endl;
sc_stop();
}
int round_robin(const char *str, sc_event& receive, sc_event& send, int cnt)
{
cout << "Round robin method " << str <<
" at time " << sc_time_stamp() << endl;
next_trigger(receive);
send.notify(10, SC_NS);
return 0;
}
};
int sc_main (int argc , char *argv[])
{
top top1("Top1");
sc_start();
return 0;
}
| 26.707143 | 79 | 0.595881 | hyu-iot |
67d2a2c727b58a793eaee3e1242769335aa297da | 11,379 | cpp | C++ | display/test/unittest/standard/display_gralloc/display_gralloc_test.cpp | openharmony-gitee-mirror/drivers_peripheral | 4ee6d41befdf54a97afeb5838be5fcd0b4888d56 | [
"Apache-2.0"
] | null | null | null | display/test/unittest/standard/display_gralloc/display_gralloc_test.cpp | openharmony-gitee-mirror/drivers_peripheral | 4ee6d41befdf54a97afeb5838be5fcd0b4888d56 | [
"Apache-2.0"
] | null | null | null | display/test/unittest/standard/display_gralloc/display_gralloc_test.cpp | openharmony-gitee-mirror/drivers_peripheral | 4ee6d41befdf54a97afeb5838be5fcd0b4888d56 | [
"Apache-2.0"
] | 2 | 2021-09-13T10:12:47.000Z | 2021-09-13T11:16:31.000Z | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 "display_gralloc_test.h"
#include <securec.h>
#include "gtest/gtest.h"
#include "display_gralloc.h"
#include "display_test.h"
#include "hi_gbm_internal.h"
namespace {
const AllocTestPrms GRALLOC_TEST_SETS[] = {
{
.allocInfo = {
.width = 1920,
.height = 1080,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_RGBX_8888
},
.expectStride = 1920 * 4,
.expectSize = 1920 * 1080 * 4
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_RGBX_8888
},
.expectStride = 1080 * 4,
.expectSize = 1080 * 1920 * 4
},
{
.allocInfo = {
.width = 1280,
.height = 720,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_RGBX_8888
},
.expectStride = 1280 * 4,
.expectSize = 1280 * 720 * 4
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_RGBA_8888
},
.expectStride = 1080 * 4,
.expectSize = 1080 * 1920 * 4
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_RGB_888
},
.expectStride = 1080 * 3,
.expectSize = 1080 * 1920 * 3
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_BGRA_8888
},
.expectStride = 1080 * 4,
.expectSize = 1080 * 1920 * 4
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_BGRX_8888
},
.expectStride = 1080 * 4,
.expectSize = 1080 * 1920 * 4
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_RGBA_4444
},
.expectStride = 1080 * 2,
.expectSize = 1080 * 1920 * 2
},
{
.allocInfo =
{
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_RGBX_4444
},
.expectStride = 1080 * 2,
.expectSize = 1080 * 1920 * 2
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_BGRA_4444
},
.expectStride = 1080 * 2,
.expectSize = 1080 * 1920 * 2
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_BGRX_4444
},
.expectStride = 1080 * 2,
.expectSize = 1080 * 1920 * 2
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_BGR_565
},
.expectStride = 1080 * 2,
.expectSize = 1080 * 1920 * 2
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_BGRA_5551
},
.expectStride = 1080 * 2,
.expectSize = 1080 * 1920 * 2
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_BGRX_5551
},
.expectStride = 1080 * 2,
.expectSize = 1080 * 1920 * 2
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_YCBCR_420_SP
},
.expectStride = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN),
.expectSize = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN) * 1920,
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_YCRCB_420_SP
},
.expectStride = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN),
.expectSize = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN) * 1920,
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_YCBCR_420_P
},
.expectStride = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN),
.expectSize = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN) * 1920,
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_YCRCB_420_P
},
.expectStride = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN),
.expectSize = ALIGN_UP(1080 * 3 / 2, WIDTH_ALIGN) * 1920,
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA,
.format = PIXEL_FMT_RGBX_8888
},
.expectStride = 1080 * 4,
.expectSize = 1080 * 1920 * 4,
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_READ,
.format = PIXEL_FMT_RGBX_8888
},
.expectStride = 1080 * 4,
.expectSize = 1080 * 1920 * 4,
},
{
.allocInfo = {
.width = 1080,
.height = 1920,
.usage = HBM_USE_MEM_DMA | HBM_USE_CPU_WRITE,
.format = PIXEL_FMT_RGBX_8888
},
.expectStride = 1080 * 4,
.expectSize = 1080 * 1920 * 4,
},
};
static bool CheckBufferHandle(AllocTestPrms &info, BufferHandle &buffer)
{
if (buffer.stride != (ALIGN_UP(info.expectStride, WIDTH_ALIGN))) {
DISPLAY_TEST_LOGE("stride check faild stride %d, expect stride %d ", buffer.stride, info.expectStride);
DISPLAY_TEST_LOGE("stride check faild format %d width %d, height %d ", info.allocInfo.format,
info.allocInfo.width, info.allocInfo.height);
return false;
}
if (buffer.size != info.expectSize) {
DISPLAY_TEST_LOGE("size check faild size %d, expect size %d ", buffer.size, info.expectSize);
DISPLAY_TEST_LOGE("stride check faild format %d width %d, height %d ", info.allocInfo.format,
info.allocInfo.width, info.allocInfo.height);
return false;
}
return true;
}
void GrallocAllocTest::SetUp()
{
if (GrallocInitialize(&mGrallocFuncs) != DISPLAY_SUCCESS) {
DISPLAY_TEST_LOGE("DisplayInit failure\n");
ASSERT_TRUE(0);
}
}
void GrallocAllocTest::TearDown()
{
if (GrallocUninitialize(mGrallocFuncs) != DISPLAY_SUCCESS) {
DISPLAY_TEST_LOGE("DisplayUninit failure\n");
ASSERT_TRUE(0);
}
}
int32_t GrallocAllocTest::AllocMemTest(AllocTestPrms &info)
{
int ret;
BufferHandle *buffer = nullptr;
const int testCount = 1; // test 40 times
for (int i = 0; i < testCount; i++) {
ret = mGrallocFuncs->AllocMem(&info.allocInfo, &buffer);
if (ret != DISPLAY_SUCCESS) {
return ret;
}
void *vAddr = mGrallocFuncs->Mmap(buffer);
if (vAddr == nullptr) {
return DISPLAY_FAILURE;
}
if (info.allocInfo.usage & (HBM_USE_CPU_READ | HBM_USE_CPU_WRITE)) {
ret = mGrallocFuncs->InvalidateCache(buffer);
if (ret != DISPLAY_SUCCESS) {
return ret;
}
}
if (memset_s(vAddr, buffer->size, 0, buffer->size) != EOK) {
return DISPLAY_NOMEM;
}
DISPLAY_TEST_CHK_RETURN(!CheckBufferHandle(info, *buffer), DISPLAY_FAILURE,
DISPLAY_TEST_LOGE("buffer check failed"));
if (info.allocInfo.usage & (HBM_USE_CPU_READ | HBM_USE_CPU_WRITE)) {
ret = mGrallocFuncs->FlushCache(buffer);
if (ret != DISPLAY_SUCCESS) {
return ret;
}
}
mGrallocFuncs->Unmap((buffer));
mGrallocFuncs->FreeMem(buffer);
}
return DISPLAY_SUCCESS;
}
TEST(GrallocAllocTest, NULLPTR)
{
int ret = GrallocInitialize(nullptr);
ASSERT_TRUE(ret != DISPLAY_SUCCESS);
GrallocFuncs *grallocFuncs;
AllocInfo allocInfo;
BufferHandle *hdl;
ret = GrallocInitialize(&grallocFuncs);
ASSERT_TRUE(ret == DISPLAY_SUCCESS);
ret = grallocFuncs->AllocMem(nullptr, nullptr);
ASSERT_TRUE(ret != DISPLAY_SUCCESS);
ret = grallocFuncs->AllocMem(&allocInfo, nullptr);
ASSERT_TRUE(ret != DISPLAY_SUCCESS);
ret = grallocFuncs->AllocMem(nullptr, &hdl);
ASSERT_TRUE(ret != DISPLAY_SUCCESS);
ret = grallocFuncs->InvalidateCache(nullptr);
ASSERT_TRUE(ret != DISPLAY_SUCCESS);
ret = grallocFuncs->FlushCache(nullptr);
ASSERT_TRUE(ret != DISPLAY_SUCCESS);
grallocFuncs->FreeMem(nullptr);
void *vAddr = grallocFuncs->Mmap(nullptr);
ASSERT_TRUE(vAddr == nullptr);
ret = grallocFuncs->Unmap(nullptr);
ASSERT_TRUE(ret != DISPLAY_SUCCESS);
ret = GrallocUninitialize(nullptr);
ASSERT_TRUE(ret != DISPLAY_SUCCESS);
ret = GrallocUninitialize(grallocFuncs);
ASSERT_TRUE(ret == DISPLAY_SUCCESS);
}
TEST_P(GrallocAllocTest, GrallocAlloc)
{
AllocTestPrms params = GetParam();
int ret = AllocMemTest(params);
ASSERT_TRUE(ret == DISPLAY_SUCCESS);
}
INSTANTIATE_TEST_CASE_P(AllocTest, GrallocAllocTest, ::testing::ValuesIn(GRALLOC_TEST_SETS));
}
| 30.58871 | 112 | 0.544336 | openharmony-gitee-mirror |
67d366bce444367b0765be6a054c21b16dd31253 | 50,218 | cc | C++ | language/examples/pennant.cc | mmccarty/legion | 30e00fa6016527c4cf60025a461fb7865f8def6b | [
"Apache-2.0"
] | 555 | 2015-01-19T07:50:27.000Z | 2022-03-22T11:35:48.000Z | language/examples/pennant.cc | mmccarty/legion | 30e00fa6016527c4cf60025a461fb7865f8def6b | [
"Apache-2.0"
] | 1,157 | 2015-01-07T18:34:23.000Z | 2022-03-31T19:45:27.000Z | language/examples/pennant.cc | mmccarty/legion | 30e00fa6016527c4cf60025a461fb7865f8def6b | [
"Apache-2.0"
] | 145 | 2015-02-03T02:31:42.000Z | 2022-02-28T12:03:51.000Z | /* Copyright 2021 Stanford University
*
* 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 "pennant.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstring>
#include <map>
#include <vector>
#include "mappers/default_mapper.h"
#include <sys/time.h>
#include <sys/resource.h>
void print_rusage(const char *message)
{
struct rusage usage;
if (getrusage(RUSAGE_SELF, &usage) != 0) return;
printf("%s: %ld MB\n", message, usage.ru_maxrss / 1024);
}
using namespace Legion;
using namespace Legion::Mapping;
struct config {
int64_t np;
int64_t nz;
int64_t nzx;
int64_t nzy;
double lenx;
double leny;
int64_t numpcx;
int64_t numpcy;
int64_t npieces;
int64_t meshtype;
bool compact;
int64_t stripsize;
int64_t spansize;
};
enum {
MESH_PIE = 0,
MESH_RECT = 1,
MESH_HEX = 2,
};
///
/// Mesh Generator
///
/*
* Some portions of the following code are derived from the
* open-source release of PENNANT:
*
* https://github.com/losalamos/PENNANT
*/
static void generate_mesh_rect(config &conf,
std::vector<double> &pointpos_x,
std::vector<double> &pointpos_y,
std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
std::vector<int64_t> &zonestart,
std::vector<int64_t> &zonesize,
std::vector<int64_t> &zonepoints,
std::vector<int64_t> &zonecolors,
std::vector<int64_t> &zxbounds,
std::vector<int64_t> &zybounds)
{
int64_t &nz = conf.nz;
int64_t &np = conf.np;
nz = conf.nzx * conf.nzy;
const int npx = conf.nzx + 1;
const int npy = conf.nzy + 1;
np = npx * npy;
// generate point coordinates
pointpos_x.reserve(np);
pointpos_y.reserve(np);
double dx = conf.lenx / (double) conf.nzx;
double dy = conf.leny / (double) conf.nzy;
int pcy = 0;
for (int j = 0; j < npy; ++j) {
if (j >= zybounds[pcy+1]) pcy += 1;
double y = dy * (double) j;
int pcx = 0;
for (int i = 0; i < npx; ++i) {
if (i >= zxbounds[pcx+1]) pcx += 1;
double x = dx * (double) i;
pointpos_x.push_back(x);
pointpos_y.push_back(y);
int c = pcy * conf.numpcx + pcx;
if (i != zxbounds[pcx] && j != zybounds[pcy])
pointcolors.push_back(c);
else {
int p = pointpos_x.size() - 1;
pointcolors.push_back(MULTICOLOR);
std::vector<int64_t> &pmc = pointmcolors[p];
if (i == zxbounds[pcx] && j == zybounds[pcy])
pmc.push_back(c - conf.numpcx - 1);
if (j == zybounds[pcy]) pmc.push_back(c - conf.numpcx);
if (i == zxbounds[pcx]) pmc.push_back(c - 1);
pmc.push_back(c);
}
}
}
// generate zone adjacency lists
zonestart.reserve(nz);
zonesize.reserve(nz);
zonepoints.reserve(4 * nz);
zonecolors.reserve(nz);
pcy = 0;
for (int j = 0; j < conf.nzy; ++j) {
if (j >= zybounds[pcy+1]) pcy += 1;
int pcx = 0;
for (int i = 0; i < conf.nzx; ++i) {
if (i >= zxbounds[pcx+1]) pcx += 1;
zonestart.push_back(zonepoints.size());
zonesize.push_back(4);
int p0 = j * npx + i;
zonepoints.push_back(p0);
zonepoints.push_back(p0 + 1);
zonepoints.push_back(p0 + npx + 1);
zonepoints.push_back(p0 + npx);
zonecolors.push_back(pcy * conf.numpcx + pcx);
}
}
}
static void generate_mesh_pie(config &conf,
std::vector<double> &pointpos_x,
std::vector<double> &pointpos_y,
std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
std::vector<int64_t> &zonestart,
std::vector<int64_t> &zonesize,
std::vector<int64_t> &zonepoints,
std::vector<int64_t> &zonecolors,
std::vector<int64_t> &zxbounds,
std::vector<int64_t> &zybounds)
{
int64_t &nz = conf.nz;
int64_t &np = conf.np;
nz = conf.nzx * conf.nzy;
const int npx = conf.nzx + 1;
const int npy = conf.nzy + 1;
np = npx * (npy - 1) + 1;
// generate point coordinates
pointpos_x.reserve(np);
pointpos_y.reserve(np);
double dth = conf.lenx / (double) conf.nzx;
double dr = conf.leny / (double) conf.nzy;
int pcy = 0;
for (int j = 0; j < npy; ++j) {
if (j >= zybounds[pcy+1]) pcy += 1;
if (j == 0) {
// special case: "row" at origin only contains
// one point, shared by all pieces in row
pointpos_x.push_back(0.);
pointpos_y.push_back(0.);
if (conf.numpcx == 1)
pointcolors.push_back(0);
else {
pointcolors.push_back(MULTICOLOR);
std::vector<int64_t> &pmc = pointmcolors[0];
for (int c = 0; c < conf.numpcx; ++c)
pmc.push_back(c);
}
continue;
}
double r = dr * (double) j;
int pcx = 0;
for (int i = 0; i < npx; ++i) {
if (i >= zxbounds[pcx+1]) pcx += 1;
double th = dth * (double) (conf.nzx - i);
double x = r * cos(th);
double y = r * sin(th);
pointpos_x.push_back(x);
pointpos_y.push_back(y);
int c = pcy * conf.numpcx + pcx;
if (i != zxbounds[pcx] && j != zybounds[pcy])
pointcolors.push_back(c);
else {
int p = pointpos_x.size() - 1;
pointcolors.push_back(MULTICOLOR);
std::vector<int64_t> &pmc = pointmcolors[p];
if (i == zxbounds[pcx] && j == zybounds[pcy])
pmc.push_back(c - conf.numpcx - 1);
if (j == zybounds[pcy]) pmc.push_back(c - conf.numpcx);
if (i == zxbounds[pcx]) pmc.push_back(c - 1);
pmc.push_back(c);
}
}
}
// generate zone adjacency lists
zonestart.reserve(nz);
zonesize.reserve(nz);
zonepoints.reserve(4 * nz);
zonecolors.reserve(nz);
pcy = 0;
for (int j = 0; j < conf.nzy; ++j) {
if (j >= zybounds[pcy+1]) pcy += 1;
int pcx = 0;
for (int i = 0; i < conf.nzx; ++i) {
if (i >= zxbounds[pcx+1]) pcx += 1;
zonestart.push_back(zonepoints.size());
int p0 = j * npx + i - (npx - 1);
if (j == 0) {
zonesize.push_back(3);
zonepoints.push_back(0);
}
else {
zonesize.push_back(4);
zonepoints.push_back(p0);
zonepoints.push_back(p0 + 1);
}
zonepoints.push_back(p0 + npx + 1);
zonepoints.push_back(p0 + npx);
zonecolors.push_back(pcy * conf.numpcx + pcx);
}
}
}
static void generate_mesh_hex(config &conf,
std::vector<double> &pointpos_x,
std::vector<double> &pointpos_y,
std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
std::vector<int64_t> &zonestart,
std::vector<int64_t> &zonesize,
std::vector<int64_t> &zonepoints,
std::vector<int64_t> &zonecolors,
std::vector<int64_t> &zxbounds,
std::vector<int64_t> &zybounds)
{
int64_t &nz = conf.nz;
int64_t &np = conf.np;
nz = conf.nzx * conf.nzy;
const int npx = conf.nzx + 1;
const int npy = conf.nzy + 1;
// generate point coordinates
pointpos_x.resize(2 * npx * npy); // upper bound
pointpos_y.resize(2 * npx * npy); // upper bound
double dx = conf.lenx / (double) (conf.nzx - 1);
double dy = conf.leny / (double) (conf.nzy - 1);
std::vector<int64_t> pbase(npy);
int p = 0;
int pcy = 0;
for (int j = 0; j < npy; ++j) {
if (j >= zybounds[pcy+1]) pcy += 1;
pbase[j] = p;
double y = dy * ((double) j - 0.5);
y = std::max(0., std::min(conf.leny, y));
int pcx = 0;
for (int i = 0; i < npx; ++i) {
if (i >= zxbounds[pcx+1]) pcx += 1;
double x = dx * ((double) i - 0.5);
x = std::max(0., std::min(conf.lenx, x));
int c = pcy * conf.numpcx + pcx;
if (i == 0 || i == conf.nzx || j == 0 || j == conf.nzy) {
pointpos_x[p] = x;
pointpos_y[p++] = y;
if (i != zxbounds[pcx] && j != zybounds[pcy])
pointcolors.push_back(c);
else {
int p1 = p - 1;
pointcolors.push_back(MULTICOLOR);
std::vector<int64_t> &pmc = pointmcolors[p1];
if (j == zybounds[pcy]) pmc.push_back(c - conf.numpcx);
if (i == zxbounds[pcx]) pmc.push_back(c - 1);
pmc.push_back(c);
}
}
else {
pointpos_x[p] = x - dx / 6.;
pointpos_y[p++] = y + dy / 6.;
pointpos_x[p] = x + dx / 6.;
pointpos_y[p++] = y - dy / 6.;
if (i != zxbounds[pcx] && j != zybounds[pcy]) {
pointcolors.push_back(c);
pointcolors.push_back(c);
}
else {
int p1 = p - 2;
int p2 = p - 1;
pointcolors.push_back(MULTICOLOR);
pointcolors.push_back(MULTICOLOR);
std::vector<int64_t> &pmc1 = pointmcolors[p1];
std::vector<int64_t> &pmc2 = pointmcolors[p2];
if (i == zxbounds[pcx] && j == zybounds[pcy]) {
pmc1.push_back(c - conf.numpcx - 1);
pmc2.push_back(c - conf.numpcx - 1);
pmc1.push_back(c - 1);
pmc2.push_back(c - conf.numpcx);
}
else if (j == zybounds[pcy]) {
pmc1.push_back(c - conf.numpcx);
pmc2.push_back(c - conf.numpcx);
}
else { // i == zxbounds[pcx]
pmc1.push_back(c - 1);
pmc2.push_back(c - 1);
}
pmc1.push_back(c);
pmc2.push_back(c);
}
}
} // for i
} // for j
np = p;
pointpos_x.resize(np);
pointpos_y.resize(np);
// generate zone adjacency lists
zonestart.resize(nz);
zonesize.resize(nz);
zonepoints.reserve(6 * nz); // upper bound
zonecolors.reserve(nz);
pcy = 0;
for (int j = 0; j < conf.nzy; ++j) {
if (j >= zybounds[pcy+1]) pcy += 1;
int pbasel = pbase[j];
int pbaseh = pbase[j+1];
int pcx = 0;
for (int i = 0; i < conf.nzx; ++i) {
if (i >= zxbounds[pcx+1]) pcx += 1;
int z = j * conf.nzx + i;
std::vector<int64_t> v(6);
v[1] = pbasel + 2 * i;
v[0] = v[1] - 1;
v[2] = v[1] + 1;
v[5] = pbaseh + 2 * i;
v[4] = v[5] + 1;
v[3] = v[4] + 1;
if (j == 0) {
v[0] = pbasel + i;
v[2] = v[0] + 1;
if (i == conf.nzx - 1) v.erase(v.begin()+3);
v.erase(v.begin()+1);
} // if j
else if (j == conf.nzy - 1) {
v[5] = pbaseh + i;
v[3] = v[5] + 1;
v.erase(v.begin()+4);
if (i == 0) v.erase(v.begin()+0);
} // else if j
else if (i == 0)
v.erase(v.begin()+0);
else if (i == conf.nzx - 1)
v.erase(v.begin()+3);
zonestart[z] = zonepoints.size();
zonesize[z] = v.size();
zonepoints.insert(zonepoints.end(), v.begin(), v.end());
zonecolors.push_back(pcy * conf.numpcx + pcx);
} // for i
} // for j
}
static void calc_mesh_num_pieces(config &conf)
{
// pick numpcx, numpcy such that pieces are as close to square
// as possible
// we would like: nzx / numpcx == nzy / numpcy,
// where numpcx * numpcy = npieces (total number of pieces)
// this solves to: numpcx = sqrt(npieces * nzx / nzy)
// we compute this, assuming nzx <= nzy (swap if necessary)
double nx = static_cast<double>(conf.nzx);
double ny = static_cast<double>(conf.nzy);
bool swapflag = (nx > ny);
if (swapflag) std::swap(nx, ny);
double n = sqrt(conf.npieces * nx / ny);
// need to constrain n to be an integer with npieces % n == 0
// try rounding n both up and down
int n1 = floor(n + 1.e-12);
n1 = std::max(n1, 1);
while (conf.npieces % n1 != 0) --n1;
int n2 = ceil(n - 1.e-12);
while (conf.npieces % n2 != 0) ++n2;
// pick whichever of n1 and n2 gives blocks closest to square,
// i.e. gives the shortest long side
double longside1 = std::max(nx / n1, ny / (conf.npieces/n1));
double longside2 = std::max(nx / n2, ny / (conf.npieces/n2));
conf.numpcx = (longside1 <= longside2 ? n1 : n2);
conf.numpcy = conf.npieces / conf.numpcx;
if (swapflag) std::swap(conf.numpcx, conf.numpcy);
}
static void generate_mesh(config &conf,
std::vector<double> &pointpos_x,
std::vector<double> &pointpos_y,
std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
std::vector<int64_t> &zonestart,
std::vector<int64_t> &zonesize,
std::vector<int64_t> &zonepoints,
std::vector<int64_t> &zonecolors)
{
// Do calculations common to all mesh types:
std::vector<int64_t> zxbounds;
std::vector<int64_t> zybounds;
if (conf.numpcx <= 0 || conf.numpcy <= 0) {
calc_mesh_num_pieces(conf);
}
zxbounds.push_back(-1);
for (int pcx = 1; pcx < conf.numpcx; ++pcx)
zxbounds.push_back(pcx * conf.nzx / conf.numpcx);
zxbounds.push_back(conf.nzx + 1);
zybounds.push_back(-1);
for (int pcy = 1; pcy < conf.numpcy; ++pcy)
zybounds.push_back(pcy * conf.nzy / conf.numpcy);
zybounds.push_back(0x7FFFFFFF);
// Mesh type-specific calculations:
if (conf.meshtype == MESH_PIE) {
generate_mesh_pie(conf, pointpos_x, pointpos_y, pointcolors, pointmcolors,
zonestart, zonesize, zonepoints, zonecolors,
zxbounds, zybounds);
} else if (conf.meshtype == MESH_RECT) {
generate_mesh_rect(conf, pointpos_x, pointpos_y, pointcolors, pointmcolors,
zonestart, zonesize, zonepoints, zonecolors,
zxbounds, zybounds);
} else if (conf.meshtype == MESH_HEX) {
generate_mesh_hex(conf, pointpos_x, pointpos_y, pointcolors, pointmcolors,
zonestart, zonesize, zonepoints, zonecolors,
zxbounds, zybounds);
}
}
static void sort_zones_by_color(const config &conf,
const std::vector<int64_t> &zonecolors,
std::vector<int64_t> &zones_inverse_map,
std::vector<int64_t> &zones_map)
{
// Sort zones by color.
assert(int64_t(zonecolors.size()) == conf.nz);
std::map<int64_t, std::vector<int64_t> > zones_by_color;
for (int64_t z = 0; z < conf.nz; z++) {
zones_by_color[zonecolors[z]].push_back(z);
}
for (int64_t c = 0; c < conf.npieces; c++) {
std::vector<int64_t> &zones = zones_by_color[c];
for (std::vector<int64_t>::iterator zt = zones.begin(), ze = zones.end();
zt != ze; ++zt) {
int64_t z = *zt;
assert(zones_map[z] == -1ll);
zones_map[z] = zones_inverse_map.size();
zones_inverse_map.push_back(z);
}
}
}
static std::set<int64_t> zone_point_set(
int64_t z,
const std::vector<int64_t> &zonestart,
const std::vector<int64_t> &zonesize,
const std::vector<int64_t> &zonepoints)
{
std::set<int64_t> points;
for (int64_t z_start = zonestart[z], z_size = zonesize[z],
z_point = z_start; z_point < z_start + z_size; z_point++) {
points.insert(zonepoints[z_point]);
}
return points;
}
static void sort_zones_by_color_strip(const config &conf,
const std::vector<double> &pointpos_x,
const std::vector<double> &pointpos_y,
const std::vector<int64_t> &zonestart,
const std::vector<int64_t> &zonesize,
const std::vector<int64_t> &zonepoints,
const std::vector<int64_t> &zonecolors,
std::vector<int64_t> &zones_inverse_map,
std::vector<int64_t> &zones_map)
{
int64_t stripsize = conf.stripsize;
// Sort zones by color. Within each color, make strips of zones of
// size stripsize.
std::vector<std::vector<int64_t> > strips;
assert(int64_t(zonecolors.size()) == conf.nz);
for (int64_t c = 0; c < conf.npieces; c++) {
strips.assign(strips.size(), std::vector<int64_t>());
int64_t z_start = -1ll;
std::set<int64_t> z_start_points;
for (int64_t z = 0; z < conf.nz; z++) {
if (zonecolors[z] == c) {
if (z_start >= 0) {
if (z > z_start + 1) {
bool intersect = false;
for (int64_t z_start = zonestart[z], z_size = zonesize[z],
z_point = z_start; z_point < z_start + z_size; z_point++) {
if (z_start_points.count(zonepoints[z_point])) {
intersect = true;
break;
}
}
if (intersect) {
z_start = z;
z_start_points =
zone_point_set(z_start, zonestart, zonesize, zonepoints);
}
}
} else {
z_start = z;
z_start_points =
zone_point_set(z_start, zonestart, zonesize, zonepoints);
}
int64_t strip = (z - z_start)/stripsize;
if (strip + 1 > int64_t(strips.size())) {
strips.resize(strip+1);
}
strips[strip].push_back(z);
}
}
for (std::vector<std::vector<int64_t> >::iterator st = strips.begin(),
se = strips.end(); st != se; ++st) {
for (std::vector<int64_t>::iterator zt = st->begin(), ze = st->end();
zt != ze; ++zt) {
int64_t z = *zt;
assert(zones_map[z] == -1ll);
zones_map[z] = zones_inverse_map.size();
zones_inverse_map.push_back(z);
}
}
}
}
static void sort_points_by_color(
const config &conf,
const std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
std::vector<int64_t> &points_inverse_map,
std::vector<int64_t> &points_map)
{
// Sort points by color; sort multi-color points by first color.
assert(int64_t(pointcolors.size()) == conf.np);
std::map<int64_t, std::vector<int64_t> > points_by_color;
std::map<int64_t, std::vector<int64_t> > points_by_multicolor;
for (int64_t p = 0; p < conf.np; p++) {
if (pointcolors[p] == MULTICOLOR) {
points_by_multicolor[pointmcolors[p][0]].push_back(p);
} else {
points_by_color[pointcolors[p]].push_back(p);
}
}
for (int64_t c = 0; c < conf.npieces; c++) {
std::vector<int64_t> &points = points_by_multicolor[c];
for (std::vector<int64_t>::iterator pt = points.begin(), pe = points.end();
pt != pe; ++pt) {
int64_t p = *pt;
assert(points_map[p] == -1ll);
points_map[p] = points_inverse_map.size();
points_inverse_map.push_back(p);
}
}
for (int64_t c = 0; c < conf.npieces; c++) {
std::vector<int64_t> &points = points_by_color[c];
for (std::vector<int64_t>::iterator pt = points.begin(), pe = points.end();
pt != pe; ++pt) {
int64_t p = *pt;
assert(points_map[p] == -1ll);
points_map[p] = points_inverse_map.size();
points_inverse_map.push_back(p);
}
}
}
static void compact_mesh(const config &conf,
std::vector<double> &pointpos_x,
std::vector<double> &pointpos_y,
std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
std::vector<int64_t> &zonestart,
std::vector<int64_t> &zonesize,
std::vector<int64_t> &zonepoints,
std::vector<int64_t> &zonecolors)
{
// This stage is responsible for compacting the mesh so that each of
// the pieces is dense (in the global coordinate space). This
// involves sorting the various elements by color and then rewriting
// the various pointers to be internally consistent again.
// Sort zones by color.
std::vector<int64_t> zones_inverse_map;
std::vector<int64_t> zones_map(conf.nz, -1ll);
if (conf.stripsize > 0) {
sort_zones_by_color_strip(conf, pointpos_x, pointpos_y,
zonestart, zonesize, zonepoints, zonecolors,
zones_inverse_map, zones_map);
} else {
sort_zones_by_color(conf, zonecolors, zones_inverse_map, zones_map);
}
assert(int64_t(zones_inverse_map.size()) == conf.nz);
// Sort points by color; sort multi-color points by first color.
std::vector<int64_t> points_inverse_map;
std::vector<int64_t> points_map(conf.np, -1ll);
sort_points_by_color(conf, pointcolors, pointmcolors,
points_inverse_map, points_map);
assert(int64_t(points_inverse_map.size()) == conf.np);
// Various sanity checks.
#if 0
for (int64_t z = 0; z < conf.nz; z++) {
printf("zone old %ld new %ld color %ld\n", z, zones_map[z], zonecolors[z]);
}
printf("\n");
for (int64_t newz = 0; newz < conf.nz; newz++) {
int64_t oldz = zones_inverse_map[newz];
printf("zone new %ld old %ld color %ld\n", newz, oldz, zonecolors[oldz]);
}
printf("\n");
for (int64_t p = 0; p < conf.np; p++) {
printf("point old %ld new %ld color %ld\n", p, points_map[p], pointcolors[p]);
}
printf("\n");
for (int64_t newp = 0; newp < conf.np; newp++) {
int64_t oldp = points_inverse_map[newp];
printf("point new %ld old %ld color %ld\n", newp, oldp, pointcolors[oldp]);
}
#endif
// Project zones through the zones map.
{
std::vector<int64_t> old_zonestart = zonestart;
for (int64_t newz = 0; newz < conf.nz; newz++) {
int64_t oldz = zones_inverse_map[newz];
zonestart[newz] = old_zonestart[oldz];
}
}
{
std::vector<int64_t> old_zonesize = zonesize;
for (int64_t newz = 0; newz < conf.nz; newz++) {
int64_t oldz = zones_inverse_map[newz];
zonesize[newz] = old_zonesize[oldz];
}
}
{
std::vector<int64_t> old_zonepoints = zonepoints;
int64_t nzp = zonepoints.size();
for (int64_t zp = 0; zp < nzp; zp++) {
zonepoints[zp] = points_map[old_zonepoints[zp]];
}
}
{
std::vector<int64_t> old_zonecolors = zonecolors;
for (int64_t newz = 0; newz < conf.nz; newz++) {
int64_t oldz = zones_inverse_map[newz];
zonecolors[newz] = old_zonecolors[oldz];
}
}
// Project points through the points map.
{
std::vector<double> old_pointpos_x = pointpos_x;
for (int64_t newp = 0; newp < conf.np; newp++) {
int64_t oldp = points_inverse_map[newp];
pointpos_x[newp] = old_pointpos_x[oldp];
}
}
{
std::vector<double> old_pointpos_y = pointpos_y;
for (int64_t newp = 0; newp < conf.np; newp++) {
int64_t oldp = points_inverse_map[newp];
pointpos_y[newp] = old_pointpos_y[oldp];
}
}
{
std::vector<int64_t> old_pointcolors = pointcolors;
for (int64_t newp = 0; newp < conf.np; newp++) {
int64_t oldp = points_inverse_map[newp];
pointcolors[newp] = old_pointcolors[oldp];
}
}
{
std::map<int64_t, std::vector<int64_t> > old_pointmcolors = pointmcolors;
for (int64_t newp = 0; newp < conf.np; newp++) {
int64_t oldp = points_inverse_map[newp];
pointmcolors[newp] = old_pointmcolors[oldp];
}
}
}
static void
color_spans(const config &conf,
const std::vector<double> &pointpos_x,
const std::vector<double> &pointpos_y,
const std::vector<int64_t> &pointcolors,
std::map<int64_t, std::vector<int64_t> > &pointmcolors,
const std::vector<int64_t> &zonestart,
const std::vector<int64_t> &zonesize,
const std::vector<int64_t> &zonepoints,
const std::vector<int64_t> &zonecolors,
std::vector<int64_t> &zonespancolors_vec,
std::vector<int64_t> &pointspancolors_vec,
int64_t &nspans_zones,
int64_t &nspans_points)
{
{
// Compute zone spans.
std::vector<std::vector<std::vector<int64_t> > > spans(conf.npieces);
std::vector<int64_t> span_size(conf.npieces, conf.spansize);
for (int64_t z = 0; z < conf.nz; z++) {
int64_t c = zonecolors[z];
if (span_size[c] + zonesize[c] > conf.spansize) {
spans[c].resize(spans[c].size() + 1);
span_size[c] = 0;
}
spans[c][spans[c].size() - 1].push_back(z);
span_size[c] += zonesize[z];
}
// Color zones by span.
nspans_zones = 0;
zonespancolors_vec.assign(conf.nz, -1ll);
for (int64_t c = 0; c < conf.npieces; c++) {
std::vector<std::vector<int64_t> > &color_spans = spans[c];
int64_t nspans = color_spans.size();
nspans_zones = std::max(nspans_zones, nspans);
for (int64_t ispan = 0; ispan < nspans; ispan++) {
std::vector<int64_t> &span = color_spans[ispan];
for (std::vector<int64_t>::iterator zt = span.begin(), ze = span.end();
zt != ze; ++zt) {
int64_t z = *zt;
zonespancolors_vec[z] = ispan;
}
}
}
for (int64_t z = 0; z < conf.nz; z++) {
assert(zonespancolors_vec[z] != -1ll);
}
}
{
// Compute point spans.
std::vector<std::vector<std::vector<int64_t> > > spans(conf.npieces);
std::vector<std::vector<std::vector<int64_t> > > mspans(conf.npieces);
std::vector<int64_t> span_size(conf.npieces, conf.spansize);
std::vector<int64_t> mspan_size(conf.npieces, conf.spansize);
for (int64_t p = 0; p < conf.np; p++) {
int64_t c = pointcolors[p];
if (c != MULTICOLOR) {
if (span_size[c] >= conf.spansize) {
spans[c].resize(spans[c].size() + 1);
span_size[c] = 0;
}
spans[c][spans[c].size() - 1].push_back(p);
span_size[c]++;
} else {
c = pointmcolors[p][0];
if (mspan_size[c] >= conf.spansize) {
mspans[c].resize(mspans[c].size() + 1);
mspan_size[c] = 0;
}
mspans[c][mspans[c].size() - 1].push_back(p);
mspan_size[c]++;
}
}
// Color points by span.
nspans_points = 0;
pointspancolors_vec.assign(conf.np, -1ll);
for (int64_t c = 0; c < conf.npieces; c++) {
std::vector<std::vector<int64_t> > &color_spans = spans[c];
int64_t nspans = color_spans.size();
nspans_points = std::max(nspans_points, nspans);
for (int64_t ispan = 0; ispan < nspans; ispan++) {
std::vector<int64_t> &span = color_spans[ispan];
for (std::vector<int64_t>::iterator pt = span.begin(), pe = span.end();
pt != pe; ++pt) {
int64_t p = *pt;
pointspancolors_vec[p] = ispan;
}
}
}
for (int64_t c = 0; c < conf.npieces; c++) {
std::vector<std::vector<int64_t> > &color_spans = mspans[c];
int64_t nspans = color_spans.size();
nspans_points = std::max(nspans_points, nspans);
for (int64_t ispan = 0; ispan < nspans; ispan++) {
std::vector<int64_t> &span = color_spans[ispan];
for (std::vector<int64_t>::iterator pt = span.begin(), pe = span.end();
pt != pe; ++pt) {
int64_t p = *pt;
pointspancolors_vec[p] = ispan;
}
}
}
for (int64_t p = 0; p < conf.np; p++) {
assert(pointspancolors_vec[p] != -1ll);
}
}
}
void generate_mesh_raw(
int64_t conf_np,
int64_t conf_nz,
int64_t conf_nzx,
int64_t conf_nzy,
double conf_lenx,
double conf_leny,
int64_t conf_numpcx,
int64_t conf_numpcy,
int64_t conf_npieces,
int64_t conf_meshtype,
bool conf_compact,
int64_t conf_stripsize,
int64_t conf_spansize,
double *pointpos_x, size_t *pointpos_x_size,
double *pointpos_y, size_t *pointpos_y_size,
int64_t *pointcolors, size_t *pointcolors_size,
uint64_t *pointmcolors, size_t *pointmcolors_size,
int64_t *pointspancolors, size_t *pointspancolors_size,
int64_t *zonestart, size_t *zonestart_size,
int64_t *zonesize, size_t *zonesize_size,
int64_t *zonepoints, size_t *zonepoints_size,
int64_t *zonecolors, size_t *zonecolors_size,
int64_t *zonespancolors, size_t *zonespancolors_size,
int64_t *nspans_zones,
int64_t *nspans_points)
{
config conf;
conf.np = conf_np;
conf.nz = conf_nz;
conf.nzx = conf_nzx;
conf.nzy = conf_nzy;
conf.lenx = conf_lenx;
conf.leny = conf_leny;
conf.numpcx = conf_numpcx;
conf.numpcy = conf_numpcy;
conf.npieces = conf_npieces;
conf.meshtype = conf_meshtype;
conf.compact = conf_compact;
conf.stripsize = conf_stripsize;
conf.spansize = conf_spansize;
std::vector<double> pointpos_x_vec;
std::vector<double> pointpos_y_vec;
std::vector<int64_t> pointcolors_vec;
std::map<int64_t, std::vector<int64_t> > pointmcolors_map;
std::vector<int64_t> zonestart_vec;
std::vector<int64_t> zonesize_vec;
std::vector<int64_t> zonepoints_vec;
std::vector<int64_t> zonecolors_vec;
generate_mesh(conf,
pointpos_x_vec,
pointpos_y_vec,
pointcolors_vec,
pointmcolors_map,
zonestart_vec,
zonesize_vec,
zonepoints_vec,
zonecolors_vec);
if (conf.compact) {
compact_mesh(conf,
pointpos_x_vec,
pointpos_y_vec,
pointcolors_vec,
pointmcolors_map,
zonestart_vec,
zonesize_vec,
zonepoints_vec,
zonecolors_vec);
}
std::vector<int64_t> zonespancolors_vec;
std::vector<int64_t> pointspancolors_vec;
color_spans(conf,
pointpos_x_vec,
pointpos_y_vec,
pointcolors_vec,
pointmcolors_map,
zonestart_vec,
zonesize_vec,
zonepoints_vec,
zonecolors_vec,
zonespancolors_vec,
pointspancolors_vec,
*nspans_zones,
*nspans_points);
int64_t color_words = int64_t(ceil(conf_npieces/64.0));
assert(pointpos_x_vec.size() <= *pointpos_x_size);
assert(pointpos_y_vec.size() <= *pointpos_y_size);
assert(pointcolors_vec.size() <= *pointcolors_size);
assert(pointcolors_vec.size()*color_words <= *pointmcolors_size);
assert(pointspancolors_vec.size() <= *pointspancolors_size);
assert(zonestart_vec.size() <= *zonestart_size);
assert(zonesize_vec.size() <= *zonesize_size);
assert(zonepoints_vec.size() <= *zonepoints_size);
assert(zonecolors_vec.size() <= *zonecolors_size);
assert(zonespancolors_vec.size() <= *zonespancolors_size);
memcpy(pointpos_x, pointpos_x_vec.data(), pointpos_x_vec.size()*sizeof(double));
memcpy(pointpos_y, pointpos_y_vec.data(), pointpos_y_vec.size()*sizeof(double));
memcpy(pointcolors, pointcolors_vec.data(), pointcolors_vec.size()*sizeof(int64_t));
memcpy(pointspancolors, pointspancolors_vec.data(), pointspancolors_vec.size()*sizeof(int64_t));
memcpy(zonestart, zonestart_vec.data(), zonestart_vec.size()*sizeof(int64_t));
memcpy(zonesize, zonesize_vec.data(), zonesize_vec.size()*sizeof(int64_t));
memcpy(zonepoints, zonepoints_vec.data(), zonepoints_vec.size()*sizeof(int64_t));
memcpy(zonecolors, zonecolors_vec.data(), zonecolors_vec.size()*sizeof(int64_t));
memcpy(zonespancolors, zonespancolors_vec.data(), zonespancolors_vec.size()*sizeof(int64_t));
memset(pointmcolors, 0, (*pointmcolors_size)*sizeof(uint64_t));
for (std::map<int64_t, std::vector<int64_t> >::iterator it = pointmcolors_map.begin(),
ie = pointmcolors_map.end(); it != ie; ++it) {
int64_t p = it->first;
for (std::vector<int64_t>::iterator ct = it->second.begin(),
ce = it->second.end(); ct != ce; ++ct) {
int64_t word = (*ct) / 64.0;
int64_t bit = (*ct) % 64;
pointmcolors[p + word] |= (1 << bit);
}
}
*pointpos_x_size = pointpos_x_vec.size();
*pointpos_y_size = pointpos_y_vec.size();
*pointcolors_size = pointcolors_vec.size();
*pointmcolors_size = pointcolors_vec.size()*color_words;
*pointspancolors_size = pointspancolors_vec.size();
*zonestart_size = zonestart_vec.size();
*zonesize_size = zonesize_vec.size();
*zonepoints_size = zonepoints_vec.size();
*zonecolors_size = zonecolors_vec.size();
*zonespancolors_size = zonespancolors_vec.size();
}
///
/// Mapper
///
#define SPMD_SHARD_USE_IO_PROC 0
static LegionRuntime::Logger::Category log_pennant("pennant");
class PennantMapper : public DefaultMapper
{
public:
PennantMapper(MapperRuntime *rt, Machine machine, Processor local,
const char *mapper_name,
std::vector<Processor>* procs_list,
std::vector<Memory>* sysmems_list,
std::map<Memory, std::vector<Processor> >* sysmem_local_procs,
#if SPMD_SHARD_USE_IO_PROC
std::map<Memory, std::vector<Processor> >* sysmem_local_io_procs,
#endif
std::map<Processor, Memory>* proc_sysmems,
std::map<Processor, Memory>* proc_regmems);
virtual void default_policy_rank_processor_kinds(
MapperContext ctx, const Task &task,
std::vector<Processor::Kind> &ranking);
virtual Processor default_policy_select_initial_processor(
MapperContext ctx, const Task &task);
virtual void default_policy_select_target_processors(
MapperContext ctx,
const Task &task,
std::vector<Processor> &target_procs);
virtual LogicalRegion default_policy_select_instance_region(
MapperContext ctx, Memory target_memory,
const RegionRequirement &req,
const LayoutConstraintSet &constraints,
bool force_new_instances,
bool meets_constraints);
virtual void map_copy(const MapperContext ctx,
const Copy ©,
const MapCopyInput &input,
MapCopyOutput &output);
virtual void map_must_epoch(const MapperContext ctx,
const MapMustEpochInput& input,
MapMustEpochOutput& output);
template<bool IS_SRC>
void pennant_create_copy_instance(MapperContext ctx, const Copy ©,
const RegionRequirement &req, unsigned index,
std::vector<PhysicalInstance> &instances);
private:
std::vector<Processor>& procs_list;
std::vector<Memory>& sysmems_list;
std::map<Memory, std::vector<Processor> >& sysmem_local_procs;
#if SPMD_SHARD_USE_IO_PROC
std::map<Memory, std::vector<Processor> >& sysmem_local_io_procs;
#endif
std::map<Processor, Memory>& proc_sysmems;
// std::map<Processor, Memory>& proc_regmems;
};
PennantMapper::PennantMapper(MapperRuntime *rt, Machine machine, Processor local,
const char *mapper_name,
std::vector<Processor>* _procs_list,
std::vector<Memory>* _sysmems_list,
std::map<Memory, std::vector<Processor> >* _sysmem_local_procs,
#if SPMD_SHARD_USE_IO_PROC
std::map<Memory, std::vector<Processor> >* _sysmem_local_io_procs,
#endif
std::map<Processor, Memory>* _proc_sysmems,
std::map<Processor, Memory>* _proc_regmems)
: DefaultMapper(rt, machine, local, mapper_name),
procs_list(*_procs_list),
sysmems_list(*_sysmems_list),
sysmem_local_procs(*_sysmem_local_procs),
#if SPMD_SHARD_USE_IO_PROC
sysmem_local_io_procs(*_sysmem_local_io_procs),
#endif
proc_sysmems(*_proc_sysmems)// ,
// proc_regmems(*_proc_regmems)
{
}
void PennantMapper::default_policy_rank_processor_kinds(MapperContext ctx,
const Task &task, std::vector<Processor::Kind> &ranking)
{
#if SPMD_SHARD_USE_IO_PROC
const char* task_name = task.get_task_name();
const char* prefix = "shard_";
if (strncmp(task_name, prefix, strlen(prefix)) == 0) {
// Put shard tasks on IO processors.
ranking.resize(5);
ranking[0] = Processor::TOC_PROC;
ranking[1] = Processor::PROC_SET;
ranking[2] = Processor::IO_PROC;
ranking[3] = Processor::LOC_PROC;
ranking[4] = Processor::PY_PROC;
} else {
#endif
ranking.resize(5);
ranking[0] = Processor::TOC_PROC;
ranking[1] = Processor::PROC_SET;
ranking[2] = Processor::LOC_PROC;
ranking[3] = Processor::IO_PROC;
ranking[4] = Processor::PY_PROC;
#if SPMD_SHARD_USE_IO_PROC
}
#endif
}
Processor PennantMapper::default_policy_select_initial_processor(
MapperContext ctx, const Task &task)
{
if (!task.regions.empty()) {
if (task.regions[0].handle_type == SINGULAR) {
Color index = runtime->get_logical_region_color(ctx, task.regions[0].region);
#define NO_SPMD 0
#if NO_SPMD
return procs_list[index % procs_list.size()];
#else
std::vector<Processor> &local_procs =
sysmem_local_procs[proc_sysmems[local_proc]];
if (local_procs.size() > 1) {
#define SPMD_RESERVE_SHARD_PROC 0
#if SPMD_RESERVE_SHARD_PROC
return local_procs[(index % (local_procs.size() - 1)) + 1];
#else
return local_procs[index % local_procs.size()];
#endif
} else if (local_procs.size() > 0) { // FIXME: This check seems to be required when using Python processors
return local_procs[0];
}
#endif
}
}
return DefaultMapper::default_policy_select_initial_processor(ctx, task);
}
void PennantMapper::default_policy_select_target_processors(
MapperContext ctx,
const Task &task,
std::vector<Processor> &target_procs)
{
target_procs.push_back(task.target_proc);
}
LogicalRegion PennantMapper::default_policy_select_instance_region(
MapperContext ctx, Memory target_memory,
const RegionRequirement &req,
const LayoutConstraintSet &layout_constraints,
bool force_new_instances,
bool meets_constraints)
{
return req.region;
}
//--------------------------------------------------------------------------
template<bool IS_SRC>
void PennantMapper::pennant_create_copy_instance(MapperContext ctx,
const Copy ©, const RegionRequirement &req,
unsigned idx, std::vector<PhysicalInstance> &instances)
//--------------------------------------------------------------------------
{
// This method is identical to the default version except that it
// chooses an intelligent memory based on the destination of the
// copy.
// See if we have all the fields covered
std::set<FieldID> missing_fields = req.privilege_fields;
for (std::vector<PhysicalInstance>::const_iterator it =
instances.begin(); it != instances.end(); it++)
{
it->remove_space_fields(missing_fields);
if (missing_fields.empty())
break;
}
if (missing_fields.empty())
return;
// If we still have fields, we need to make an instance
// We clearly need to take a guess, let's see if we can find
// one of our instances to use.
// ELLIOTT: Get the remote node here.
Color index = runtime->get_logical_region_color(ctx, copy.src_requirements[idx].region);
// #if SPMD_RESERVE_SHARD_PROC
// size_t sysmem_index = index / (std::max(sysmem_local_procs.begin()->second.size() - 1, (size_t)1));
// #else
// size_t sysmem_index = index / sysmem_local_procs.begin()->second.size();
// #endif
// assert(sysmem_index < sysmems_list.size());
// Memory target_memory = sysmems_list[sysmem_index];
Memory target_memory = default_policy_select_target_memory(ctx,
procs_list[index % procs_list.size()],
req);
log_pennant.spew("Building instance for copy of a region with index %u to be in memory %llx",
index, target_memory.id);
bool force_new_instances = false;
LayoutConstraintID our_layout_id =
default_policy_select_layout_constraints(ctx, target_memory,
req, COPY_MAPPING,
true/*needs check*/,
force_new_instances);
LayoutConstraintSet creation_constraints =
runtime->find_layout_constraints(ctx, our_layout_id);
creation_constraints.add_constraint(
FieldConstraint(missing_fields,
false/*contig*/, false/*inorder*/));
instances.resize(instances.size() + 1);
if (!default_make_instance(ctx, target_memory,
creation_constraints, instances.back(),
COPY_MAPPING, force_new_instances, true/*meets*/, req))
{
// If we failed to make it that is bad
log_pennant.error("Pennant mapper failed allocation for "
"%s region requirement %d of explicit "
"region-to-region copy operation in task %s "
"(ID %lld) in memory " IDFMT " for processor "
IDFMT ". This means the working set of your "
"application is too big for the allotted "
"capacity of the given memory under the default "
"mapper's mapping scheme. You have three "
"choices: ask Realm to allocate more memory, "
"write a custom mapper to better manage working "
"sets, or find a bigger machine. Good luck!",
IS_SRC ? "source" : "destination", idx,
copy.parent_task->get_task_name(),
copy.parent_task->get_unique_id(),
target_memory.id,
copy.parent_task->current_proc.id);
assert(false);
}
}
void PennantMapper::map_copy(const MapperContext ctx,
const Copy ©,
const MapCopyInput &input,
MapCopyOutput &output)
{
log_pennant.spew("Pennant mapper map_copy");
for (unsigned idx = 0; idx < copy.src_requirements.size(); idx++)
{
// Use a virtual instance for the source unless source is
// restricted or we'd applying a reduction.
output.src_instances[idx].clear();
if (copy.src_requirements[idx].is_restricted()) {
// If it's restricted, just take the instance. This will only
// happen inside the shard task.
output.src_instances[idx] = input.src_instances[idx];
if (!output.src_instances[idx].empty())
runtime->acquire_and_filter_instances(ctx,
output.src_instances[idx]);
} else if (copy.dst_requirements[idx].privilege == REDUCE) {
// Use the default here. This will place the instance on the
// current node.
default_create_copy_instance<true/*is src*/>(ctx, copy,
copy.src_requirements[idx], idx, output.src_instances[idx]);
} else {
output.src_instances[idx].push_back(
PhysicalInstance::get_virtual_instance());
}
// Place the destination instance on the remote node.
output.dst_instances[idx].clear();
if (!copy.dst_requirements[idx].is_restricted()) {
// Call a customized method to create an instance on the desired node.
pennant_create_copy_instance<false/*is src*/>(ctx, copy,
copy.dst_requirements[idx], idx, output.dst_instances[idx]);
} else {
// If it's restricted, just take the instance. This will only
// happen inside the shard task.
output.dst_instances[idx] = input.dst_instances[idx];
if (!output.dst_instances[idx].empty())
runtime->acquire_and_filter_instances(ctx,
output.dst_instances[idx]);
}
}
}
void PennantMapper::map_must_epoch(const MapperContext ctx,
const MapMustEpochInput& input,
MapMustEpochOutput& output)
{
size_t num_nodes = sysmems_list.size();
size_t num_tasks = input.tasks.size();
size_t num_shards_per_node =
num_nodes < input.tasks.size() ? (num_tasks + num_nodes - 1) / num_nodes : 1;
std::map<const Task*, size_t> task_indices;
for (size_t idx = 0; idx < num_tasks; ++idx) {
size_t node_idx = idx / num_shards_per_node;
size_t proc_idx = idx % num_shards_per_node;
assert(node_idx < sysmems_list.size());
#if SPMD_SHARD_USE_IO_PROC
assert(proc_idx < sysmem_local_io_procs[sysmems_list[node_idx]].size());
output.task_processors[idx] = sysmem_local_io_procs[sysmems_list[node_idx]][proc_idx];
#else
assert(proc_idx < sysmem_local_procs[sysmems_list[node_idx]].size());
output.task_processors[idx] = sysmem_local_procs[sysmems_list[node_idx]][proc_idx];
#endif
task_indices[input.tasks[idx]] = node_idx;
}
for (size_t idx = 0; idx < input.constraints.size(); ++idx) {
const MappingConstraint& constraint = input.constraints[idx];
int owner_id = -1;
for (unsigned i = 0; i < constraint.constrained_tasks.size(); ++i) {
const RegionRequirement& req =
constraint.constrained_tasks[i]->regions[
constraint.requirement_indexes[i]];
if (req.is_no_access()) continue;
assert(owner_id == -1);
owner_id = static_cast<int>(i);
}
assert(owner_id != -1);
const Task* task = constraint.constrained_tasks[owner_id];
const RegionRequirement& req =
task->regions[constraint.requirement_indexes[owner_id]];
Memory target_memory = sysmems_list[task_indices[task]];
LayoutConstraintSet layout_constraints;
default_policy_select_constraints(ctx, layout_constraints, target_memory, req);
layout_constraints.add_constraint(
FieldConstraint(req.privilege_fields, false /*!contiguous*/));
PhysicalInstance inst;
bool created;
bool ok = runtime->find_or_create_physical_instance(ctx, target_memory,
layout_constraints, std::vector<LogicalRegion>(1, req.region),
inst, created, true /*acquire*/);
assert(ok);
output.constraint_mappings[idx].push_back(inst);
}
}
static void create_mappers(Machine machine, Runtime *runtime, const std::set<Processor> &local_procs)
{
std::vector<Processor>* procs_list = new std::vector<Processor>();
std::vector<Memory>* sysmems_list = new std::vector<Memory>();
std::map<Memory, std::vector<Processor> >* sysmem_local_procs =
new std::map<Memory, std::vector<Processor> >();
#if SPMD_SHARD_USE_IO_PROC
std::map<Memory, std::vector<Processor> >* sysmem_local_io_procs =
new std::map<Memory, std::vector<Processor> >();
#endif
std::map<Processor, Memory>* proc_sysmems = new std::map<Processor, Memory>();
std::map<Processor, Memory>* proc_regmems = new std::map<Processor, Memory>();
std::vector<Machine::ProcessorMemoryAffinity> proc_mem_affinities;
machine.get_proc_mem_affinity(proc_mem_affinities);
for (unsigned idx = 0; idx < proc_mem_affinities.size(); ++idx) {
Machine::ProcessorMemoryAffinity& affinity = proc_mem_affinities[idx];
if (affinity.p.kind() == Processor::LOC_PROC ||
affinity.p.kind() == Processor::IO_PROC) {
if (affinity.m.kind() == Memory::SYSTEM_MEM) {
(*proc_sysmems)[affinity.p] = affinity.m;
if (proc_regmems->find(affinity.p) == proc_regmems->end())
(*proc_regmems)[affinity.p] = affinity.m;
}
else if (affinity.m.kind() == Memory::REGDMA_MEM)
(*proc_regmems)[affinity.p] = affinity.m;
}
}
for (std::map<Processor, Memory>::iterator it = proc_sysmems->begin();
it != proc_sysmems->end(); ++it) {
if (it->first.kind() == Processor::LOC_PROC) {
procs_list->push_back(it->first);
(*sysmem_local_procs)[it->second].push_back(it->first);
}
#if SPMD_SHARD_USE_IO_PROC
else if (it->first.kind() == Processor::IO_PROC) {
(*sysmem_local_io_procs)[it->second].push_back(it->first);
}
#endif
}
for (std::map<Memory, std::vector<Processor> >::iterator it =
sysmem_local_procs->begin(); it != sysmem_local_procs->end(); ++it)
sysmems_list->push_back(it->first);
for (std::set<Processor>::const_iterator it = local_procs.begin();
it != local_procs.end(); it++)
{
PennantMapper* mapper = new PennantMapper(runtime->get_mapper_runtime(),
machine, *it, "pennant_mapper",
procs_list,
sysmems_list,
sysmem_local_procs,
#if SPMD_SHARD_USE_IO_PROC
sysmem_local_io_procs,
#endif
proc_sysmems,
proc_regmems);
runtime->replace_default_mapper(mapper, *it);
}
}
void register_mappers()
{
Runtime::add_registration_callback(create_mappers);
}
| 36.735918 | 113 | 0.58941 | mmccarty |
67d6ad2490edc8e8690bb1c5773f33069e3f920e | 1,233 | cpp | C++ | third_party/boost/libs/parameter/test/macros.cpp | Jackarain/tinyrpc | 07060e3466776aa992df8574ded6c1616a1a31af | [
"BSL-1.0"
] | 32 | 2019-02-27T06:57:07.000Z | 2021-08-29T10:56:19.000Z | third_party/boost/libs/parameter/test/macros.cpp | avplayer/cxxrpc | 7049b4079fac78b3828e68f787d04d699ce52f6d | [
"BSL-1.0"
] | 1 | 2019-04-04T18:00:00.000Z | 2019-04-04T18:00:00.000Z | third_party/boost/libs/parameter/test/macros.cpp | avplayer/cxxrpc | 7049b4079fac78b3828e68f787d04d699ce52f6d | [
"BSL-1.0"
] | 5 | 2019-08-20T13:45:04.000Z | 2022-03-01T18:23:49.000Z | // Copyright David Abrahams, Daniel Wallin 2003. Use, modification and
// distribution is subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/parameter.hpp>
#include <boost/parameter/macros.hpp>
#include <boost/bind.hpp>
#include <boost/static_assert.hpp>
#include <boost/ref.hpp>
#include <cassert>
#include <string.h>
#include "basics.hpp"
namespace test
{
BOOST_PARAMETER_FUN(int, f, 2, 4, f_parameters)
{
p[tester](
p[name]
, p[value || boost::bind(&value_default) ]
#if BOOST_WORKAROUND(__DECCXX_VER, BOOST_TESTED_AT(60590042))
, p[test::index | 999 ]
#else
, p[index | 999 ]
#endif
);
return 1;
}
} // namespace test
int main()
{
using test::f;
using test::name;
using test::value;
using test::index;
using test::tester;
f(
test::values(S("foo"), S("bar"), S("baz"))
, S("foo"), S("bar"), S("baz")
);
int x = 56;
f(
test::values("foo", 666.222, 56)
, index = boost::ref(x), name = "foo"
);
return boost::report_errors();
}
| 21.258621 | 72 | 0.583131 | Jackarain |
67d6bac0c85022d2e8fd437d316295bf8d10c947 | 1,222 | hpp | C++ | android-31/java/security/cert/PKIXRevocationChecker.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/java/security/cert/PKIXRevocationChecker.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/java/security/cert/PKIXRevocationChecker.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #pragma once
#include "./PKIXCertPathChecker.hpp"
class JObject;
namespace java::net
{
class URI;
}
namespace java::security::cert
{
class X509Certificate;
}
namespace java::security::cert
{
class PKIXRevocationChecker : public java::security::cert::PKIXCertPathChecker
{
public:
// Fields
// QJniObject forward
template<typename ...Ts> explicit PKIXRevocationChecker(const char *className, const char *sig, Ts...agv) : java::security::cert::PKIXCertPathChecker(className, sig, std::forward<Ts>(agv)...) {}
PKIXRevocationChecker(QJniObject obj);
// Constructors
// Methods
java::security::cert::PKIXRevocationChecker clone() const;
JObject getOcspExtensions() const;
java::net::URI getOcspResponder() const;
java::security::cert::X509Certificate getOcspResponderCert() const;
JObject getOcspResponses() const;
JObject getOptions() const;
JObject getSoftFailExceptions() const;
void setOcspExtensions(JObject arg0) const;
void setOcspResponder(java::net::URI arg0) const;
void setOcspResponderCert(java::security::cert::X509Certificate arg0) const;
void setOcspResponses(JObject arg0) const;
void setOptions(JObject arg0) const;
};
} // namespace java::security::cert
| 27.772727 | 196 | 0.748773 | YJBeetle |
67d8635bbbf5b70ada4b6515f338ef69d251bfab | 1,591 | cpp | C++ | v1/Lewcid/OSBinding_SDL.cpp | Jess-Stuart/FreedGames | a8f1dcb9daa8063740f9875a1615500ad8ca9498 | [
"BSL-1.0"
] | 2 | 2020-12-05T08:35:17.000Z | 2021-03-06T20:32:28.000Z | v1/Lewcid/OSBinding_SDL.cpp | Jess-Stuart/FreedGames | a8f1dcb9daa8063740f9875a1615500ad8ca9498 | [
"BSL-1.0"
] | 1 | 2021-04-05T21:58:09.000Z | 2021-04-06T00:18:26.000Z | v1/Lewcid/OSBinding_SDL.cpp | Jess-Stuart/FreedGames | a8f1dcb9daa8063740f9875a1615500ad8ca9498 | [
"BSL-1.0"
] | 3 | 2021-04-02T03:55:53.000Z | 2021-04-09T20:18:04.000Z |
#include <stdio.h>
#include <math.h>
#include <time.h>
#ifdef WIN32
#include <windows.h>
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <math.h>
#include <fstream.h>
void SetRandomSeed()
{
LARGE_INTEGER la;
QueryPerformanceCounter( &la );
srand( (unsigned int)la.QuadPart );
}
void ShowMessage(char* mess, char* title)
{
// SDL_WM_SetCaption(mess, 0);
// MessageBox(0, mess, title, MB_OK);
}
double LC_GetCurrentTime()
{
double val = clock();
return (val / 1000.0);
}
#define UseMessageBoxForIntro false
#else
#define UseMessageBoxForIntro false
// put the Mac Carbon headers here
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
void SetRandomSeed()
{
srand( clock() );
}
void ConvertCToPascalString(char* from, unsigned char* to)
{
int i=0;
for(i=0; from[i]; i++)
{
to[i+1] = from[i];
}
to[0] = i;
}
void ShowMessage(char* mess, char* title)
{
unsigned char buff1[200], buff2[200];
ConvertCToPascalString( ((char*)mess), buff1);
ConvertCToPascalString( ((char*)title), buff2);
short res;
StandardAlert(kAlertNoteAlert, buff2, buff1, 0, &res);
}
/*
void ShowMessage(char* mess, char* title)
{
printf("\n%s\n", title);
for (int i=0; title[i]; i++)
printf("-");
printf("\n%s\n\n", mess);
}
*/
double LC_GetCurrentTime()
{
double val = clock();
return (val / 100.0);
}
#endif
| 16.747368 | 59 | 0.610937 | Jess-Stuart |
67ddc59593676eb432301ab3fd9bbe98badc48e0 | 612 | hpp | C++ | include/vsim/env/rigid_body.hpp | malasiot/vsim | 2a69e27364bab29194328af3d050e34f907e226b | [
"MIT"
] | null | null | null | include/vsim/env/rigid_body.hpp | malasiot/vsim | 2a69e27364bab29194328af3d050e34f907e226b | [
"MIT"
] | null | null | null | include/vsim/env/rigid_body.hpp | malasiot/vsim | 2a69e27364bab29194328af3d050e34f907e226b | [
"MIT"
] | null | null | null | #ifndef __VSIM_RIGID_BODY_HPP__
#define __VSIM_RIGID_BODY_HPP__
#include <string>
#include <vector>
#include <memory>
#include <Eigen/Core>
#include <vsim/env/scene_fwd.hpp>
#include <vsim/env/pose.hpp>
#include <vsim/env/base_element.hpp>
namespace vsim {
class RigidBody ;
typedef std::shared_ptr<RigidBody> BodyPtr ;
// class defining a rigid body
class RigidBody: public BaseElement {
public:
RigidBody() = default ;
public:
std::vector<CollisionShapePtr> shapes_ ;
Pose pose_ ;
float mass_ ;
Eigen::Vector3f velocity_, angular_velocity_ ;
NodePtr visual_ ;
};
}
#endif
| 15.3 | 50 | 0.72549 | malasiot |
67df8c576a6fe8065b2fd920603ad28a3fda09ae | 746 | cc | C++ | utils/sv_test.cc | kho/cdec | d88186af251ecae60974b20395ce75807bfdda35 | [
"BSD-3-Clause-LBNL",
"Apache-2.0"
] | null | null | null | utils/sv_test.cc | kho/cdec | d88186af251ecae60974b20395ce75807bfdda35 | [
"BSD-3-Clause-LBNL",
"Apache-2.0"
] | null | null | null | utils/sv_test.cc | kho/cdec | d88186af251ecae60974b20395ce75807bfdda35 | [
"BSD-3-Clause-LBNL",
"Apache-2.0"
] | null | null | null | #define BOOST_TEST_MODULE WeightsTest
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include "sparse_vector.h"
using namespace std;
BOOST_AUTO_TEST_CASE(Dot) {
SparseVector<double> x;
SparseVector<double> y;
x.set_value(1,0.8);
y.set_value(1,5);
x.set_value(2,-2);
y.set_value(2,1);
x.set_value(3,80);
BOOST_CHECK_CLOSE(x.dot(y), 2.0, 1e-9);
}
BOOST_AUTO_TEST_CASE(Equality) {
SparseVector<double> x;
SparseVector<double> y;
x.set_value(1,-1);
y.set_value(1,-1);
BOOST_CHECK(x == y);
}
BOOST_AUTO_TEST_CASE(Division) {
SparseVector<double> x;
SparseVector<double> y;
x.set_value(1,1);
y.set_value(1,-1);
BOOST_CHECK(!(x == y));
x /= -1;
BOOST_CHECK(x == y);
}
| 20.722222 | 51 | 0.690349 | kho |
67e09e5b3f18ed4386cdb803bd7258239866a7e4 | 1,938 | cpp | C++ | tools/ltsview/savepicturedialog.cpp | gijskant/mcrl2-pmc | 9ea75755081b20623bc8fc7db27124d084e781fe | [
"BSL-1.0"
] | null | null | null | tools/ltsview/savepicturedialog.cpp | gijskant/mcrl2-pmc | 9ea75755081b20623bc8fc7db27124d084e781fe | [
"BSL-1.0"
] | null | null | null | tools/ltsview/savepicturedialog.cpp | gijskant/mcrl2-pmc | 9ea75755081b20623bc8fc7db27124d084e781fe | [
"BSL-1.0"
] | null | null | null | // Author(s): Bas Ploeger, Carst Tankink, Ruud Koolen
// Copyright: see the accompanying file COPYING or copy at
// https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "savepicturedialog.h"
#include <QImage>
#include <QImageWriter>
SavePictureDialog::SavePictureDialog(QWidget *parent, LtsCanvas *canvas, QString filename):
QDialog(parent),
m_canvas(canvas),
m_filename(filename),
m_inChange(false)
{
m_ui.setupUi(this);
m_width = canvas->viewWidth();
m_height = canvas->viewHeight();
m_ui.width->setValue(m_width);
m_ui.height->setValue(m_height);
connect(m_ui.width, SIGNAL(valueChanged(int)), this, SLOT(widthChanged(int)));
connect(m_ui.height, SIGNAL(valueChanged(int)), this, SLOT(heightChanged(int)));
connect(m_ui.buttonBox, SIGNAL(accepted()), this, SLOT(save()));
connect(m_ui.buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
}
void SavePictureDialog::widthChanged(int value)
{
if (m_inChange)
{
return;
}
if (m_ui.maintainAspectRatio->isChecked())
{
m_inChange = true;
m_ui.height->setValue((int)(value * m_height / m_width));
m_inChange = false;
}
}
void SavePictureDialog::heightChanged(int value)
{
if (m_inChange)
{
return;
}
if (m_ui.maintainAspectRatio->isChecked())
{
m_inChange = true;
m_ui.height->setValue((int)(value * m_width / m_height));
m_inChange = false;
}
}
void SavePictureDialog::save()
{
int width = m_ui.width->value();
int height = m_ui.height->value();
QImage image = m_canvas->renderImage(width, height);
emit statusMessage("Saving image...");
QImageWriter writer(m_filename);
if (writer.write(image))
{
emit statusMessage("Done");
}
else
{
emit statusMessage("Saving image failed.");
}
accept();
}
| 23.634146 | 91 | 0.69453 | gijskant |
67e25b4e5ea794a026bfdd70c04c254d66f5ac0a | 337 | cpp | C++ | hackerrank/Algorithms/Warmup/HalloweenParty/HalloweenParty.cpp | everyevery/programming_study | ff35e97e13953e4d7a26591f7cdb301d3e8e36c6 | [
"MIT"
] | null | null | null | hackerrank/Algorithms/Warmup/HalloweenParty/HalloweenParty.cpp | everyevery/programming_study | ff35e97e13953e4d7a26591f7cdb301d3e8e36c6 | [
"MIT"
] | null | null | null | hackerrank/Algorithms/Warmup/HalloweenParty/HalloweenParty.cpp | everyevery/programming_study | ff35e97e13953e4d7a26591f7cdb301d3e8e36c6 | [
"MIT"
] | 1 | 2017-04-01T21:34:23.000Z | 2017-04-01T21:34:23.000Z | // HACKERRANK - Halloween Party
// https://www.hackerrank.com/challenges/halloween-party
#include <iostream>
using namespace std;
int main (int argc, char *argv[]) {
int N;
cin >> N;
while (N--) {
long long input;
long long x, y;
cin >> input;
x = input / 2;
y = input - x;
cout << x * y << endl;
}
return 0;
} | 12.481481 | 56 | 0.590504 | everyevery |
67e2738ca714e1aef79e4f33a4df272ff188782e | 3,473 | hpp | C++ | src/libs/optframe/src/OptFrame/MultiMoveCost.hpp | fellipessanha/LMRRC-Team-AIDA | 8076599427df0e35890caa7301972a53ae327edb | [
"MIT"
] | 1 | 2021-08-19T13:31:29.000Z | 2021-08-19T13:31:29.000Z | src/libs/optframe/src/OptFrame/MultiMoveCost.hpp | fellipessanha/LMRRC-Team-AIDA | 8076599427df0e35890caa7301972a53ae327edb | [
"MIT"
] | null | null | null | src/libs/optframe/src/OptFrame/MultiMoveCost.hpp | fellipessanha/LMRRC-Team-AIDA | 8076599427df0e35890caa7301972a53ae327edb | [
"MIT"
] | null | null | null | // OptFrame - Optimization Framework
// Copyright (C) 2009-2015
// http://optframe.sourceforge.net/
//
// This file is part of the OptFrame optimization framework. This framework
// is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License v3 as published by the
// Free Software Foundation.
// This framework 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 v3 for more details.
// You should have received a copy of the GNU Lesser General Public License v3
// along with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#ifndef OPTFRAME_MULTI_MOVE_COST_HPP_
#define OPTFRAME_MULTI_MOVE_COST_HPP_
#include <cstdlib>
#include <iostream>
#include <cmath>
#include "Component.hpp"
#include "BaseConcepts.hpp"
#include "Evaluation.hpp"
#include "MoveCost.hpp"
using namespace std;
namespace optframe
{
//// more than 'objval' we need to ensure arithmetics here... TODO: see that (same as Evaluation)
template<optframe::objval ObjType = evtype, XEvaluation XEv = Evaluation<ObjType>>
//template<class ObjType = evtype, XEvaluation XEv = Evaluation<ObjType>>
class MultiMoveCost: public Component
{
protected:
vector<MoveCost<ObjType, XEv>*> vmc;
public:
explicit MultiMoveCost(vector<MoveCost<>*> _vmc) :
vmc(_vmc)
{
}
MultiMoveCost(const MultiMoveCost<>& mc) :
vmc(mc.vmc)
{
}
virtual ~MultiMoveCost()
{
}
int size() const
{
return vmc.size();
}
bool hasCost(int k) const
{
return vmc[k];
}
bool isEstimated(int k) const
{
return vmc[k]->estimated;
}
const vector<pair<ObjType, ObjType> >& getAlternativeCosts(int k) const
{
return vmc[k]->alternatives;
}
ObjType getObjFunctionCost(int k) const
{
return vmc[k]->objFunction;
}
ObjType getInfMeasureCost(int k) const
{
return vmc[k]->infMeasure;
}
void addAlternativeCost(const pair<ObjType, ObjType>& alternativeCost, int k)
{
vmc[k]->alternatives.push_back(alternativeCost);
}
void setAlternativeCosts(const vector<pair<ObjType, ObjType> >& alternativeCosts, int k)
{
vmc[k]->alternatives = alternativeCosts;
}
void setObjFunctionCost(ObjType obj, int k)
{
vmc[k]->objFunction = obj;
}
void setInfMeasureCost(ObjType inf, int k)
{
vmc[k]->infMeasure = inf;
}
ObjType cost(int k) const
{
return vmc[k]->cost();
}
static string idComponent()
{
return "OptFrame:MultiMoveCost";
}
virtual string id() const
{
return idComponent();
}
virtual void print() const
{
cout << fixed; // disable scientific notation
cout << "MultiMoveCost for " << size() << " objectives:" << endl;
for(unsigned i=0; i<vmc.size(); i++)
if(vmc[i])
vmc[i]->print();
else
cout << "NO COST" << endl;
}
virtual MultiMoveCost<>& operator=(const MultiMoveCost<>& mmc)
{
if (&mmc == this) // auto ref check
return *this;
vmc = mmc.vmc; // TODO fix: this should handle some local instances, for the future...
return *this;
}
virtual MultiMoveCost<>& clone() const
{
return *new MultiMoveCost<>(*this);
}
};
#ifndef NDEBUG
struct optframe_debug_test_multimove_cost
{
MultiMoveCost<> testMoveCost;
};
#endif
} // namespace optframe
#endif /*OPTFRAME_MULTI_MOVE_COST_HPP_*/
| 21.306748 | 97 | 0.708033 | fellipessanha |
67e31c601d860a04539d998362e8d1659aee1477 | 3,871 | hpp | C++ | include/wprofile.hpp | aegistudio/wdedup | 686af391347418991260d421f33316171047fe95 | [
"MIT"
] | null | null | null | include/wprofile.hpp | aegistudio/wdedup | 686af391347418991260d421f33316171047fe95 | [
"MIT"
] | null | null | null | include/wprofile.hpp | aegistudio/wdedup | 686af391347418991260d421f33316171047fe95 | [
"MIT"
] | null | null | null | /* Copyright © 2019 Haoran Luo
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the “Software”), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. */
/**
* @file wprofile.hpp
* @author Haoran Luo
* @brief wdedup Profile header.
*
* This file describes the profile structures. Profiles are stored in a
* (logically) sorted-by-word, FIFO and immutable file.
*
* According to previous studying of sorted table implementation, multiple
* variance of physical implementation is observed, and which one excels
* has not been verified. So the profiler file is designed as a virtual
* interface, and provided as wdedup::Config item.
*/
#pragma once
#include "wtypes.hpp"
#include <string>
namespace wdedup {
/**
* @brief Defines the profile item in profile input and output.
*
* Various implementation must customize their interfaces to return such
* kind of items.
*/
struct ProfileItem {
/// Current recorded word.
std::string word;
/// Whether this word has been repeated.
bool repeated;
/// The first occurence of the word.
/// If repeated is true, this field should be ignored by the
/// scanning algorithms.
fileoff_t occur;
/// Construct a repeated item.
ProfileItem(std::string word) noexcept:
word(std::move(word)), repeated(true), occur(0) {}
/// Construct a single occurence item.
ProfileItem(std::string word, fileoff_t occur) noexcept:
word(std::move(word)), repeated(false), occur(occur) {}
/// Move constructor of a profile item.
ProfileItem(ProfileItem&& item) noexcept:
word(std::move(item.word)),
repeated(item.repeated), occur(item.occur) {}
};
/// @brief Defines the virtual read interface of profile.
struct ProfileInput {
/// Virtual destructor for pure virtual classes.
virtual ~ProfileInput() noexcept {};
/// Test whether there's content in the file.
virtual bool empty() const noexcept = 0;
/// Peeking the head profileItem from the input table.
/// If there's no more content in the table, the content
/// returned by the table will be undefined.
virtual const ProfileItem& peek() const noexcept = 0;
/// Pop the head profileItem from the input table.
/// If there's no more content in the table, popping
/// from the table will cause exception to be thrown.
virtual ProfileItem pop() throw (wdedup::Error) = 0;
};
/// @brief Defines the virtual write interface of profile.
struct ProfileOutput {
/// Virtual destructor for pure virtual classes.
virtual ~ProfileOutput() noexcept {};
/// Push content to the profile output.
/// Exception will be thrown if there's I/O error on the
/// underlying (append-only) files.
virtual void push(ProfileItem) throw (wdedup::Error) = 0;
/// Indicates that this is the end of profile output.
/// The size of the generated file will be collected and
/// return to the caller.
virtual size_t close() throw (wdedup::Error) = 0;
};
} // namespace wdedup
| 35.513761 | 75 | 0.727977 | aegistudio |
67e393d34739298ca0dddd343152d7fbf7d26048 | 1,691 | hpp | C++ | server/api/include/irods/rs_set_delay_server_migration_info.hpp | stefan-wolfsheimer/irods | f6eb6c72786288878706e2562a370b91b7d0802e | [
"BSD-3-Clause"
] | null | null | null | server/api/include/irods/rs_set_delay_server_migration_info.hpp | stefan-wolfsheimer/irods | f6eb6c72786288878706e2562a370b91b7d0802e | [
"BSD-3-Clause"
] | null | null | null | server/api/include/irods/rs_set_delay_server_migration_info.hpp | stefan-wolfsheimer/irods | f6eb6c72786288878706e2562a370b91b7d0802e | [
"BSD-3-Clause"
] | null | null | null | #ifndef IRODS_RS_SET_DELAY_SERVER_MIGRATION_INFO_HPP
#define IRODS_RS_SET_DELAY_SERVER_MIGRATION_INFO_HPP
/// \file
#include "irods/plugins/api/delay_server_migration_types.h"
struct RsComm;
#ifdef __cplusplus
extern "C" {
#endif
/// Atomically sets the leader and successor hostnames for delay server migration in the
/// R_GRID_CONFIGURATION table.
///
/// The invoking user of this API must be a \p rodsadmin.
///
/// This API will verify the following before updating the catalog:
/// - Verify that input arguments are not null
/// - Verify that hostname requirements imposed by the OS have not been violated
/// - Verify that hostnames are not identical
/// - Verify that hostnames refer to iRODS servers in the local zone
///
/// \param[in] _comm A pointer to a RsComm.
/// \param[in] _input \parblock An object holding the new hostname values for the leader and successor.
///
/// Although the API allows updating the leader and successor simultaneously, users aren't required to
/// do so. Users can choose to skip updating either field. This is achieved by setting the respective
/// member variable to the value of \p KW_DELAY_SERVER_MIGRATION_IGNORE. For example:
/// \code{.c}
/// DelayServerMigrationInput input;
/// memset(&input, 0, sizeof(DelayServerMigrationInput));
/// strcpy(input.leader, KW_DELAY_SERVER_MIGRATION_IGNORE);
/// \endcode
/// \endparblock
///
/// \return An integer.
/// \retval 0 On success.
/// \retval Non-zero On failure.
///
/// \since 4.3.0
int rs_set_delay_server_migration_info(RsComm* _comm, const DelayServerMigrationInput* _input);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // IRODS_RS_SET_DELAY_SERVER_MIGRATION_INFO_HPP
| 33.156863 | 103 | 0.754583 | stefan-wolfsheimer |
67e538aa22d0282fc0866f9438d1c45e28b6a41e | 2,050 | cpp | C++ | tests/transport/test_send_multi.cpp | boeschf/GHEX-OLD | a1c8e12e50b4781cc6d0b0314f17bd3f91ac3769 | [
"BSD-3-Clause"
] | null | null | null | tests/transport/test_send_multi.cpp | boeschf/GHEX-OLD | a1c8e12e50b4781cc6d0b0314f17bd3f91ac3769 | [
"BSD-3-Clause"
] | null | null | null | tests/transport/test_send_multi.cpp | boeschf/GHEX-OLD | a1c8e12e50b4781cc6d0b0314f17bd3f91ac3769 | [
"BSD-3-Clause"
] | null | null | null | #include <ghex/transport_layer/callback_communicator.hpp>
#include <ghex/transport_layer/mpi/communicator.hpp>
#include <iostream>
#include <iomanip>
#include <gtest/gtest.h>
template<typename Comm, typename Alloc>
using callback_comm_t = gridtools::ghex::tl::callback_communicator<Comm,Alloc>;
//using callback_comm_t = gridtools::ghex::tl::callback_communicator_ts<Comm,Alloc>;
const int SIZE = 4000000;
int mpi_rank;
//#define GHEX_TEST_COUNT_ITERATIONS
TEST(transport, send_multi) {
{
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
EXPECT_EQ(size, 4);
}
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
MPI_Barrier(MPI_COMM_WORLD);
using comm_type = gridtools::ghex::tl::communicator<gridtools::ghex::tl::mpi_tag>;
comm_type comm;
using allocator_type = std::allocator<unsigned char>;
using smsg_type = gridtools::ghex::tl::shared_message_buffer<allocator_type>;
callback_comm_t<comm_type,allocator_type> cb_comm(comm);
if (mpi_rank == 0) {
smsg_type smsg{SIZE};
int * data = smsg.data<int>();
for (int i = 0; i < SIZE/(int)sizeof(int); ++i) {
data[i] = i;
}
std::array<int, 3> dsts = {1,2,3};
cb_comm.send_multi(smsg, dsts, 42);
#ifdef GHEX_TEST_COUNT_ITERATIONS
int c = 0;
#endif
while (cb_comm.progress()) {
#ifdef GHEX_TEST_COUNT_ITERATIONS
c++;
#endif
}
EXPECT_EQ(smsg.use_count(), 1);
#ifdef GHEX_TEST_COUNT_ITERATIONS
std::cout << "\n***********\n";
std::cout << "*" << std::setw(8) << c << " *\n";
std::cout << "***********\n";
#endif
} else {
gridtools::ghex::tl::message_buffer<> rmsg{SIZE};
auto fut = comm.recv(rmsg, 0, 42);
fut.wait();
bool ok = true;
for (int i = 0; i < (int)rmsg.size()/(int)sizeof(int); ++i) {
int * data = rmsg.data<int>();
if ( data[i] != i )
ok = false;
}
EXPECT_TRUE(ok);
}
EXPECT_FALSE(cb_comm.progress());
}
| 23.295455 | 86 | 0.603415 | boeschf |
67e9695533fd6b9311054129b64516ea00c82d5f | 2,172 | hpp | C++ | raintk/RainTkRow.hpp | preet/raintk | 9cbd596d9cec9aca7d3bbf3994a2931bac87e98d | [
"Apache-2.0"
] | 4 | 2016-05-03T20:47:51.000Z | 2021-04-15T09:33:34.000Z | raintk/RainTkRow.hpp | preet/raintk | 9cbd596d9cec9aca7d3bbf3994a2931bac87e98d | [
"Apache-2.0"
] | null | null | null | raintk/RainTkRow.hpp | preet/raintk | 9cbd596d9cec9aca7d3bbf3994a2931bac87e98d | [
"Apache-2.0"
] | 1 | 2017-07-26T07:31:35.000Z | 2017-07-26T07:31:35.000Z | /*
Copyright (C) 2015 Preet Desai (preet.desai@gmail.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef RAINTK_ROW_HPP
#define RAINTK_ROW_HPP
#include <map>
#include <list>
#include <raintk/RainTkWidget.hpp>
namespace raintk
{
class Row : public Widget
{
public:
using base_type = raintk::Widget;
enum class LayoutDirection
{
LeftToRight,
RightToLeft
};
Row(ks::Object::Key const &key,
Scene* scene,
shared_ptr<Widget> parent);
void Init(ks::Object::Key const &,
shared_ptr<Row> const &);
~Row();
void AddChild(shared_ptr<Widget> const &child) override;
void RemoveChild(shared_ptr<Widget> const &child) override;
// Properties
Property<float> spacing{
0.0f
};
Property<float> children_width{
0.0f
};
Property<float> children_height{
0.0f
};
Property<LayoutDirection> layout_direction{
LayoutDirection::LeftToRight
};
protected:
void onSpacingChanged();
void onLayoutDirectionChanged();
void onChildDimsChanged();
Id m_cid_spacing;
Id m_cid_layout_direction;
private:
void update() override;
struct Item
{
Widget* widget;
Id cid_width;
Id cid_height;
};
// TODO replace list if performance is an issue
std::list<Item> m_list_items;
std::map<Id,std::list<Item>::iterator> m_lkup_id_item_it;
};
}
#endif // RAINTK_ROW_HPP
| 23.868132 | 75 | 0.609576 | preet |
67ed639ec8b8b650b8ab257ea157ae5fcf47165e | 3,662 | cpp | C++ | dev/Basic/long/database/entity/PopulationPerPlanningArea.cpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 50 | 2018-12-21T08:21:38.000Z | 2022-01-24T09:47:59.000Z | dev/Basic/long/database/entity/PopulationPerPlanningArea.cpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 2 | 2018-12-19T13:42:47.000Z | 2019-05-13T04:11:45.000Z | dev/Basic/long/database/entity/PopulationPerPlanningArea.cpp | gusugusu1018/simmobility-prod | d30a5ba353673f8fd35f4868c26994a0206a40b6 | [
"MIT"
] | 27 | 2018-11-28T07:30:34.000Z | 2022-02-05T02:22:26.000Z | /*
* PopulationPerPlanningArea.cpp
*
* Created on: 13 Aug, 2015
* Author: Chetan Rogbeer <chetan.rogbeer@smart.mit.edu>
*/
#include "database/entity/PopulationPerPlanningArea.hpp"
#include <boost/serialization/vector.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
using namespace sim_mob::long_term;
PopulationPerPlanningArea::PopulationPerPlanningArea(int planningAreaId, int population, int ethnicityId, int ageCategoryId, double avgIncome, int avgHhSize, int unitType, int floorArea):
planningAreaId(planningAreaId), population(population), ethnicityId(ethnicityId), ageCategoryId(ageCategoryId), avgIncome(avgIncome),
avgHhSize(avgHhSize), unitType(unitType), floorArea(floorArea){}
PopulationPerPlanningArea::~PopulationPerPlanningArea() {}
PopulationPerPlanningArea::PopulationPerPlanningArea( const PopulationPerPlanningArea &source)
{
planningAreaId = source.planningAreaId;
population = source.population;
ethnicityId = source.ethnicityId;
ageCategoryId = source.ageCategoryId;
avgIncome = source.avgIncome;
avgHhSize = source.avgHhSize;
unitType = source.unitType;
floorArea = source.floorArea;
}
PopulationPerPlanningArea& PopulationPerPlanningArea::operator=( const PopulationPerPlanningArea& source)
{
planningAreaId = source.planningAreaId;
population = source.population;
ethnicityId = source.ethnicityId;
ageCategoryId = source.ageCategoryId;
avgIncome = source.avgIncome;
avgHhSize = source.avgHhSize;
unitType = source.unitType;
floorArea = source.floorArea;
return *this;
}
template<class Archive>
void PopulationPerPlanningArea::serialize(Archive & ar,const unsigned int version)
{
ar & planningAreaId;
ar & population;
ar & ethnicityId ;
ar & ethnicityId;
ar & ageCategoryId;
ar & avgIncome;
ar & avgIncome;
ar & avgHhSize;
ar & unitType;
ar & floorArea;
}
void PopulationPerPlanningArea::saveData(std::vector<PopulationPerPlanningArea*> &s)
{
// make an archive
std::ofstream ofs(filename);
boost::archive::binary_oarchive oa(ofs);
oa & s;
}
std::vector<PopulationPerPlanningArea*> PopulationPerPlanningArea::loadSerializedData()
{
std::vector<PopulationPerPlanningArea*> populationPerPA;
// Restore from saved data and print to verify contents
std::vector<PopulationPerPlanningArea*> restored_info;
{
// Create and input archive
std::ifstream ifs( "populationPerPlanningArea" );
boost::archive::binary_iarchive ar( ifs );
// Load the data
ar & restored_info;
}
for (auto *itr :restored_info)
{
PopulationPerPlanningArea *popPerPA = itr;
populationPerPA.push_back(popPerPA);
}
return populationPerPA;
}
int PopulationPerPlanningArea::getPlanningAreaId() const
{
return planningAreaId;
}
int PopulationPerPlanningArea::getPopulation() const
{
return population;
}
double PopulationPerPlanningArea::getFloorArea() const
{
return floorArea;
}
int PopulationPerPlanningArea::getEthnicityId() const
{
return ethnicityId;
}
int PopulationPerPlanningArea::getAgeCategoryId() const
{
return ageCategoryId;
}
double PopulationPerPlanningArea::getAvgIncome() const
{
return avgIncome;
}
int PopulationPerPlanningArea::getAvgHhSize() const
{
return avgHhSize;
}
int PopulationPerPlanningArea::getUnitType() const
{
return unitType;
}
| 25.255172 | 187 | 0.704533 | gusugusu1018 |
67edfb7331705c47a3716d32060942916c63a84b | 1,044 | cc | C++ | 3rdParty/V8/v5.7.492.77/test/unittests/unicode-unittest.cc | sita1999/arangodb | 6a4f462fa209010cd064f99e63d85ce1d432c500 | [
"Apache-2.0"
] | 16 | 2017-08-24T14:53:25.000Z | 2021-08-19T04:49:23.000Z | test/unittests/unicode-unittest.cc | Acidburn0zzz/v8-1 | 0dd6885de60fdba36532e068a31693c870d8b50b | [
"BSD-3-Clause"
] | null | null | null | test/unittests/unicode-unittest.cc | Acidburn0zzz/v8-1 | 0dd6885de60fdba36532e068a31693c870d8b50b | [
"BSD-3-Clause"
] | 10 | 2017-09-21T07:40:42.000Z | 2020-03-31T05:53:42.000Z | // Copyright 2016 the V8 project 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 <memory>
#include <string>
#include "src/unicode-decoder.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace v8 {
namespace internal {
namespace {
using Utf8Decoder = unibrow::Utf8Decoder<512>;
void Decode(Utf8Decoder* decoder, const std::string& str) {
// Put the string in its own buffer on the heap to make sure that
// AddressSanitizer's heap-buffer-overflow logic can see what's going on.
std::unique_ptr<char[]> buffer(new char[str.length()]);
memcpy(buffer.get(), str.data(), str.length());
decoder->Reset(buffer.get(), str.length());
}
} // namespace
TEST(UnicodeTest, ReadOffEndOfUtf8String) {
Utf8Decoder decoder;
// Not enough continuation bytes before string ends.
Decode(&decoder, "\xE0");
Decode(&decoder, "\xED");
Decode(&decoder, "\xF0");
Decode(&decoder, "\xF4");
}
} // namespace internal
} // namespace v8
| 26.1 | 75 | 0.706897 | sita1999 |
67f1dfdf029eca8007ff8503aee3d11bee123f0e | 2,644 | cpp | C++ | clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp | tkf/opencilk-project | 48265098754b785d1b06cb08d8e22477a003efcd | [
"MIT"
] | 1 | 2020-09-25T23:33:05.000Z | 2020-09-25T23:33:05.000Z | clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp | tkf/opencilk-project | 48265098754b785d1b06cb08d8e22477a003efcd | [
"MIT"
] | 2 | 2021-10-06T22:33:18.000Z | 2022-02-19T07:00:39.000Z | clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp | tkf/opencilk-project | 48265098754b785d1b06cb08d8e22477a003efcd | [
"MIT"
] | 1 | 2020-07-30T11:23:41.000Z | 2020-07-30T11:23:41.000Z | #include "ClangTidy.h"
#include "ClangTidyTest.h"
#include "gtest/gtest.h"
namespace clang {
namespace tidy {
namespace test {
class TestCheck : public ClangTidyCheck {
public:
TestCheck(StringRef Name, ClangTidyContext *Context)
: ClangTidyCheck(Name, Context) {}
void registerMatchers(ast_matchers::MatchFinder *Finder) override {
Finder->addMatcher(ast_matchers::varDecl().bind("var"), this);
}
void check(const ast_matchers::MatchFinder::MatchResult &Result) override {
const auto *Var = Result.Nodes.getNodeAs<VarDecl>("var");
// Add diagnostics in the wrong order.
diag(Var->getLocation(), "variable");
diag(Var->getTypeSpecStartLoc(), "type specifier");
}
};
TEST(ClangTidyDiagnosticConsumer, SortsErrors) {
std::vector<ClangTidyError> Errors;
runCheckOnCode<TestCheck>("int a;", &Errors);
EXPECT_EQ(2ul, Errors.size());
EXPECT_EQ("type specifier", Errors[0].Message.Message);
EXPECT_EQ("variable", Errors[1].Message.Message);
}
TEST(GlobList, Empty) {
GlobList Filter("");
EXPECT_TRUE(Filter.contains(""));
EXPECT_FALSE(Filter.contains("aaa"));
}
TEST(GlobList, Nothing) {
GlobList Filter("-*");
EXPECT_FALSE(Filter.contains(""));
EXPECT_FALSE(Filter.contains("a"));
EXPECT_FALSE(Filter.contains("-*"));
EXPECT_FALSE(Filter.contains("-"));
EXPECT_FALSE(Filter.contains("*"));
}
TEST(GlobList, Everything) {
GlobList Filter("*");
EXPECT_TRUE(Filter.contains(""));
EXPECT_TRUE(Filter.contains("aaaa"));
EXPECT_TRUE(Filter.contains("-*"));
EXPECT_TRUE(Filter.contains("-"));
EXPECT_TRUE(Filter.contains("*"));
}
TEST(GlobList, Simple) {
GlobList Filter("aaa");
EXPECT_TRUE(Filter.contains("aaa"));
EXPECT_FALSE(Filter.contains(""));
EXPECT_FALSE(Filter.contains("aa"));
EXPECT_FALSE(Filter.contains("aaaa"));
EXPECT_FALSE(Filter.contains("bbb"));
}
TEST(GlobList, WhitespacesAtBegin) {
GlobList Filter("-*, a.b.*");
EXPECT_TRUE(Filter.contains("a.b.c"));
EXPECT_FALSE(Filter.contains("b.c"));
}
TEST(GlobList, Complex) {
GlobList Filter("*,-a.*, -b.*, \r \n a.1.* ,-a.1.A.*,-..,-...,-..+,-*$, -*qwe* ");
EXPECT_TRUE(Filter.contains("aaa"));
EXPECT_TRUE(Filter.contains("qqq"));
EXPECT_FALSE(Filter.contains("a."));
EXPECT_FALSE(Filter.contains("a.b"));
EXPECT_FALSE(Filter.contains("b."));
EXPECT_FALSE(Filter.contains("b.b"));
EXPECT_TRUE(Filter.contains("a.1.b"));
EXPECT_FALSE(Filter.contains("a.1.A.a"));
EXPECT_FALSE(Filter.contains("qwe"));
EXPECT_FALSE(Filter.contains("asdfqweasdf"));
EXPECT_TRUE(Filter.contains("asdfqwEasdf"));
}
} // namespace test
} // namespace tidy
} // namespace clang
| 27.831579 | 86 | 0.687216 | tkf |
67f810d0c8717bb0d3ab7d45802bde1ee0e9c04b | 3,460 | cc | C++ | src/cameras/camera.cc | BlurryLight/DiRender | 1ea55ff8a10bb76993ce9990b200ee8ed173eb3e | [
"MIT"
] | 20 | 2020-06-28T03:55:40.000Z | 2022-03-08T06:00:31.000Z | src/cameras/camera.cc | BlurryLight/DiRender | 1ea55ff8a10bb76993ce9990b200ee8ed173eb3e | [
"MIT"
] | null | null | null | src/cameras/camera.cc | BlurryLight/DiRender | 1ea55ff8a10bb76993ce9990b200ee8ed173eb3e | [
"MIT"
] | 1 | 2020-06-29T08:47:21.000Z | 2020-06-29T08:47:21.000Z | //
// Created by panda on 2021/2/26.
//
#include <cameras/camera.h>
#include <cores/scene.h>
using namespace DR;
void Film::write_ppm(const std::string &filename) {
auto fp = std::unique_ptr<FILE, decltype(&fclose)>(
fopen(filename.c_str(), "wb"), &fclose);
(void)fprintf(fp.get(), "P6\n%d %d\n255\n", height, width);
for (uint i = 0; i < width * height; ++i) {
static unsigned char color[3];
color[0] =
(unsigned char)(255 *
std::pow(clamp(0.0f, 1.0f, framebuffer_[i].x), 0.6f));
color[1] =
(unsigned char)(255 *
std::pow(clamp(0.0f, 1.0f, framebuffer_[i].y), 0.6f));
color[2] =
(unsigned char)(255 *
std::pow(clamp(0.0f, 1.0f, framebuffer_[i].z), 0.6f));
fwrite(color, 1, 3, fp.get());
}
}
Transform Camera::look_at(Point3f origin, Vector3f WorldUp, Vector3f target) {
auto cam_origin = static_cast<Vector3f>(origin);
auto cam_target = (static_cast<Vector3f>(origin) - target).normalize();
auto cam_right = cross(WorldUp.normalize(), cam_target).normalize();
auto cam_up = cross(cam_target, cam_right).normalize();
Matrix4 part2 = Matrix4(1.0f);
part2.m[0][3] = -cam_origin[0];
part2.m[1][3] = -cam_origin[1];
part2.m[2][3] = -cam_origin[2];
Matrix4 part1 = Matrix4(1.0f);
part1.m[0][0] = cam_right[0];
part1.m[0][1] = cam_right[1];
part1.m[0][2] = cam_right[2];
part1.m[1][0] = cam_up[0];
part1.m[1][1] = cam_up[1];
part1.m[1][2] = cam_up[2];
part1.m[2][0] = cam_target[0];
part1.m[2][1] = cam_target[1];
part1.m[2][2] = cam_target[2];
return Transform(part1 * part2);
}
Camera::Camera(Point3f origin, Vector3f WorldUp, Vector3f target, float fov,
uint height, uint width, observer_ptr<Scene> scene, bool gamma)
: position_(origin), fov_(fov), aspect_ratio_(float(width) / height),
scene_(scene) {
auto view_trans = Camera::look_at(origin, WorldUp, target);
auto [trans, trans_inv] = scene->trans_table.get_tf_and_inv(view_trans);
view_trans_ = trans;
view_trans_inverse_ = trans_inv;
film_ptr_ = std::make_unique<Film>(width, height, gamma);
}
void Film::write(const std::string &filename, PicType type, uint spp) const {
std::unique_ptr<uint8_t[]> data{
new uint8_t[height * width * 3]}; // don't support alpha & HDR
float inv_spp = 1.0f / float(spp);
for (uint i = 0; i < height * width; i++) {
for (uint j = 0; j < 3; j++) {
uint8_t tmp = 0;
static constexpr float gamma_index = 1 / 2.2f;
// Tone mapping
auto AcesFilmicToneMapping = [](float color) {
float a = 2.51f;
float b = 0.03f;
float c = 2.43f;
float d = 0.59f;
float e = 0.14f;
float new_cl =
clamp(0.0f, 1.0f,
(color * (a * color + b)) / (color * (c * color + d) + e));
return new_cl;
};
float value = tone_mapping_ ? AcesFilmicToneMapping(framebuffer_[i][j] * inv_spp) : framebuffer_[i][j] * inv_spp;
if (gamma_) {
tmp = static_cast<uint8_t>(
std::pow(clamp(0.0f, kOneMinusEps, value), gamma_index) * 255);
} else {
tmp = static_cast<uint8_t>(clamp(0.0f, kOneMinusEps, value) * 255);
}
data[3 * i + j] = tmp;
}
}
Image img(data.get(), height, width, type, 3);
if (!img.write_image(filename, false)) {
std::cerr << "Error: Writing " + filename << "failed" << std::endl;
}
}
| 34.257426 | 119 | 0.592486 | BlurryLight |
67fcac273c5d64e4b5d88d8de1e0ade6c11005d5 | 123 | hpp | C++ | src/FSNG/Forge/Ticket.hpp | ChristofferGreen/Forsoning | 838b35587c00227f2f5cdd91ba78bc63b76835fe | [
"BSD-2-Clause"
] | null | null | null | src/FSNG/Forge/Ticket.hpp | ChristofferGreen/Forsoning | 838b35587c00227f2f5cdd91ba78bc63b76835fe | [
"BSD-2-Clause"
] | null | null | null | src/FSNG/Forge/Ticket.hpp | ChristofferGreen/Forsoning | 838b35587c00227f2f5cdd91ba78bc63b76835fe | [
"BSD-2-Clause"
] | null | null | null | #pragma once
namespace FSNG {
using Ticket = uint64_t;
inline Ticket InvalidTicket = 0;
inline Ticket FirstTicket = 1;
} | 17.571429 | 32 | 0.747967 | ChristofferGreen |
67fd44fc2d6c2574114b00eb498c782013bf0656 | 4,331 | cpp | C++ | tests/Transaction/CountCacheTest.cpp | Mu-L/arangodb | a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | tests/Transaction/CountCacheTest.cpp | Mu-L/arangodb | a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | tests/Transaction/CountCacheTest.cpp | Mu-L/arangodb | a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "Transaction/CountCache.h"
#include "Basics/system-functions.h"
#include "gtest/gtest.h"
#include <chrono>
#include <thread>
using namespace arangodb;
struct SpeedyCountCache : public transaction::CountCache {
explicit SpeedyCountCache(double ttl)
: CountCache(ttl), _time(TRI_microtime()) {}
double getTime() const override { return _time; }
void advanceTime(double value) { _time += value; }
double _time;
};
TEST(TransactionCountCacheTest, testExpireShort) {
SpeedyCountCache cache(0.5);
EXPECT_EQ(transaction::CountCache::NotPopulated, cache.get());
EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl());
cache.store(0);
EXPECT_EQ(0, cache.get());
EXPECT_EQ(0, cache.getWithTtl());
cache.store(555);
EXPECT_EQ(555, cache.get());
EXPECT_EQ(555, cache.getWithTtl());
cache.advanceTime(0.550);
EXPECT_EQ(555, cache.get());
EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl());
cache.store(21111234);
EXPECT_EQ(21111234, cache.get());
EXPECT_EQ(21111234, cache.getWithTtl());
cache.store(0);
EXPECT_EQ(0, cache.get());
EXPECT_EQ(0, cache.getWithTtl());
cache.advanceTime(0.550);
EXPECT_EQ(0, cache.get());
EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl());
}
TEST(TransactionCountCacheTest, testExpireMedium) {
SpeedyCountCache cache(1.5);
EXPECT_EQ(transaction::CountCache::NotPopulated, cache.get());
EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl());
cache.store(0);
EXPECT_EQ(0, cache.get());
EXPECT_EQ(0, cache.getWithTtl());
cache.store(555);
EXPECT_EQ(555, cache.get());
EXPECT_EQ(555, cache.getWithTtl());
cache.advanceTime(0.250);
EXPECT_EQ(555, cache.get());
EXPECT_EQ(555, cache.getWithTtl());
cache.advanceTime(0.250);
EXPECT_EQ(555, cache.get());
EXPECT_EQ(555, cache.getWithTtl());
cache.advanceTime(1.100);
EXPECT_EQ(555, cache.get());
EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl());
cache.store(21111234);
EXPECT_EQ(21111234, cache.get());
EXPECT_EQ(21111234, cache.getWithTtl());
cache.advanceTime(0.250);
EXPECT_EQ(21111234, cache.get());
EXPECT_EQ(21111234, cache.getWithTtl());
cache.advanceTime(1.350);
EXPECT_EQ(21111234, cache.get());
EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl());
}
TEST(TransactionCountCacheTest, testExpireLong) {
SpeedyCountCache cache(60.0);
EXPECT_EQ(transaction::CountCache::NotPopulated, cache.get());
EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl());
cache.store(0);
EXPECT_EQ(0, cache.get());
EXPECT_EQ(0, cache.getWithTtl());
cache.store(666);
EXPECT_EQ(666, cache.get());
EXPECT_EQ(666, cache.getWithTtl());
cache.advanceTime(0.250);
EXPECT_EQ(666, cache.get());
EXPECT_EQ(666, cache.getWithTtl());
cache.advanceTime(1.100);
EXPECT_EQ(666, cache.get());
EXPECT_EQ(666, cache.getWithTtl());
cache.store(777);
EXPECT_EQ(777, cache.get());
EXPECT_EQ(777, cache.getWithTtl());
cache.store(888);
EXPECT_EQ(888, cache.get());
EXPECT_EQ(888, cache.getWithTtl());
cache.advanceTime(55.0);
EXPECT_EQ(888, cache.get());
EXPECT_EQ(888, cache.getWithTtl());
cache.advanceTime(5.01);
EXPECT_EQ(888, cache.get());
EXPECT_EQ(transaction::CountCache::NotPopulated, cache.getWithTtl());
}
| 26.248485 | 80 | 0.688063 | Mu-L |
67fd5c5d44da68fae86afeac9f5450e67686a413 | 449 | cxx | C++ | src/Comment.cxx | astrorigin/html5xx | cbaaeb232597a713630df7425752051036cf0cb2 | [
"MIT"
] | null | null | null | src/Comment.cxx | astrorigin/html5xx | cbaaeb232597a713630df7425752051036cf0cb2 | [
"MIT"
] | null | null | null | src/Comment.cxx | astrorigin/html5xx | cbaaeb232597a713630df7425752051036cf0cb2 | [
"MIT"
] | null | null | null | /*
*
*/
#include "Comment.hxx"
using namespace std;
namespace html
{
string Comment::toString() const
{
string s = m_text;
size_t found, pos = 0;
const string ind = indent();
const string nl = "\n" + ind + ' ';
while ((found = s.find('\n', pos)) != string::npos) {
s.replace(found, 1, nl);
pos = found + nl.length();
}
return ind + "<!-- " + s + " -->\n";
}
} // end namespace html
// vi: set ai et sw=2 sts=2 ts=2 :
| 14.966667 | 55 | 0.545657 | astrorigin |
67ff43d0f01815e59fc6e059a1bf127ed6f16095 | 107,073 | cc | C++ | SimG4CMS/Calo/src/HFFibreFiducial.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | SimG4CMS/Calo/src/HFFibreFiducial.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | SimG4CMS/Calo/src/HFFibreFiducial.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | #include "SimG4CMS/Calo/interface/HFFibreFiducial.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "CLHEP/Units/GlobalPhysicalConstants.h"
#include "CLHEP/Units/GlobalSystemOfUnits.h"
#include<iostream>
//#define DebugLog
int HFFibreFiducial::PMTNumber(const G4ThreeVector& pe_effect)
{
double xv = pe_effect.x(); // X in global system
double yv = pe_effect.y(); // Y in global system
double phi = atan2(yv, xv); // In global system
if (phi < 0.) phi+=CLHEP::pi; // Just for security
double dph = CLHEP::pi/18; // 10 deg = a half sector width
double sph = dph+dph; // 20 deg = a sector width
int nphi = phi/dph; // 10 deg sector #
#ifdef DebugLog
edm::LogInfo("HFShower") <<"HFFibreFiducial:***> P = " << pe_effect
<< ", phi = " << phi/CLHEP::deg;
#endif
if (nphi > 35) nphi=35; // Just for security
double xl=0.; // local sector coordinates (left/right)
double yl=0.; // local sector coordinates (down/up)
int nwid=0; // CMS widget number (@@ not used now M.K.)
double phir= 0.; // phi for rotation to the sector system
if (nphi==0 || nphi==35)
{
yl=xv;
xl=yv;
nwid=6;
}
else if (nphi==17 || nphi==18)
{
yl=-xv;
xl=-yv;
nwid=15;
phir=CLHEP::pi; // nr=9 ?
}
else
{
int nr = (nphi+1)/2; // a sector # (@@ internal definition)
nwid = 6-nr;
if(nwid <= 0) nwid+=18; // @@ +z || -z M.K. to be improved
phir= sph*nr; // nontrivial phi for rotation to the sector system
double cosr= cos(phir);
double sinr= sin(phir);
yl= xv*cosr+yv*sinr;
xl= yv*cosr-xv*sinr;
#ifdef DebugLog
edm::LogInfo("HFShower") << "HFFibreFiducial: nr " << nr << " phi " << phir/CLHEP::deg;
#endif
}
if (yl < 0) yl =-yl;
#ifdef DebugLog
edm::LogInfo("HFShower") << "HFFibreFiducial: Global Point " << pe_effect
<< " nphi " << nphi << " Local Sector Coordinates ("
<< xl << ", " << yl << "), widget # " << nwid;
#endif
// Provides a PMT # for the (x,y) hit in the widget # nwid (M. Kosov, 11.2010)
// Send comments/questions to Mikhail.Kossov@cern.ch
// nwid = 1-18 for Forward HF, 19-36 for Backward HF (all equal now)
// npmt = 0 for No Hit, 1-24 for H(Long) PMT, 25-48 for E(Short) PMT, negative for souces
static const int nWidM=36;
if (nwid > nWidM || nwid <= 0)
{
#ifdef DebugLog
edm::LogInfo("HFShower") << "-Warning-HFFibreFiducial::PMTNumber: "
<< nwid << " == wrong widget number";
#endif
return 0;
}
static const double yMin= 13.1*CLHEP::cm; // start of the active area (Conv to mm?)
static const double yMax=129.6*CLHEP::cm; // finish of the active area (Conv to mm?)
if( yl < yMin || yl >= yMax )
{
#ifdef DebugLog
edm::LogInfo("HFShower") << "-Warning-HFFibreFiducial::PMTNumber: Point "
<< "with y = " << yl << " outside acceptance ["
<< yMin << ":" << yMax << "], X = " << xv
<< ", Y = " << yv << ", x = " << xl << ", nW = "
<< nwid << ", phi = " << phi/CLHEP::deg
<< ", phir = " << phir/CLHEP::deg;
#endif
return 0; // ===> out of the acceptance
}
bool left=true; // flag of the left part of the widget
double r=xl/yl; // for the widget acceptance check
if (r < 0)
{
r=-r;
left=false;
}
static const double tg10=.17632698070847; // phi-angular acceptance of the widget
if (r > tg10)
{
#ifdef DebugLog
edm::LogInfo("HFShower") << "-Warning-HFFibreFiducial::PMTNumber: (x = "
<< xl << ", y = " << yl << ", tg = " << r
<< ") out of the widget acceptance tg(10) " << tg10;
#endif
return 0;
}
static const int nLay=233; // a # of the sensetive layers in the widget
static const int nL001=4;
static const int nL002=4;
static const int nL003=5;
static const int nL004=5;
static const int nL005=5; // (5)
static const int nL006=5;
static const int nL007=5;
static const int nL008=6;
static const int nL009=6;
static const int nL010=6; // (6)
static const int nL011=6;
static const int nL012=6;
static const int nL013=6;
static const int nL014=7;
static const int nL015=7;
static const int nL016=7; // (6)
static const int nL017=7;
static const int nL018=7;
static const int nL019=7;
static const int nL020=8;
static const int nL021=8;
static const int nL022=8; // (5)
static const int nL023=8;
static const int nL024=8;
static const int nL025=9;
static const int nL026=9;
static const int nL027=9; // (6)
static const int nL028=9;
static const int nL029=9;
static const int nL030=9;
static const int nL031=10;
static const int nL032=10;
static const int nL033=10; // (6)
static const int nL034=10;
static const int nL035=10;
static const int nL036=10;
static const int nL037=11;
static const int nL038=11; // (5)
static const int nL039=11;
static const int nL040=11;
static const int nL041=11;
static const int nL042=12;
static const int nL043=12;
static const int nL044=12;
static const int nL045=12; // (6)
static const int nL046=12;
static const int nL047=12;
static const int nL048=13;
static const int nL049=13;
static const int nL050=13; // (6)
static const int nL051=13;
static const int nL052=13;
static const int nL053=13;
static const int nL054=14;
static const int nL055=14;
static const int nL056=14; // (5)
static const int nL057=14;
static const int nL058=14;
static const int nL059=15;
static const int nL060=15;
static const int nL061=15; // (6)
static const int nL062=15;
static const int nL063=15;
static const int nL064=15;
static const int nL065=16;
static const int nL066=16;
static const int nL067=16; // (6)
static const int nL068=16;
static const int nL069=16;
static const int nL070=16;
static const int nL071=17;
static const int nL072=17;
static const int nL073=17; // (5)
static const int nL074=17;
static const int nL075=17;
static const int nL076=18;
static const int nL077=18;
static const int nL078=18; // (6)
static const int nL079=18;
static const int nL080=18;
static const int nL081=18;
static const int nL082=19;
static const int nL083=19; // (6)
static const int nL084=19;
static const int nL085=19;
static const int nL086=19;
static const int nL087=19;
static const int nL088=20;
static const int nL089=20;
static const int nL090=20; // (5)
static const int nL091=20;
static const int nL092=20;
static const int nL093=21;
static const int nL094=21;
static const int nL095=21; // (6)
static const int nL096=21;
static const int nL097=21;
static const int nL098=21;
static const int nL099=22;
static const int nL100=22;
static const int nL101=22; // (6)
static const int nL102=22;
static const int nL103=22;
static const int nL104=22;
static const int nL105=23;
static const int nL106=23;
static const int nL107=23; // (5)
static const int nL108=23;
static const int nL109=23;
static const int nL110=24;
static const int nL111=24;
static const int nL112=24; // (6)
static const int nL113=24;
static const int nL114=24;
static const int nL115=24;
static const int nL116=25;
static const int nL117=25;
static const int nL118=25; // (6)
static const int nL119=25;
static const int nL120=25;
static const int nL121=25;
static const int nL122=26;
static const int nL123=26;
static const int nL124=26; // (5)
static const int nL125=26;
static const int nL126=26;
static const int nL127=27;
static const int nL128=27;
static const int nL129=27; // (6)
static const int nL130=27;
static const int nL131=27;
static const int nL132=27;
static const int nL133=28;
static const int nL134=28;
static const int nL135=28; // (6)
static const int nL136=28;
static const int nL137=28;
static const int nL138=28;
static const int nL139=29;
static const int nL140=29;
static const int nL141=29; // (5)
static const int nL142=29;
static const int nL143=29;
static const int nL144=30;
static const int nL145=30;
static const int nL146=30; // (6)
static const int nL147=30;
static const int nL148=30;
static const int nL149=30;
static const int nL150=31;
static const int nL151=31;
static const int nL152=31; // (6)
static const int nL153=31;
static const int nL154=31;
static const int nL155=31;
static const int nL156=32;
static const int nL157=32; // (5)
static const int nL158=32;
static const int nL159=32;
static const int nL160=32;
static const int nL161=33;
static const int nL162=33; // (6)
static const int nL163=33;
static const int nL164=33;
static const int nL165=33;
static const int nL166=33;
static const int nL167=34;
static const int nL168=34;
static const int nL169=34; // (6)
static const int nL170=34;
static const int nL171=34;
static const int nL172=34;
static const int nL173=35;
static const int nL174=35;
static const int nL175=35; // (5)
static const int nL176=35;
static const int nL177=35;
static const int nL178=36;
static const int nL179=36;
static const int nL180=36; // (6)
static const int nL181=36;
static const int nL182=36;
static const int nL183=36;
static const int nL184=37;
static const int nL185=37;
static const int nL186=37; // (6)
static const int nL187=37;
static const int nL188=37;
static const int nL189=37;
static const int nL190=38;
static const int nL191=38;
static const int nL192=38; // (5)
static const int nL193=38;
static const int nL194=38;
static const int nL195=39;
static const int nL196=39;
static const int nL197=39;
static const int nL198=39; // (6)
static const int nL199=39;
static const int nL200=39;
static const int nL201=40;
static const int nL202=40;
static const int nL203=40; // (6)
static const int nL204=40;
static const int nL205=40;
static const int nL206=40;
static const int nL207=41;
static const int nL208=41;
static const int nL209=41; // (5)
static const int nL210=41;
static const int nL211=41;
static const int nL212=42;
static const int nL213=42;
static const int nL214=42;
static const int nL215=42; // (6)
static const int nL216=42;
static const int nL217=42;
static const int nL218=43;
static const int nL219=43;
static const int nL220=43; // (6)
static const int nL221=43;
static const int nL222=43;
static const int nL223=43;
static const int nL224=44;
static const int nL225=44;
static const int nL226=44; // (5)
static const int nL227=44;
static const int nL228=44;
static const int nL229=45;
static const int nL230=45;
static const int nL231=45; // (5+1=6)
static const int nL232=45;
static const int nL233=45;
//------------------------------------------------------------------------------------
// Mean numbers of fibers in the layer is used. In some widgets it's bigger ***
// (if the fiber passed throug the hole closer to the edge) and sometimes it ***
// is smaller (if in some holes of the layer fibers did not pass throug). ***
// The real presence of fibers in the holes is now unknown (not documented), ***
// but the narrow electron showers can be used for revealing of the missing ***
// or additional fibers in the widget, because the missing fibers reduce the ***
// response and additional fibers increas it. So the tables can be improved ***
// to be individual for widgets and the FXX/BXX sources-tables can be used. ***
// ********************** M.Kosov, Mikhail.Kosssov@cern.ch *********************
// NNI, NN=tower#(1-24), i=0: dead; i=1: E(L); i=2: H(S); i=3: ESource; i=4: HSource
static const int tR001[nL001]={132,131,132,131}; // Left Part of the widget (-phi)
static const int tR002[nL002]={131,132,131,132};
static const int tR003[nL003]={132,131,132,131,132};
static const int tR004[nL004]={133,132,131,132,131}; // (5)
static const int tR005[nL005]={132,131,132,131,132};
static const int tR006[nL006]={131,132,131,132,131};
static const int tR007[nL007]={132,131,132,131,132};
static const int tR008[nL008]={131,132,131,132,131,132}; // _______________________13_
static const int tR009[nL009]={122,121,122,121,122,121};
static const int tR010[nL010]={121,122,121,122,123,122}; // (6) (A)
static const int tR011[nL011]={122,121,122,121,122,121};
static const int tR012[nL012]={121,122,121,122,121,122};
static const int tR013[nL013]={122,121,122,121,122,121};
static const int tR014[nL014]={121,122,121,122,121,122,121}; //____________________12_
static const int tR015[nL015]={122,121,242,241,242,241,242}; // (6)
static const int tR016[nL016]={241,242,241,242,241,242,241};
static const int tR017[nL017]={242,241,242,241,242,241,242};
static const int tR018[nL018]={241,242,241,242,243,242,241};
static const int tR019[nL019]={242,241,242,241,242,241,242};
static const int tR020[nL020]={241,242,241,242,241,242,241,242};
static const int tR021[nL021]={242,241,242,241,242,241,242,241}; // (5)
static const int tR022[nL022]={241,242,241,242,241,242,241,242}; //________________24_
static const int tR023[nL023]={232,231,232,231,232,231,232,231};
static const int tR024[nL024]={231,232,231,232,231,232,231,232};
static const int tR025[nL025]={232,231,232,231,232,231,232,231,232};
static const int tR026[nL026]={231,232,231,232,233,232,231,232,231};
static const int tR027[nL027]={232,231,232,231,232,231,232,231,232}; // (6)
static const int tR028[nL028]={231,232,231,232,231,232,231,232,231};
static const int tR029[nL029]={232,231,232,231,232,231,232,231,232};
static const int tR030[nL030]={231,232,231,232,231,232,231,232,231};
static const int tR031[nL031]={232,231,232,231,232,231,232,231,232,231}; //________23_
static const int tR032[nL032]={231,232,231,222,221,222,221,222,221,222};
static const int tR033[nL033]={222,221,222,221,222,221,222,221,222,221}; // (6)
static const int tR034[nL034]={221,222,221,222,221,222,221,222,221,222};
static const int tR035[nL035]={222,221,222,221,222,221,222,221,222,221};
static const int tR036[nL036]={221,222,221,222,223,222,221,222,221,222};
static const int tR037[nL037]={222,221,222,221,222,221,222,221,222,221,222};
static const int tR038[nL038]={221,222,221,222,221,222,221,222,221,222,221};
static const int tR039[nL039]={222,221,222,221,222,221,222,221,222,221,222}; // (5)
static const int tR040[nL040]={221,222,221,222,221,222,221,222,221,222,221};//_____22_
static const int tR041[nL041]={212,211,212,211,212,211,212,211,212,211,212};
static const int tR042[nL042]={211,212,211,212,211,212,211,212,211,212,211,212};
static const int tR043[nL043]={212,211,212,211,212,211,212,211,212,211,212,211};
static const int tR044[nL044]={211,212,211,212,211,212,211,212,211,212,211,212};
static const int tR045[nL045]={212,211,212,211,212,211,212,211,212,211,212,211};//(6)
static const int tR046[nL046]={211,212,211,212,211,212,211,212,211,212,211,212};
static const int tR047[nL047]={212,211,212,211,212,211,212,211,212,211,212,211};
static const int tR048[nL048]={211,212,211,212,211,212,211,214,211,212,211,212,211};
static const int tR049[nL049]={212,211,212,211,212,211,212,211,212,211,212,211,212};
static const int tR050[nL050]={211,212,211,212,211,212,211,212,211,212,211,212,211};
static const int tR051[nL051]={212,211,212,211,212,211,212,211,212,211,212,211,212};//(6)
static const int tR052[nL052]={211,212,211,212,211,212,211,212,211,212,211,212,211};
static const int tR053[nL053]={212,211,212,211,212,211,212,211,212,211,212,211,212};
static const int tR054[nL054]={211,212,211,212,211,212,211,212,211,212,211,212,211,212};
static const int tR055[nL055]={212,211,212,211,212,211,212,211,212,211,212,211,212,211};
// _______________________________________________________________________________21_ (5)
static const int tR056[nL056]={211,212,211,202,201,202,201,202,201,202,201,202,201,202};
static const int tR057[nL057]={202,201,202,201,202,201,202,201,202,201,202,201,202,201};
static const int tR058[nL058]={201,202,201,202,201,202,201,202,201,202,201,202,201,202};
static const int tR059[nL059]={202,201,202,201,202,201,202,201,202,201,202,201,202,201,
202};
static const int tR060[nL060]={201,202,201,202,201,202,201,202,201,202,201,202,201,202,
201};
static const int tR061[nL061]={202,201,202,201,202,201,202,201,202,201,202,201,202,201,
202}; // (6)
static const int tR062[nL062]={201,202,201,202,201,202,201,204,201,202,201,202,201,202,
201};
static const int tR063[nL063]={202,201,202,201,202,201,202,201,202,201,202,201,202,201,
202};
static const int tR064[nL064]={201,202,201,202,201,202,201,202,201,202,201,202,201,202,
201};
static const int tR065[nL065]={202,201,202,201,202,201,202,201,202,201,202,201,202,201,
202,201};
static const int tR066[nL066]={201,202,201,202,201,202,201,202,201,202,201,202,201,202,
201,202}; // (6)
static const int tR067[nL067]={202,201,202,201,202,201,202,201,202,201,202,201,202,201,
202,201};
static const int tR068[nL068]={201,202,201,202,201,202,201,202,201,202,201,202,201,202,
201,202};
static const int tR069[nL069]={202,201,202,201,202,201,202,201,202,201,202,201,202,201,
202,201};
static const int tR070[nL070]={201,202,201,202,201,202,201,202,201,202,201,202,201,202,
201,202};
static const int tR071[nL071]={202,201,202,201,202,201,202,201,202,201,192,191,192,191,
192,191,192}; // ___________________________________20_
static const int tR072[nL072]={191,192,191,192,191,192,191,192,191,192,191,192,191,192,
191,192,191};
static const int tR073[nL073]={192,191,192,191,192,191,192,191,192,191,192,191,192,191,
192,191,192}; // (5)
static const int tR074[nL074]={191,192,191,192,191,192,191,192,191,192,191,192,191,192,
191,192,191};
static const int tR075[nL075]={192,191,192,191,192,191,192,191,192,191,192,191,192,191,
192,191,192};
static const int tR076[nL076]={191,192,191,192,191,192,191,192,191,192,191,192,191,192,
191,192,191,192};
static const int tR077[nL077]={192,191,192,191,192,191,192,191,192,191,192,191,192,191,
192,191,192,191};
static const int tR078[nL078]={191,192,191,192,191,192,191,192,191,192,191,192,191,192,
191,192,191,192}; // (6)
static const int tR079[nL079]={192,191,192,191,192,191,192,191,192,191,192,191,192,191,
192,191,192,191};
static const int tR080[nL080]={191,192,191,192,191,192,191,194,191,192,191,192,191,192,
191,192,191,192};
static const int tR081[nL081]={192,191,192,191,192,191,192,191,192,191,192,191,192,191,
192,191,192,191};
static const int tR082[nL082]={191,192,191,192,191,192,191,192,191,192,191,192,191,192,
191,192,191,192,191};
static const int tR083[nL083]={192,191,192,191,192,191,192,191,192,191,192,191,192,191,
192,191,192,191,192};
static const int tR084[nL084]={191,192,191,192,191,192,191,192,191,192,191,192,191,192,
191,192,191,192,191}; // (6)
static const int tR085[nL085]={192,191,192,191,192,191,192,191,192,191,192,191,192,191,
192,191,192,191,192};
static const int tR086[nL086]={191,192,191,192,191,192,191,192,191,192,191,192,191,192,
191,192,191,192,191};
static const int tR087[nL087]={192,191,192,191,192,191,192,191,192,191,192,191,192,191,
192,191,192,191,192};
static const int tR088[nL088]={191,192,191,192,191,192,191,192,191,192,191,192,191,192,
191,192,181,182,181,182}; // _______________________19_
// ------------------------------------------------------------------------------------
static const int tR089[nL089]={192,191,192,191,182,181,182,181,182,181,182,181,182,181,
182,181,182,181,182,181}; // (5)
static const int tR090[nL090]={181,182,181,182,181,182,181,182,181,182,181,182,181,182,
181,182,181,182,181,182};
static const int tR091[nL091]={182,181,182,181,182,181,182,181,182,181,182,181,182,181,
182,181,182,181,182,181};
static const int tR092[nL092]={181,182,181,182,181,182,181,182,181,182,181,182,181,182,
181,182,181,182,181,182};
static const int tR093[nL093]={182,181,182,181,182,181,182,181,182,181,182,181,182,181,
182,181,182,181,182,181,182};
static const int tR094[nL094]={181,182,181,182,181,182,181,182,181,182,181,182,181,182,
181,182,181,182,181,182,181};
static const int tR095[nL095]={182,181,182,181,182,181,182,181,182,181,182,181,182,181,
182,181,182,181,182,181,182}; // (6)
static const int tR096[nL096]={181,182,181,182,181,182,181,182,181,182,181,182,181,182,
181,182,181,182,181,182,181};
static const int tR097[nL097]={182,181,182,181,182,181,182,181,182,181,182,181,182,181,
182,181,182,181,182,181,182};
static const int tR098[nL098]={181,182,181,182,181,182,181,182,181,182,181,182,181,182,
181,182,181,182,181,182,181};
static const int tR099[nL099]={182,181,182,181,182,181,182,181,182,181,182,181,182,181,
182,181,182,181,182,181,182,181};
static const int tR100[nL100]={181,182,181,182,181,182,181,182,181,182,181,182,183,182,
181,182,181,182,181,182,181,182}; // (6)
static const int tR101[nL101]={182,181,182,181,182,181,182,181,182,181,182,181,182,181,
182,181,182,181,182,181,182,181};
static const int tR102[nL102]={181,182,181,182,181,182,181,182,181,182,181,182,181,182,
181,182,181,182,181,182,181,182};
static const int tR103[nL103]={182,181,182,181,182,181,182,181,182,181,182,181,182,181,
182,181,182,181,182,181,182,181};
static const int tR104[nL104]={181,182,181,182,181,182,181,182,181,182,181,182,181,182,
181,182,181,182,181,182,181,182};
static const int tR105[nL105]={182,181,182,181,182,181,182,181,182,181,182,181,182,181,
182,181,182,181,182,181,182,181,182};
static const int tR106[nL106]={181,182,181,182,181,182,181,182,181,182,181,182,181,182,
181,182,181,182,181,182,181,182,181};
static const int tR107[nL107]={182,181,182,181,182,181,182,181,182,181,182,181,182,181,
182,181,182,181,182,181,182,181,182}; // (5)
static const int tR108[nL108]={181,182,181,182,181,182,181,182,181,182,181,182,181,182,
181,182,181,182,181,182,181,182,181};
static const int tR109[nL109]={182,181,182,181,182,181,182,181,182,181,182,181,182,181,
182,181,182,181,182,181,182,181,182};
static const int tR110[nL110]={181,182,181,182,181,182,181,182,181,182,181,182,181,182,
181,182,181,182,181,182,181,182,181,182};
static const int tR111[nL111]={182,181,182,181,182,181,182,181,182,181,182,181,182,181,
182,181,182,171,172,171,172,171,172,171}; // _________4_
static const int tR112[nL112]={181,182,181,182,171,172,171,172,171,172,171,172,171,172,
171,172,171,172,171,172,171,172,171,172}; // (6)
static const int tR113[nL113]={172,171,172,171,172,171,172,171,172,171,172,171,172,171,
172,171,172,171,172,171,172,171,172,171};
static const int tR114[nL114]={171,172,171,172,171,172,171,172,171,172,171,172,171,172,
171,172,171,172,171,172,171,172,171,172};
static const int tR115[nL115]={172,171,172,171,172,171,172,171,172,171,172,171,172,171,
172,171,172,171,172,171,172,171,172,171};
static const int tR116[nL116]={171,172,171,172,171,172,171,172,171,172,171,172,171,172,
171,172,171,172,171,172,171,172,171,172,171};
static const int tR117[nL117]={172,171,172,171,172,171,172,171,172,171,172,171,172,171,
172,171,172,171,172,171,172,171,172,171,172};
static const int tR118[nL118]={171,172,171,172,171,172,171,172,171,172,171,172,171,172,
171,172,171,172,171,172,171,172,171,172,171};
static const int tR119[nL119]={172,171,172,171,172,171,172,171,172,171,172,171,172,171,
172,171,172,171,172,171,172,171,172,171,172}; // (6)
static const int tR120[nL120]={171,172,171,172,171,172,171,172,171,172,171,172,171,172,
171,172,171,172,171,172,171,172,171,172,171};
static const int tR121[nL121]={172,171,172,171,172,171,172,171,172,171,172,171,172,171,
172,171,172,171,172,171,172,171,172,171,172};
static const int tR122[nL122]={171,172,171,172,171,172,171,172,171,172,171,172,171,172,
171,172,171,172,171,172,171,172,171,172,171,172};
static const int tR123[nL123]={172,171,172,171,172,171,172,171,172,171,172,171,172,171,
172,171,172,171,172,171,172,171,172,171,172,171};
static const int tR124[nL124]={171,172,171,172,171,172,171,172,171,172,171,172,173,172,
171,172,171,172,171,172,171,172,171,172,171,172};// (5)
static const int tR125[nL125]={172,171,172,171,172,171,172,171,172,171,172,171,172,171,
172,171,172,171,172,171,172,171,172,171,172,171};
static const int tR126[nL126]={171,172,171,172,171,172,171,172,171,172,171,172,171,172,
171,172,171,172,171,172,171,172,171,172,171,172};
static const int tR127[nL127]={172,171,172,171,172,171,172,171,172,171,172,171,172,171,
172,171,172,171,172,171,172,171,172,171,172,171,172};
static const int tR128[nL128]={171,172,171,172,171,172,171,172,171,172,171,172,171,172,
171,172,171,172,171,172,171,172,171,172,171,172,171};
static const int tR129[nL129]={172,171,172,171,172,171,172,171,172,171,172,171,172,171,
172,171,172,171,172,171,172,171,172,171,172,171,172};
static const int tR130[nL130]={171,172,171,172,171,172,171,172,171,172,171,172,171,172,
171,172,171,172,171,172,171,172,171,172,171,172,171};//(6)
static const int tR131[nL131]={172,171,172,171,172,171,172,171,172,171,172,171,172,171,
172,171,172,171,172,171,172,171,172,171,172,171,172};
static const int tR132[nL132]={171,172,171,172,171,172,171,172,171,172,171,172,171,172,
171,172,171,172,171,172,171,172,171,172,171,172,171};
static const int tR133[nL133]={172,171,172,171,172,171,172,171,172,171,172,171,172,171,
172,171,172,171,172,171,172,171,172,171,172,171,172,171};
static const int tR134[nL134]={171,172,171,172,171,172,171,172,171,172,171,172,171,172,
171,172,171,172,171,172,171,172,171,172,171,172,171,172};
static const int tR135[nL135]={172,171,172,171,172,171,172,171,172,171,172,171,172,171,
172,171,172,171,172,171,172,171,172,171,172,171,172,171};
static const int tR136[nL136]={171,172,171,172,171,172,171,172,171,172,171,172,171,172,
171,172,171,172,171,172,171,172,171,172,171,172,171,172};
static const int tR137[nL137]={172,171,172,171,172,171,172,171,172,171,172,171,172,171,
172,171,172,171,172,171,172,171,162,161,162,161,162,161};
// ____________________________________________________________________________(6)___3_
static const int tR138[nL138]={171,172,171,172,171,172,171,172,171,172,171,172,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,162};
static const int tR139[nL139]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162};
static const int tR140[nL140]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161};
static const int tR141[nL141]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162}; // (5)
static const int tR142[nL142]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161};
static const int tR143[nL143]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162};
static const int tR144[nL144]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162};
static const int tR145[nL145]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161};
static const int tR146[nL146]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,163,162,161,162,161,162,161,162,161,162,161,162,
161,162};
static const int tR147[nL147]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161}; // (6)
static const int tR148[nL148]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162};
static const int tR149[nL149]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161};
static const int tR150[nL150]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161};
static const int tR151[nL151]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162};
static const int tR152[nL152]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161}; // (6)
static const int tR153[nL153]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162};
static const int tR154[nL154]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161};
static const int tR155[nL155]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162};
static const int tR156[nL156]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162};
static const int tR157[nL157]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161};
static const int tR158[nL158]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162}; // (5)
static const int tR159[nL159]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161};
static const int tR160[nL160]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,163,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162};
static const int tR161[nL161]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162};
static const int tR162[nL162]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161};
static const int tR163[nL163]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162}; // (6)
static const int tR164[nL164]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161};
static const int tR165[nL165]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162};
static const int tR166[nL166]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161};
static const int tR167[nL167]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,162,161};
static const int tR168[nL168]={161,162,161,162,161,162,161,162,161,162,161,162,161,162,
161,162,161,162,161,162,161,162,161,162,161,162,161,152,
151,152,151,152,151,152}; // _________________________2_
static const int tR169[nL169]={162,161,162,161,162,161,162,161,162,161,162,161,162,161,
162,161,162,161,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151}; // (6)
static const int tR170[nL170]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152};
static const int tR171[nL171]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151};
static const int tR172[nL172]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152};
static const int tR173[nL173]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152};
static const int tR174[nL174]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151};
static const int tR175[nL175]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152}; // (5)
static const int tR176[nL176]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151};
static const int tR177[nL177]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152};
static const int tR178[nL178]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,153,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152};
static const int tR179[nL179]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151};
static const int tR180[nL180]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152}; // (6)
static const int tR181[nL181]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151};
static const int tR182[nL182]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152};
static const int tR183[nL183]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151};
static const int tR184[nL184]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151};
static const int tR185[nL185]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152};
static const int tR186[nL186]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151};
static const int tR187[nL187]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152}; // (6)
static const int tR188[nL188]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151};
static const int tR189[nL189]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152};
static const int tR190[nL190]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152};
static const int tR191[nL191]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151};
static const int tR192[nL192]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152}; // (5)
static const int tR193[nL193]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151};
static const int tR194[nL194]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152};
static const int tR195[nL195]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152};
static const int tR196[nL196]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,153,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151};
static const int tR197[nL197]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152}; // (6)
static const int tR198[nL198]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151};
static const int tR199[nL199]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152};
static const int tR200[nL200]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151};
static const int tR201[nL201]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151};
static const int tR202[nL202]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152};
static const int tR203[nL203]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151}; //(6)
static const int tR204[nL204]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,151,152};
static const int tR205[nL205]={152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,152,151,152,151,152,151,152,151,152,151,
152,151,152,151,142,141,142,141,142,141,142,141};
static const int tR206[nL206]={151,152,151,152,151,152,151,152,151,152,151,152,151,152,
151,152,151,152,151,152,151,152,151,152,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142};//__1_
static const int tR207[nL207]={152,151,152,151,152,151,152,151,152,151,152,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142};
static const int tR208[nL208]={141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141};
static const int tR209[nL209]={142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142};//(5)
static const int tR210[nL210]={141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141};
static const int tR211[nL211]={142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142};
static const int tR212[nL212]={141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,143,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142};
static const int tR213[nL213]={142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141};
static const int tR214[nL214]={141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142};
static const int tR215[nL215]={142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141};
static const int tR216[nL216]={141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142};
static const int tR217[nL217]={142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141};
static const int tR218[nL218]={141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141};
static const int tR219[nL219]={142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142};
static const int tR220[nL220]={141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141};
static const int tR221[nL221]={142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142}; // (6)
static const int tR222[nL222]={141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141};
static const int tR223[nL223]={142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142};
static const int tR224[nL224]={141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142};
static const int tR225[nL225]={142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141};
static const int tR226[nL226]={141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,143,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142}; // (5)
static const int tR227[nL227]={142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141};
static const int tR228[nL228]={141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142};
static const int tR229[nL229]={142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142};
static const int tR230[nL230]={141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141};
static const int tR231[nL231]={142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141,142,141,142, 0, 0, 0,
0, 0, 0}; // (5+1=6)
static const int tR232[nL232]={141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142,141,142,141,142,141,142,141,142,141,142,
141,142,141,142, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0};
static const int tR233[nL233]={142,141,142,141,142,141,142,141,142,141,142,141,142,141,
142,141,142,141,142,141,142,141, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0};
//------------------------------------------------------------------------------------
static const int tL001[nL001]={131,132,131,132}; // Left Part of the widget (-phi)
static const int tL002[nL002]={132,131,132,131};
static const int tL003[nL003]={131,132,131,132,131};
static const int tL004[nL004]={132,131,132,131,132}; // (5)
static const int tL005[nL005]={131,132,131,132,131};
static const int tL006[nL006]={132,131,132,131,132};
static const int tL007[nL007]={131,132,131,132,131};
static const int tL008[nL008]={132,131,132,131,132,131}; // ______________________13_
static const int tL009[nL009]={121,122,121,122,121,122};
static const int tL010[nL010]={122,121,122,121,124,121};
static const int tL011[nL011]={121,122,121,122,121,122}; // (6) (B)
static const int tL012[nL012]={122,121,122,121,122,121};
static const int tL013[nL013]={121,122,121,122,121,122};
static const int tL014[nL014]={122,121,122,121,122,121,122}; //___________________12_
static const int tL015[nL015]={121,122,111,112,111,112,111};
static const int tL016[nL016]={112,111,112,111,112,111,112};
static const int tL017[nL017]={111,112,111,112,111,112,111}; // (6)
static const int tL018[nL018]={112,111,112,111,114,111,112};
static const int tL019[nL019]={111,112,111,112,111,112,111};
static const int tL020[nL020]={112,111,112,111,112,111,112,111};
static const int tL021[nL021]={111,112,111,112,111,112,111,112}; // (5)
static const int tL022[nL022]={112,111,112,111,112,111,112,111}; //_______________11_
static const int tL023[nL023]={101,102,101,102,101,102,101,102};
static const int tL024[nL024]={102,101,102,101,102,101,102,101};
static const int tL025[nL025]={101,102,101,102,101,102,101,102,101};
static const int tL026[nL026]={102,101,102,101,104,101,102,101,102};
static const int tL027[nL027]={101,102,101,102,101,102,101,102,101}; // (6)
static const int tL028[nL028]={102,101,102,101,102,101,102,101,102};
static const int tL029[nL029]={101,102,101,102,101,102,101,102,101};
static const int tL030[nL030]={102,101,102,101,102,101,102,101,102};
static const int tL031[nL031]={101,102,101,102,101,102,101,102,101,102}; //_______10_
static const int tL032[nL032]={102,101,102, 91, 92, 91, 92, 91, 92, 91};
static const int tL033[nL033]={ 91, 92, 91, 92, 91, 92, 91, 92, 91, 92}; // (6)
static const int tL034[nL034]={ 92, 91, 92, 91, 92, 91, 92, 91, 92, 91};
static const int tL035[nL035]={ 91, 92, 91, 92, 91, 92, 91, 92, 91, 92};
static const int tL036[nL036]={ 92, 91, 92, 91, 94, 91, 92, 91, 92, 91};
static const int tL037[nL037]={ 91, 92, 91, 92, 91, 92, 91, 92, 91, 92, 91};
static const int tL038[nL038]={ 92, 91, 92, 91, 92, 91, 92, 91, 92, 91, 92};
static const int tL039[nL039]={ 91, 92, 91, 92, 91, 92, 91, 92, 91, 92, 91}; // (5)
static const int tL040[nL040]={ 92, 91, 92, 91, 92, 91, 92, 91, 92, 91, 92};
static const int tL041[nL041]={ 91, 92, 91, 92, 91, 92, 91, 92, 91, 92, 91};
static const int tL042[nL042]={ 92, 91, 92, 91, 92, 91, 92, 91, 92, 91, 92, 91};//_9_
static const int tL043[nL043]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82};
static const int tL044[nL044]={ 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81};
static const int tL045[nL045]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82};//(6)
static const int tL046[nL046]={ 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81};
static const int tL047[nL047]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82};
static const int tL048[nL048]={ 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82};
static const int tL049[nL049]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81};
static const int tL050[nL050]={ 82, 81, 82, 81, 82, 81, 82, 81, 84, 81, 82, 81, 82};//(6)
static const int tL051[nL051]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81};
static const int tL052[nL052]={ 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82};
static const int tL053[nL053]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81};
static const int tL054[nL054]={ 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81};
static const int tL055[nL055]={ 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82, 81, 82};
// ________________________________________________________________________________8_ (5)
static const int tL056[nL056]={ 82, 81, 82, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71};
static const int tL057[nL057]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72};
static const int tL058[nL058]={ 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71};
static const int tL059[nL059]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72,
71};
static const int tL060[nL060]={ 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71,
72};
static const int tL061[nL061]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72,
71}; // (6)
static const int tL062[nL062]={ 72, 71, 72, 71, 72, 71, 72, 71, 74, 71, 72, 71, 72, 71,
71};
static const int tL063[nL063]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72,
71};
static const int tL064[nL064]={ 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71,
72};
static const int tL065[nL065]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72,
71, 72};
static const int tL066[nL066]={ 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71,
72, 71}; // (6)
static const int tL067[nL067]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72,
71, 72};
static const int tL068[nL068]={ 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71,
72, 71};
static const int tL069[nL069]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72,
71, 72};
static const int tL070[nL070]={ 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 71,
72, 71};
static const int tL071[nL071]={ 71, 72, 71, 72, 71, 72, 71, 72, 71, 72, 61, 62, 61, 62,
61, 62, 61}; // _____________________________________7_
static const int tL072[nL072]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61,
62, 61, 62};
static const int tL073[nL073]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62,
61, 62, 61}; // (5)
static const int tL074[nL074]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61,
62, 61, 62};
static const int tL075[nL075]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62,
61, 62, 61};
static const int tL076[nL076]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61,
62, 61, 62, 61};
static const int tL077[nL077]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62,
61, 62, 61, 62};
static const int tL078[nL078]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61,
62, 61, 62, 61}; // (6)
static const int tL079[nL079]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62,
61, 62, 61, 62};
static const int tL080[nL080]={ 62, 61, 62, 61, 62, 61, 62, 61, 64, 61, 62, 61, 62, 61,
62, 61, 62, 61};
static const int tL081[nL081]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62,
61, 62, 61, 62};
static const int tL082[nL082]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61,
62, 61, 62, 61, 62};
static const int tL083[nL083]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62,
61, 62, 61, 62, 61}; // (6)
static const int tL084[nL084]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61,
62, 61, 62, 61, 62};
static const int tL085[nL085]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62,
61, 62, 61, 62, 61};
static const int tL086[nL086]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61,
62, 61, 62, 61, 62};
static const int tL087[nL087]={ 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62,
61, 62, 61, 62, 61};
static const int tL088[nL088]={ 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61, 62, 61,
62, 61, 52, 51, 52, 51}; // _________________________6_
//-------------------------------------------------------------------------------------
static const int tL089[nL089]={ 61, 62, 61, 62, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52,
51, 52, 51, 52, 51, 52}; // (5)
static const int tL090[nL090]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51,
52, 51, 52, 51, 52, 51};
static const int tL091[nL091]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52,
51, 52, 51, 52, 51, 52};
static const int tL092[nL092]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51,
52, 51, 52, 51, 52, 51};
static const int tL093[nL093]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52,
51, 52, 51, 52, 51, 52, 51};
static const int tL094[nL094]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51,
52, 51, 52, 51, 52, 51, 52};
static const int tL095[nL095]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52,
51, 52, 51, 52, 51, 52, 51}; // (6)
static const int tL096[nL096]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51,
52, 51, 52, 51, 52, 51, 52};
static const int tL097[nL097]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52,
51, 52, 51, 52, 51, 52, 51};
static const int tL098[nL098]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51,
52, 51, 52, 51, 52, 51, 52};
static const int tL099[nL099]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52,
51, 52, 51, 52, 51, 52, 51, 52};
static const int tL100[nL100]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 53, 52, 51,
52, 51, 52, 51, 52, 51, 52, 51}; // (6)
static const int tL101[nL101]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52,
51, 52, 51, 52, 51, 52, 51, 52};
static const int tL102[nL102]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51,
52, 51, 52, 51, 52, 51, 52, 51};
static const int tL103[nL103]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52,
51, 52, 51, 52, 51, 52, 51, 52};
static const int tL104[nL104]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51,
52, 51, 52, 51, 52, 51, 52, 51};
static const int tL105[nL105]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52,
51, 52, 51, 52, 51, 52, 51, 52, 51};
static const int tL106[nL106]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51,
52, 51, 52, 51, 52, 51, 52, 51, 52};
static const int tL107[nL107]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52,
51, 52, 51, 52, 51, 52, 51, 52, 51}; // (5)
static const int tL108[nL108]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51,
52, 51, 52, 51, 52, 51, 52, 51, 52};
static const int tL109[nL109]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52,
51, 52, 51, 52, 51, 52, 51, 52, 51};
static const int tL110[nL110]={ 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51,
52, 51, 52, 51, 52, 51, 52, 51, 52, 51};
static const int tL111[nL111]={ 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52, 51, 52,
51, 52, 51, 42, 41, 42, 41, 42, 41, 42}; // _________4_
static const int tL112[nL112]={ 52, 51, 52, 51, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41,
42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; // (6)
static const int tL113[nL113]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42,
41, 42, 41, 42, 41, 42, 41, 42, 41, 42};
static const int tL114[nL114]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41,
42, 41, 42, 41, 42, 41, 42, 41, 42, 41};
static const int tL115[nL115]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42,
41, 42, 41, 42, 41, 42, 41, 42, 41, 42};
static const int tL116[nL116]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41,
42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42};
static const int tL117[nL117]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42,
41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41};
static const int tL118[nL118]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41,
42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42};
static const int tL119[nL119]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42,
41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41}; // (6)
static const int tL120[nL120]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41,
42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42};
static const int tL121[nL121]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42,
41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41};
static const int tL122[nL122]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41,
42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41};
static const int tL123[nL123]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42,
41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42};
static const int tL124[nL124]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 43, 42, 41,
42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41};// (5)
static const int tL125[nL125]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42,
41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42};
static const int tL126[nL126]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41,
42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41};
static const int tL127[nL127]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42,
41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41};
static const int tL128[nL128]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41,
42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42};
static const int tL129[nL129]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42,
41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41};
static const int tL130[nL130]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41,
42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42};//(6)
static const int tL131[nL131]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42,
41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41};
static const int tL132[nL132]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41,
42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42};
static const int tL133[nL133]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42,
41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42};
static const int tL134[nL134]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41,
42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41};
static const int tL135[nL135]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42,
41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42};
static const int tL136[nL136]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41,
42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41};
static const int tL137[nL137]={ 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42,
41, 42, 41, 42, 41, 42, 41, 42, 31, 32, 31, 32, 31, 32};
// ____________________________________________________________________________(6)___3_
static const int tL138[nL138]={ 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 42, 41, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31};
static const int tL139[nL139]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31};
static const int tL140[nL140]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32};
static const int tL141[nL141]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31}; // (5)
static const int tL142[nL142]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32};
static const int tL143[nL143]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31};
static const int tL144[nL144]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31};
static const int tL145[nL145]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32};
static const int tL146[nL146]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 33, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31};
static const int tL147[nL147]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32}; // (6)
static const int tL148[nL148]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31};
static const int tL149[nL149]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32};
static const int tL150[nL150]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32};
static const int tL151[nL151]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31};
static const int tL152[nL152]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32}; // (6)
static const int tL153[nL153]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31};
static const int tL154[nL154]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32};
static const int tL155[nL155]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31};
static const int tL156[nL156]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31};
static const int tL157[nL157]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32};
static const int tL158[nL158]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31}; // (5)
static const int tL159[nL159]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32};
static const int tL160[nL160]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 33, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31};
static const int tL161[nL161]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31};
static const int tL162[nL162]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32};
static const int tL163[nL163]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31}; // (6)
static const int tL164[nL164]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32};
static const int tL165[nL165]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31};
static const int tL166[nL166]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32};
static const int tL167[nL167]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 31, 32};
static const int tL168[nL168]={ 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31,
32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 21,
22, 21, 22, 21, 22, 21}; // _________________________2_
static const int tL169[nL169]={ 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32, 31, 32,
31, 32, 31, 32, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22}; // (6)
static const int tL170[nL170]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21};
static const int tL171[nL171]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22};
static const int tL172[nL172]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21};
static const int tL173[nL173]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21};
static const int tL174[nL174]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22};
static const int tL175[nL175]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21}; // (5)
static const int tL176[nL176]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22};
static const int tL177[nL177]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21};
static const int tL178[nL178]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 23, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21};
static const int tL179[nL179]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22};
static const int tL180[nL180]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21}; // (6)
static const int tL181[nL181]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22};
static const int tL182[nL182]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21};
static const int tL183[nL183]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22};
static const int tL184[nL184]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22};
static const int tL185[nL185]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21};
static const int tL186[nL186]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22};
static const int tL187[nL187]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21}; // (6)
static const int tL188[nL188]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22};
static const int tL189[nL189]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21};
static const int tL190[nL190]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21};
static const int tL191[nL191]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22};
static const int tL192[nL192]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; // (5)
static const int tL193[nL193]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22};
static const int tL194[nL194]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21};
static const int tL195[nL195]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21};
static const int tL196[nL196]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 23, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22};
static const int tL197[nL197]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21}; // (6)
static const int tL198[nL198]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22};
static const int tL199[nL199]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21};
static const int tL200[nL200]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22};
static const int tL201[nL201]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22};
static const int tL202[nL202]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21};
static const int tL203[nL203]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22}; //(6)
static const int tL204[nL204]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21};
static const int tL205[nL205]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22,
21, 22, 21, 22, 11, 12, 11, 12, 11, 12, 11, 12};
static const int tL206[nL206]={ 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21,
22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11};//__1_
static const int tL207[nL207]={ 21, 22, 21, 22, 21, 22, 21, 22, 21, 22, 21, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11};
static const int tL208[nL208]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12};
static const int tL209[nL209]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11};//(5)
static const int tL210[nL210]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12};
static const int tL211[nL211]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11};
static const int tL212[nL212]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 13, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11};
static const int tL213[nL213]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12};
static const int tL214[nL214]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11};
static const int tL215[nL215]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12};
static const int tL216[nL216]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11};
static const int tL217[nL217]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12};
static const int tL218[nL218]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12};
static const int tL219[nL219]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11};
static const int tL220[nL220]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12};
static const int tL221[nL221]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11}; // (6)
static const int tL222[nL222]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12};
static const int tL223[nL223]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11};
static const int tL224[nL224]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11};
static const int tL225[nL225]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12};
static const int tL226[nL226]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 13, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11}; // (5)
static const int tL227[nL227]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12};
static const int tL228[nL228]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11};
static const int tL229[nL229]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11};
static const int tL230[nL230]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12};
static const int tL231[nL231]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 0, 0, 0,
0, 0, 0}; // (5+1=6)
static const int tL232[nL232]={ 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11,
12, 11, 12, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0};
static const int tL233[nL233]={ 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12, 11, 12,
11, 12, 11, 12, 11, 12, 11, 12, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0};
static const int nSL[nLay]={
nL001, nL002, nL003, nL004, nL005, nL006, nL007, nL008, nL009 ,nL010,
nL011, nL012, nL013, nL014, nL015, nL016, nL017, nL018, nL019 ,nL020,
nL021, nL022, nL023, nL024, nL025, nL026, nL027, nL028, nL029 ,nL030,
nL031, nL032, nL033, nL034, nL035, nL036, nL037, nL038, nL039 ,nL040,
nL041, nL042, nL043, nL044, nL045, nL046, nL047, nL048, nL049 ,nL050,
nL051, nL052, nL053, nL054, nL055, nL056, nL057, nL058, nL059 ,nL060,
nL061, nL062, nL063, nL064, nL065, nL066, nL067, nL068, nL069 ,nL070,
nL071, nL072, nL073, nL074, nL075, nL076, nL077, nL078, nL079 ,nL080,
nL081, nL082, nL083, nL084, nL085, nL086, nL087, nL088, nL089 ,nL090,
nL091, nL092, nL093, nL094, nL095, nL096, nL097, nL098, nL099 ,nL100,
nL101, nL102, nL103, nL104, nL105, nL106, nL107, nL108, nL109 ,nL110,
nL111, nL112, nL113, nL114, nL115, nL116, nL117, nL118, nL119 ,nL120,
nL121, nL122, nL123, nL124, nL125, nL126, nL127, nL128, nL129 ,nL130,
nL131, nL132, nL133, nL134, nL135, nL136, nL137, nL138, nL139 ,nL140,
nL141, nL142, nL143, nL144, nL145, nL146, nL147, nL148, nL149 ,nL150,
nL151, nL152, nL153, nL154, nL155, nL156, nL157, nL158, nL159 ,nL160,
nL161, nL162, nL163, nL164, nL165, nL166, nL167, nL168, nL169 ,nL170,
nL171, nL172, nL173, nL174, nL175, nL176, nL177, nL178, nL179 ,nL180,
nL181, nL182, nL183, nL184, nL185, nL186, nL187, nL188, nL189 ,nL190,
nL191, nL192, nL193, nL194, nL195, nL196, nL197, nL198, nL199 ,nL200,
nL201, nL202, nL203, nL204, nL205, nL206, nL207, nL208, nL209 ,nL210,
nL211, nL212, nL213, nL214, nL215, nL216, nL217, nL218, nL219 ,nL220,
nL221, nL222, nL223, nL224, nL225, nL226, nL227, nL228, nL229 ,nL230,
nL231, nL232, nL233};
static const int * const nLT[nLay]={
tL001, tL002, tL003, tL004, tL005, tL006, tL007, tL008, tL009 ,tL010,
tL011, tL012, tL013, tL014, tL015, tL016, tL017, tL018, tL019 ,tL020,
tL021, tL022, tL023, tL024, tL025, tL026, tL027, tL028, tL029 ,tL030,
tL031, tL032, tL033, tL034, tL035, tL036, tL037, tL038, tL039 ,tL040,
tL041, tL042, tL043, tL044, tL045, tL046, tL047, tL048, tL049 ,tL050,
tL051, tL052, tL053, tL054, tL055, tL056, tL057, tL058, tL059 ,tL060,
tL061, tL062, tL063, tL064, tL065, tL066, tL067, tL068, tL069 ,tL070,
tL071, tL072, tL073, tL074, tL075, tL076, tL077, tL078, tL079 ,tL080,
tL081, tL082, tL083, tL084, tL085, tL086, tL087, tL088, tL089 ,tL090,
tL091, tL092, tL093, tL094, tL095, tL096, tL097, tL098, tL099 ,tL100,
tL101, tL102, tL103, tL104, tL105, tL106, tL107, tL108, tL109 ,tL110,
tL111, tL112, tL113, tL114, tL115, tL116, tL117, tL118, tL119 ,tL120,
tL121, tL122, tL123, tL124, tL125, tL126, tL127, tL128, tL129 ,tL130,
tL131, tL132, tL133, tL134, tL135, tL136, tL137, tL138, tL139 ,tL140,
tL141, tL142, tL143, tL144, tL145, tL146, tL147, tL148, tL149 ,tL150,
tL151, tL152, tL153, tL154, tL155, tL156, tL157, tL158, tL159 ,tL160,
tL161, tL162, tL163, tL164, tL165, tL166, tL167, tL168, tL169 ,tL170,
tL171, tL172, tL173, tL174, tL175, tL176, tL177, tL178, tL179 ,tL180,
tL181, tL182, tL183, tL184, tL185, tL186, tL187, tL188, tL189 ,tL190,
tL191, tL192, tL193, tL194, tL195, tL196, tL197, tL198, tL199 ,tL200,
tL201, tL202, tL203, tL204, tL205, tL206, tL207, tL208, tL209 ,tL210,
tL211, tL212, tL213, tL214, tL215, tL216, tL217, tL218, tL219 ,tL220,
tL221, tL222, tL223, tL224, tL225, tL226, tL227, tL228, tL229 ,tL230,
tL231, tL232, tL233};
static const int * const nRT[nLay]={
tR001, tR002, tR003, tR004, tR005, tR006, tR007, tR008, tR009 ,tR010,
tR011, tR012, tR013, tR014, tR015, tR016, tR017, tR018, tR019 ,tR020,
tR021, tR022, tR023, tR024, tR025, tR026, tR027, tR028, tR029 ,tR030,
tR031, tR032, tR033, tR034, tR035, tR036, tR037, tR038, tR039 ,tR040,
tR041, tR042, tR043, tR044, tR045, tR046, tR047, tR048, tR049 ,tR050,
tR051, tR052, tR053, tR054, tR055, tR056, tR057, tR058, tR059 ,tR060,
tR061, tR062, tR063, tR064, tR065, tR066, tR067, tR068, tR069 ,tR070,
tR071, tR072, tR073, tR074, tR075, tR076, tR077, tR078, tR079 ,tR080,
tR081, tR082, tR083, tR084, tR085, tR086, tR087, tR088, tR089 ,tR090,
tR091, tR092, tR093, tR094, tR095, tR096, tR097, tR098, tR099 ,tR100,
tR101, tR102, tR103, tR104, tR105, tR106, tR107, tR108, tR109 ,tR110,
tR111, tR112, tR113, tR114, tR115, tR116, tR117, tR118, tR119 ,tR120,
tR121, tR122, tR123, tR124, tR125, tR126, tR127, tR128, tR129 ,tR130,
tR131, tR132, tR133, tR134, tR135, tR136, tR137, tR138, tR139 ,tR140,
tR141, tR142, tR143, tR144, tR145, tR146, tR147, tR148, tR149 ,tR150,
tR151, tR152, tR153, tR154, tR155, tR156, tR157, tR158, tR159 ,tR160,
tR161, tR162, tR163, tR164, tR165, tR166, tR167, tR168, tR169 ,tR170,
tR171, tR172, tR173, tR174, tR175, tR176, tR177, tR178, tR179 ,tR180,
tR181, tR182, tR183, tR184, tR185, tR186, tR187, tR188, tR189 ,tR190,
tR191, tR192, tR193, tR194, tR195, tR196, tR197, tR198, tR199 ,tR200,
tR201, tR202, tR203, tR204, tR205, tR206, tR207, tR208, tR209 ,tR210,
tR211, tR212, tR213, tR214, tR215, tR216, tR217, tR218, tR219 ,tR220,
tR221, tR222, tR223, tR224, tR225, tR226, tR227, tR228, tR229 ,tR230,
tR231, tR232, tR233};
/*
// The following are differences in the Source tube positions(not used so far)
// *** At present for all widgets the F01 is used (@@ to be developed M.K.)
static const int nS=31; // a # of the source tubes in the widget
// 0 - H(Long), 1 - E(Short)
// 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2
// 1 1 2 2 3 3 4 5 6 7 8 9 0 1 2 2 3 4 4 5 5 6 6 7 8 9 0 1 2 3 4
// A B A B A B A B A B A B A B
static const int F01[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F02[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F03[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,0,1,1,1,0,0,0};
static const int F04[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F05[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F06[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F07[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F08[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F09[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F10[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F11[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F12[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F13[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F14[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F15[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int F16[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static const int F17[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static const int F18[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0};
static const int B01[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static const int B02[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0};
static const int B03[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0};
static const int B04[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0};
static const int B05[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static const int B06[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0};
static const int B07[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0};
static const int B08[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0};
static const int B09[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static const int B10[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static const int B11[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0};
static const int B12[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0};
static const int B13[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static const int B14[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0};
static const int B15[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static const int B16[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static const int B17[nS]={0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
static const int B18[nS]={0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0};
*/
static const double cellSize = 0.5*CLHEP::cm; // 0.5 cm is the cell size
if (!(xl > 0.))
xl=-xl;
double fx=xl/cellSize;
int ny=static_cast<int>((yl-yMin)/cellSize); // Layer number (starting from 0)
if (ny < 0 || ny >= nLay) // Sould never happen as was checked beforehand
{
#ifdef DebugLog
edm::LogInfo("HFShower") << "-Warning-HFFibreFiducial::PMTNumber: "
<< "check limits y = " << yl << ", nL=" << nLay;
#endif
return 0;
}
int nx=static_cast<int>(fx); // Cell number (starting from 0)
#ifdef DebugLog
double phis=atan2(xl, yl)/CLHEP::deg;
double zv = pe_effect.z(); // Z in global system
edm::LogInfo("HFShower") << "HFFibreFiducial::PMTNumber:X = " << xv
<< ", Y = " << yv << ", Z = " << zv << ", fX = "
<< fx << "-> nX = " << nx << ", nY = " << ny
<< ", mX = " << nSL[ny] << ", x = " << xl << ", y = "
<< yl << ", s = " << cellSize << ", nW = "
<< nwid << ", phi = " << phi/CLHEP::deg
<< ", phis = " << phis << ", phir = "
<< phir/CLHEP::deg;
#endif
if (nx >= nSL[ny])
{
#ifdef DebugLog
edm::LogInfo("HFShower") << "HFFibreFiducial::nx/ny (" << nx
<< "," << ny <<") " << " above limit " << nSL[ny];
#endif
return 0; // ===> out of the acceptance
}
int code=0; // a prototype
if (left) code=nLT[ny][nx];
else code=nRT[ny][nx];
int flag= code%10;
int npmt= code/10;
bool src= false; // by default: not a source-tube
#ifdef DebugLog
edm::LogInfo("HFShower") << "HFFibreFiducial::nx/ny (" << nx << ","
<< ny << ") code/flag/npmt " << code << "/" << flag
<< "/" << npmt;
#endif
if (!flag) return 0; // ===> no fiber in the cell
else if (flag==1) npmt += 24;
else if (flag==3 || flag==4) {
src=true;
}
#ifdef DebugLog
edm::LogInfo("HFShower") << "HFFibreFiducial::PMTNumber: src = " << src
<< ", npmt =" << npmt;
#endif
if (src) return -npmt; // return the negative number for the source
return npmt;
} // End of PMTNumber
| 67.81064 | 91 | 0.515695 | nistefan |
db03db9c6f2d304382cc2bffa20cb53179e96c65 | 265 | cpp | C++ | Chapter 06/q03.cpp | altugbakan/accelerated-cpp-solutions | 0087c12cf853c143a301c44eeedd041a0dc7ecfc | [
"MIT"
] | 4 | 2021-10-29T18:45:48.000Z | 2022-02-08T16:12:45.000Z | Chapter 06/q03.cpp | altugbakan/accelerated-cpp-solutions | 0087c12cf853c143a301c44eeedd041a0dc7ecfc | [
"MIT"
] | null | null | null | Chapter 06/q03.cpp | altugbakan/accelerated-cpp-solutions | 0087c12cf853c143a301c44eeedd041a0dc7ecfc | [
"MIT"
] | 1 | 2021-12-21T21:46:49.000Z | 2021-12-21T21:46:49.000Z | #include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::endl;
int main()
{
vector<int> u(10, 100);
vector<int> v;
// the code throws an error if we use v.begin()
// copy(u.begin(), u.end(), v.begin());
return 0;
} | 16.5625 | 51 | 0.596226 | altugbakan |
db04a7e1932d0b8918ed32457086bac25c9720d9 | 4,842 | cpp | C++ | src/CryptoLib/crypto_ecdsa.cpp | naishai/private-transaction-families | da2bf22650e6cab43c53c9b34a8a78bc0b432394 | [
"Apache-2.0"
] | 13 | 2019-01-30T17:51:19.000Z | 2021-03-12T02:32:41.000Z | src/CryptoLib/crypto_ecdsa.cpp | naishai/private-transaction-families | da2bf22650e6cab43c53c9b34a8a78bc0b432394 | [
"Apache-2.0"
] | 7 | 2019-06-12T06:34:40.000Z | 2019-09-24T19:11:26.000Z | src/CryptoLib/crypto_ecdsa.cpp | naishai/private-transaction-families | da2bf22650e6cab43c53c9b34a8a78bc0b432394 | [
"Apache-2.0"
] | 8 | 2019-01-29T17:01:11.000Z | 2022-03-20T07:32:04.000Z | /*
* Copyright 2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "crypto.h"
#ifdef SGX_ENCLAVE
#include "enclave_log.h"
#else
#include "app_log.h"
#endif
#include <string.h>
bool ecdsa_sign(const uint8_t* data, size_t data_size, EC_KEY* ec_key, ecdsa_bin_signature_t* out_sig)
{
sha256_data_t digest = {0};
const BIGNUM *bn_r = NULL;
const BIGNUM *bn_s = NULL;
ECDSA_SIG *ecdsa_sig = NULL;
bool retval = false;
int bn_r_size = 0;
int bn_s_size = 0;
if (data == NULL || data_size == 0 || ec_key == NULL || out_sig == NULL)
{
PRINT(ERROR, CRYPTO, "wrong input parameters\n");
return false;
}
if (data_size > MAX_CRYPTO_BUFFER_SIZE)
{
PRINT(ERROR, CRYPTO, "buffer size is too big\n");
return false;
}
do {
if (SHA256(data, data_size, digest) == NULL)
{
PRINT(ERROR, CRYPTO, "SHA256 failed\n");
break;;
}
//PRINT(INFO, CRYPTO, "ecdsa_sign SHA256 diget:\n");
//print_byte_array(digest, SHA256_DIGEST_LENGTH);
ecdsa_sig = ECDSA_do_sign(digest, sizeof(sha256_data_t), ec_key);
if (ecdsa_sig == NULL)
{
PRINT(ERROR, CRYPTO, "ECDSA_do_sign failed\n");
break;
}
ECDSA_SIG_get0(ecdsa_sig, &bn_r, &bn_s);
if (bn_r == NULL || bn_s == NULL)
{
PRINT(ERROR, CRYPTO, "ECDSA_SIG_get0 failed\n");
break;
}
bn_r_size = BN_num_bytes(bn_r);
if (bn_r_size > ECDSA_BIN_ELEMENT_SIZE)
{
PRINT(ERROR, CRYPTO, "bn_r number is too long, %d bytes instead of %d\n", bn_r_size, ECDSA_BIN_ELEMENT_SIZE);
break;
}
bn_s_size = BN_num_bytes(bn_s);
if (bn_s_size > ECDSA_BIN_ELEMENT_SIZE)
{
PRINT(ERROR, CRYPTO, "bn_s number is too long, %d bytes instead of %d\n", bn_s_size, ECDSA_BIN_ELEMENT_SIZE);
break;
}
memset_s(out_sig, sizeof(ecdsa_bin_signature_t), 0, sizeof(ecdsa_bin_signature_t));
// if the size is 32 bytes, it will start at offset 0, 31 will start in offset 1 (leaving the first byte as 0) etc.
if (BN_bn2bin(bn_r, &out_sig->r[ECDSA_BIN_ELEMENT_SIZE - bn_r_size]) != bn_r_size)
{
PRINT(ERROR, CRYPTO, "BN_bn2bin failed\n");
break;
}
if (BN_bn2bin(bn_s, &out_sig->s[ECDSA_BIN_ELEMENT_SIZE - bn_s_size]) != bn_s_size)
{
PRINT(ERROR, CRYPTO, "BN_bn2bin failed\n");
break;
}
retval = true;
} while(0);
if (ecdsa_sig != NULL)
ECDSA_SIG_free(ecdsa_sig);
return retval;
}
bool ecdsa_verify(const uint8_t* data, size_t data_size, EC_KEY* ec_key, const ecdsa_bin_signature_t* in_sig)
{
sha256_data_t digest = {0};
BIGNUM *bn_r = NULL;
BIGNUM *bn_s = NULL;
ECDSA_SIG *ecdsa_sig = NULL;
bool retval = false;
int ret = 0;
if (data == NULL || data_size == 0 || ec_key == NULL || in_sig == NULL)
{
PRINT(ERROR, CRYPTO, "wrong input parameters\n");
return false;
}
if (data_size > MAX_CRYPTO_BUFFER_SIZE)
{
PRINT(ERROR, CRYPTO, "buffer size is too big\n");
return false;
}
do {
if (SHA256(data, data_size, digest) == NULL)
{
PRINT(ERROR, CRYPTO, "SHA256 failed\n");
break;
}
bn_r = BN_bin2bn(in_sig->r, sizeof(ecdsa_bin_element_t), NULL);
if (bn_r == NULL)
{
PRINT(ERROR, CRYPTO, "BN_bin2bn failed\n");
break;
}
bn_s = BN_bin2bn(in_sig->s, sizeof(ecdsa_bin_element_t), NULL);
if (bn_s == NULL)
{
PRINT(ERROR, CRYPTO, "BN_bin2bn failed\n");
break;
}
if (BN_is_zero(bn_r) == 1 || BN_is_zero(bn_s) == 1)
{
PRINT(ERROR, CRYPTO, "signature is empty, data is not signed!\n");
break;
}
ecdsa_sig = ECDSA_SIG_new();
if (ecdsa_sig == NULL)
{
PRINT(ERROR, CRYPTO, "ECDSA_SIG_new failed\n");
break;
}
// sets r and s values of ecdsa_sig
// calling this function transfers the memory management of the values to the ECDSA_SIG object,
// and therefore the values that have been passed in should not be freed directly after this function has been called
if (ECDSA_SIG_set0(ecdsa_sig, bn_r, bn_s) != 1)
{
PRINT(ERROR, CRYPTO, "ECDSA_SIG_set0 failed\n");
break;
}
bn_r = NULL;
bn_s = NULL;
ret = ECDSA_do_verify(digest, sizeof(sha256_data_t), ecdsa_sig, ec_key);
if (ret != 1)
{
PRINT_CRYPTO_ERROR("ECDSA_do_verify");
break;
}
retval = true;
} while (0);
if (ecdsa_sig != NULL)
ECDSA_SIG_free(ecdsa_sig);
if (bn_r != NULL)
BN_clear_free(bn_r);
if (bn_s != NULL)
BN_clear_free(bn_s);
return retval;
}
| 23.852217 | 119 | 0.670797 | naishai |
db08c8d218498229f857a7f3938612e2bc73053f | 1,008 | cpp | C++ | ProjectEuler/euler001.cpp | HannoFlohr/hackerrank | 9644c78ce05a6b1bc5d8f542966781d53e5366e3 | [
"MIT"
] | null | null | null | ProjectEuler/euler001.cpp | HannoFlohr/hackerrank | 9644c78ce05a6b1bc5d8f542966781d53e5366e3 | [
"MIT"
] | null | null | null | ProjectEuler/euler001.cpp | HannoFlohr/hackerrank | 9644c78ce05a6b1bc5d8f542966781d53e5366e3 | [
"MIT"
] | null | null | null | #include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main(){
int t;
cin >> t;
for(int a0 = 0; a0 < t; a0++){
int n;
cin >> n;
n--;
unsigned long int sumThrees = n/3, sumFives = n/5, sumFifteens = n/15;
sumThrees = 3 * sumThrees * (sumThrees + 1) >> 1;
sumFives = 5 * sumFives * (sumFives + 1) >> 1;
sumFifteens = 15 * sumFifteens * (sumFifteens + 1) >> 1;
unsigned long int sum = sumThrees + sumFives - sumFifteens;
cout << sum << endl;
}
return 0;
}
//https://www.hackerrank.com/contests/projecteuler/challenges/euler001 | 21.913043 | 78 | 0.608135 | HannoFlohr |
db0ac9ea061a61622c3a25112e13c796699f3bc1 | 3,127 | cpp | C++ | src/native/QmlNet/QmlNet/types/NetSignalInfo.cpp | joachim-egger/Qml.Net | 53525c0ba0f135a6b16f47b09ad62b349d54e844 | [
"MIT"
] | null | null | null | src/native/QmlNet/QmlNet/types/NetSignalInfo.cpp | joachim-egger/Qml.Net | 53525c0ba0f135a6b16f47b09ad62b349d54e844 | [
"MIT"
] | null | null | null | src/native/QmlNet/QmlNet/types/NetSignalInfo.cpp | joachim-egger/Qml.Net | 53525c0ba0f135a6b16f47b09ad62b349d54e844 | [
"MIT"
] | null | null | null | #include <QmlNet/types/NetSignalInfo.h>
#include <QmlNet/qml/NetValueMetaObjectPacker.h>
#include <QmlNetUtilities.h>
NetSignalInfo::NetSignalInfo(QSharedPointer<NetTypeInfo> parentType, QString name) :
_parentType(parentType),
_name(name)
{
}
QSharedPointer<NetTypeInfo> NetSignalInfo::getParentType()
{
return _parentType;
}
QString NetSignalInfo::getName()
{
return _name;
}
void NetSignalInfo::addParameter(NetVariantTypeEnum type)
{
if(type == NetVariantTypeEnum_Invalid) return;
_parameters.append(type);
}
int NetSignalInfo::getParameterCount()
{
return _parameters.size();
}
NetVariantTypeEnum NetSignalInfo::getParameter(int index)
{
if(index < 0) return NetVariantTypeEnum_Invalid;
if(index >= _parameters.length()) return NetVariantTypeEnum_Invalid;
return _parameters.at(index);
}
QString NetSignalInfo::getSignature()
{
QString signature = _name;
signature.append("(");
for(int parameterIndex = 0; parameterIndex <= _parameters.size() - 1; parameterIndex++)
{
if(parameterIndex > 0) {
signature.append(",");
}
signature.append(NetMetaValueQmlType(_parameters.at(parameterIndex)));
}
signature.append(")");
return signature;
}
QString NetSignalInfo::getSlotSignature()
{
QString signature = _name;
signature.append("_internal_slot_for_net_del(");
if(_parameters.size() > 0) {
for(int parameterIndex = 0; parameterIndex <= _parameters.size() - 1; parameterIndex++)
{
if(parameterIndex > 0) {
signature.append(",");
}
signature.append(NetMetaValueQmlType(_parameters.at(parameterIndex)));
}
}
signature.append(")");
return signature;
}
extern "C" {
Q_DECL_EXPORT NetSignalInfoContainer* signal_info_create(NetTypeInfoContainer* parentTypeContainer, LPWSTR name)
{
NetSignalInfoContainer* result = new NetSignalInfoContainer();
NetSignalInfo* instance = new NetSignalInfo(parentTypeContainer->netTypeInfo, QString::fromUtf16((const char16_t*)name));
result->signal = QSharedPointer<NetSignalInfo>(instance);
return result;
}
Q_DECL_EXPORT void signal_info_destroy(NetSignalInfoContainer* container)
{
delete container;
}
Q_DECL_EXPORT NetTypeInfoContainer* signal_info_getParentType(NetSignalInfoContainer* container)
{
NetTypeInfoContainer* result = new NetTypeInfoContainer{container->signal->getParentType()};
return result;
}
Q_DECL_EXPORT QmlNetStringContainer* signal_info_getName(NetSignalInfoContainer* container)
{
QString result = container->signal->getName();
return createString(result);
}
Q_DECL_EXPORT void signal_info_addParameter(NetSignalInfoContainer* container, NetVariantTypeEnum type)
{
container->signal->addParameter(type);
}
Q_DECL_EXPORT int signal_info_getParameterCount(NetSignalInfoContainer* container)
{
return container->signal->getParameterCount();
}
Q_DECL_EXPORT NetVariantTypeEnum signal_info_getParameter(NetSignalInfoContainer* container, int index)
{
return container->signal->getParameter(index);
}
}
| 25.422764 | 125 | 0.73361 | joachim-egger |
db0b7504b4cbcbf4d7a6997394e18f046d15bb9e | 2,936 | cpp | C++ | src/Metrics/Brier.cpp | dsiuta/Comps | 2071279280d33946e975de25deedc60f1881eda0 | [
"BSD-3-Clause"
] | null | null | null | src/Metrics/Brier.cpp | dsiuta/Comps | 2071279280d33946e975de25deedc60f1881eda0 | [
"BSD-3-Clause"
] | null | null | null | src/Metrics/Brier.cpp | dsiuta/Comps | 2071279280d33946e975de25deedc60f1881eda0 | [
"BSD-3-Clause"
] | null | null | null | #include "Brier.h"
#include "../Variables/Variable.h"
#include "../Distribution.h"
#include "../Obs.h"
#include "../Data.h"
#include <iomanip>
MetricBrier::MetricBrier(const Options& iOptions, const Data& iData) :
Metric(iOptions, iData),
mAnomaly(false),
mAnomalyAbove(false),
mAnomalyBelow(false) {
// Should anomaly threshold be used? I.e. Does the forecast/obs exceed a certain amount
// (threshold) above or below the climatological mean?
iOptions.getValue("anomaly", mAnomaly);
iOptions.getValue("anomalyAbove", mAnomalyAbove);
iOptions.getValue("anomalyBelow", mAnomalyBelow);
iOptions.getRequiredValue("threshold", mThreshold);
if(mAnomalyAbove || mAnomalyBelow) {
if(mAnomaly)
Global::logger->write("MetricBrier: Both 'anomaly' and one of 'anomalyAbove' or 'anomalyBelow' where specified, which is redundant.", Logger::warning);
mAnomaly = true;
}
if(mAnomaly && !mAnomalyBelow && !mAnomalyAbove) {
// If only 'anomaly' was specified
mAnomalyAbove = true;
mAnomalyBelow = true;
}
iOptions.check();
}
float MetricBrier::computeCore(const Obs& iObs, const Distribution::ptr iForecast) const {
float obs = iObs.getValue();
// Part1: Compute probability that obs is beyond threshold
float P = Global::MV;
bool isBeyond; // Is the obs above threshold, or more anomalous than mThreshold?
if(mAnomaly) {
// Find climatological value at day of year corresponding to obs
float clim = mData.getClim(iObs.getDate(), 0, iObs.getOffset(), iObs.getLocation(), iObs.getVariable());
if(!Global::isValid(clim)) {
return Global::MV;
}
// Probability that obs is further away from clim than mThreshold
float lower = clim-mThreshold;
float upper = clim+mThreshold;
// Check if we are within the variables range
const Variable* var = Variable::get(iObs.getVariable());
if(Global::isValid(var->getMin()) && lower < var->getMin())
lower = var->getMin();
if(Global::isValid(var->getMax()) && upper > var->getMax())
lower = var->getMax();
float P0 = 0;
float P1 = 0;
isBeyond = false;
if(mAnomalyBelow) {
P0 = iForecast->getCdf(lower); // Prob that obs is anomalously low
isBeyond = isBeyond || (obs < lower);
}
if(mAnomalyAbove) {
P1 = 1 - iForecast->getCdf(upper); // Prob that obs is anomalously high
isBeyond = isBeyond || (obs > upper);
}
P = P1 + P0;
}
else {
P = iForecast->getCdf(mThreshold);
if(!Global::isValid(P)) {
return Global::MV;
}
P = 1 - P;
isBeyond = (obs > mThreshold);
}
// Part 2: Compute score
float brier = Global::MV;
if(Global::isValid(obs) && Global::isValid(P)) {
if(isBeyond)
brier = (1-P)*(1-P);
else
brier = P*P;
}
return brier;
}
| 34.139535 | 160 | 0.624319 | dsiuta |
db0c799a60603813db7380bbde0e7a9a3b32689c | 138 | hpp | C++ | experimental/brunsc/python_console/convert_simtk_vec3.hpp | lens-biophotonics/v3d_external | 44ff3b60a297a96eaa77ca092e0de9af5c990ed3 | [
"MIT"
] | 39 | 2015-05-10T23:23:03.000Z | 2022-01-26T01:31:30.000Z | experimental/brunsc/python_console/convert_simtk_vec3.hpp | lens-biophotonics/v3d_external | 44ff3b60a297a96eaa77ca092e0de9af5c990ed3 | [
"MIT"
] | 13 | 2016-03-04T05:29:23.000Z | 2021-02-07T01:11:10.000Z | experimental/brunsc/python_console/convert_simtk_vec3.hpp | lens-biophotonics/v3d_external | 44ff3b60a297a96eaa77ca092e0de9af5c990ed3 | [
"MIT"
] | 44 | 2015-11-11T07:30:59.000Z | 2021-12-26T16:41:21.000Z | #ifndef CONVERT_SIMTK_VEC3_HPP
#define CONVERT_SIMTK_VEC3_HPP
void register_simtk_vec3_conversion();
#endif // CONVERT_SIMTK_STRING_HPP
| 19.714286 | 38 | 0.862319 | lens-biophotonics |
db12a04ecd9a9c203ff2d61648123b3a6e821183 | 5,549 | cpp | C++ | src/ai/ScriptedTask.cpp | dhanin/friendly-bassoon | fafcfd3921805baddc1889dc0ee2fa367ad882f8 | [
"BSD-3-Clause"
] | 2 | 2021-11-17T10:59:38.000Z | 2021-11-17T10:59:45.000Z | src/ai/ScriptedTask.cpp | dhanin/nws | 87a3f24a7887d84b9884635064b48d456b4184e2 | [
"BSD-3-Clause"
] | null | null | null | src/ai/ScriptedTask.cpp | dhanin/nws | 87a3f24a7887d84b9884635064b48d456b4184e2 | [
"BSD-3-Clause"
] | null | null | null | /**
** @file ScriptedTask.cpp
*/
/*
** Copyright (c) 2014, GCBLUE PROJECT
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
**
** 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
**
** 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
**
** 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from
** this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
** NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
** COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
** IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "stdwx.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "ai/ScriptedTask.h"
#include "scriptinterface/tcSimPythonInterface.h"
#include "tcGameStream.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
using namespace ai;
using scriptinterface::tcSimPythonInterface;
/**
* Read from stream
*/
tcGameStream& ScriptedTask::operator<<(tcGameStream& stream)
{
Task::operator<<(stream);
stream >> commandString;
{
textMemory.clear();
unsigned int nTextMemory;
stream >> nTextMemory;
for (unsigned int n=0; n<nTextMemory; n++)
{
std::string s1;
std::string s2;
stream >> s1;
stream >> s2;
textMemory[s1] = s2;
}
stream.ReadCheckValue(8961);
}
{
numberMemory.clear();
unsigned int nNumberMemory;
stream >> nNumberMemory;
for (unsigned int n=0; n<nNumberMemory; n++)
{
int val_int;
double val_double;
stream >> val_int;
stream >> val_double;
numberMemory[val_int] = val_double;
}
stream.ReadCheckValue(1530);
}
return stream;
}
/**
* Write to stream
*/
tcGameStream& ScriptedTask::operator>>(tcGameStream& stream)
{
Task::operator>>(stream);
stream << commandString;
{
unsigned int nTextMemory = textMemory.size();
stream << nTextMemory;
for (std::map<std::string, std::string>::iterator iter = textMemory.begin();
iter != textMemory.end(); ++iter)
{
stream << iter->first;
stream << iter->second;
}
stream.WriteCheckValue(8961);
}
{
unsigned int nNumberMemory = numberMemory.size();
stream << nNumberMemory;
for (std::map<int, double>::iterator iter = numberMemory.begin();
iter != numberMemory.end(); ++iter)
{
stream << (int)iter->first;
stream << (double)iter->second;
}
stream.WriteCheckValue(1530);
}
return stream;
}
/**
* @return "" if no key exists
*/
const std::string& ScriptedTask::GetMemoryText(const std::string& key)
{
// returned if key not found
static const std::string emptyString("");
std::map<std::string, std::string>::const_iterator iter =
textMemory.find(key);
if (iter != textMemory.end())
{
return iter->second;
}
else
{
return emptyString;
}
}
void ScriptedTask::SetMemoryText(const std::string& key, const std::string& text)
{
textMemory[key] = text;
}
/**
* @return 0 if no key exists
*/
double ScriptedTask::GetMemoryValue(int key)
{
std::map<int, double>::const_iterator iter =
numberMemory.find(key);
if (iter != numberMemory.end())
{
return iter->second;
}
else
{
return 0;
}
}
void ScriptedTask::SetMemoryValue(int key, double value)
{
numberMemory[key] = value;
}
const char* ScriptedTask::GetCommandString()
{
if (commandString.size())
{
return commandString.c_str();
}
else
{
commandString = wxString::Format("AI.%s(TaskInterface)\n", taskName.c_str());
return commandString.c_str();
}
}
void ScriptedTask::Update(double t)
{
if (IsReadyForUpdate(t))
{
bool success = tcSimPythonInterface::Get()->CallTaskScript(this, GetCommandString());
FinishUpdate(t);
if (!success)
{
fprintf(stderr, "Deleting task that errored (%s)\n", GetTaskName().c_str());
EndTask();
}
}
}
ScriptedTask::ScriptedTask(tcPlatformObject* platform_, Blackboard* bb,
long id_, double priority_, int attributes_, const std::string& scriptName)
: Task(platform_, bb, id_, priority_, attributes_, scriptName)
{
}
ScriptedTask::~ScriptedTask()
{
}
| 24.662222 | 146 | 0.634349 | dhanin |
db13a60db28ce26d15f3a779921aeb2079bc39c8 | 9,074 | cpp | C++ | src/sutil/sutil.cpp | kevinkingo/OptixRenderer | dbfbabfa7a96527fed84878c0d34eaca2ee8fae7 | [
"MIT"
] | 41 | 2020-06-26T03:58:23.000Z | 2022-02-20T07:45:11.000Z | src/sutil/sutil.cpp | A-guridi/thesis_render | c03b5b988c41a2d8c4b774037ff4039e03501b87 | [
"MIT"
] | 5 | 2020-12-05T13:39:17.000Z | 2022-03-23T01:27:32.000Z | src/sutil/sutil.cpp | A-guridi/thesis_render | c03b5b988c41a2d8c4b774037ff4039e03501b87 | [
"MIT"
] | 20 | 2020-06-27T22:18:51.000Z | 2022-03-01T23:28:22.000Z | /*
* Copyright (c) 2016, 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.
*/
// Note: wglew.h has to be included before sutil.h on Windows
#include <sutil/sutil.h>
//#include <sutil/PPMLoader.h>
#include <sampleConfig.h>
#include <optixu/optixu_math_namespace.h>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <fstream>
#include <stdint.h>
#if defined(_WIN32)
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN 1
# endif
# include<windows.h>
# include<mmsystem.h>
#else // Apple and Linux both use this
# include<sys/time.h>
# include <unistd.h>
# include <dirent.h>
#endif
using namespace optix;
namespace
{
// Global variables for GLUT display functions
RTcontext g_context = 0;
RTbuffer g_image_buffer = 0;
void checkBuffer( RTbuffer buffer )
{
// Check to see if the buffer is two dimensional
unsigned int dimensionality;
RT_CHECK_ERROR( rtBufferGetDimensionality(buffer, &dimensionality) );
if (2 != dimensionality)
throw Exception( "Attempting to display non-2D buffer" );
// Check to see if the buffer is of type float{1,3,4} or uchar4
RTformat format;
RT_CHECK_ERROR( rtBufferGetFormat(buffer, &format) );
if( RT_FORMAT_FLOAT != format &&
RT_FORMAT_FLOAT4 != format &&
RT_FORMAT_FLOAT3 != format &&
RT_FORMAT_UNSIGNED_BYTE4 != format )
throw Exception( "Attempting to diaplay buffer with format not float, float3, float4, or uchar4");
}
bool dirExists( const char* path )
{
#if defined(_WIN32)
DWORD attrib = GetFileAttributes( path );
return (attrib != INVALID_FILE_ATTRIBUTES) && (attrib & FILE_ATTRIBUTE_DIRECTORY);
#else
DIR* dir = opendir( path );
if( dir == NULL )
return false;
closedir(dir);
return true;
#endif
}
} // end anonymous namespace
void sutil::reportErrorMessage( const char* message )
{
std::cerr << "OptiX Error: '" << message << "'\n";
#if defined(_WIN32) && defined(RELEASE_PUBLIC)
{
char s[2048];
sprintf( s, "OptiX Error: %s", message );
MessageBox( 0, s, "OptiX Error", MB_OK|MB_ICONWARNING|MB_SYSTEMMODAL );
}
#endif
}
void sutil::handleError( RTcontext context, RTresult code, const char* file,
int line)
{
const char* message;
char s[2048];
rtContextGetErrorString(context, code, &message);
sprintf(s, "%s\n(%s:%d)", message, file, line);
reportErrorMessage( s );
}
const char* sutil::samplesDir()
{
static char s[512];
// Allow for overrides.
const char* dir = getenv( "OPTIX_SAMPLES_SDK_DIR" );
if (dir) {
strcpy(s, dir);
return s;
}
// Return hardcoded path if it exists.
if( dirExists( SAMPLES_DIR ) )
return SAMPLES_DIR;
// Last resort.
return ".";
}
const char* sutil::samplesPTXDir()
{
static char s[512];
// Allow for overrides.
const char* dir = getenv( "OPTIX_SAMPLES_SDK_PTX_DIR" );
if (dir) {
strcpy(s, dir);
return s;
}
// Return hardcoded path if it exists.
if( dirExists(SAMPLES_PTX_DIR) )
return SAMPLES_PTX_DIR;
// Last resort.
return ".";
}
optix::Buffer sutil::createOutputBuffer(
optix::Context context,
RTformat format,
unsigned width,
unsigned height,
bool use_pbo )
{
optix::Buffer buffer;
buffer = context->createBuffer( RT_BUFFER_OUTPUT, format, width, height );
return buffer;
}
optix::GeometryInstance sutil::createOptiXGroundPlane( optix::Context context,
const std::string& parallelogram_ptx,
const optix::Aabb& aabb,
optix::Material material,
float scale )
{
optix::Geometry parallelogram = context->createGeometry();
parallelogram->setPrimitiveCount( 1u );
parallelogram->setBoundingBoxProgram( context->createProgramFromPTXFile( parallelogram_ptx, "bounds" ) );
parallelogram->setIntersectionProgram( context->createProgramFromPTXFile( parallelogram_ptx, "intersect" ) );
const float extent = scale*fmaxf( aabb.extent( 0 ), aabb.extent( 2 ) );
const float3 anchor = make_float3( aabb.center(0) - 0.5f*extent, aabb.m_min.y - 0.001f*aabb.extent( 1 ), aabb.center(2) - 0.5f*extent );
float3 v1 = make_float3( 0.0f, 0.0f, extent );
float3 v2 = make_float3( extent, 0.0f, 0.0f );
const float3 normal = normalize( cross( v1, v2 ) );
float d = dot( normal, anchor );
v1 *= 1.0f / dot( v1, v1 );
v2 *= 1.0f / dot( v2, v2 );
float4 plane = make_float4( normal, d );
parallelogram["plane"]->setFloat( plane );
parallelogram["v1"]->setFloat( v1 );
parallelogram["v2"]->setFloat( v2 );
parallelogram["anchor"]->setFloat( anchor );
optix::GeometryInstance instance = context->createGeometryInstance( parallelogram, &material, &material + 1 );
return instance;
}
void sutil::calculateCameraVariables( float3 eye, float3 lookat, float3 up,
float fov, float aspect_ratio,
float3& U, float3& V, float3& W, bool fov_is_vertical )
{
float ulen, vlen, wlen;
W = lookat - eye; // Do not normalize W -- it implies focal length
wlen = length( W );
U = normalize( cross( W, up ) );
V = normalize( cross( U, W ) );
if ( fov_is_vertical ) {
vlen = wlen * tanf( 0.5f * fov * M_PIf / 180.0f );
V *= vlen;
ulen = vlen * aspect_ratio;
U *= ulen;
}
else {
ulen = wlen * tanf( 0.5f * fov * M_PIf / 180.0f );
U *= ulen;
vlen = ulen / aspect_ratio;
V *= vlen;
}
}
void sutil::parseDimensions( const char* arg, int& width, int& height )
{
// look for an 'x': <width>x<height>
size_t width_end = strchr( arg, 'x' ) - arg;
size_t height_begin = width_end + 1;
if ( height_begin < strlen( arg ) )
{
// find the beginning of the height string/
const char *height_arg = &arg[height_begin];
// copy width to null-terminated string
char width_arg[32];
strncpy( width_arg, arg, width_end );
width_arg[width_end] = '\0';
// terminate the width string
width_arg[width_end] = '\0';
width = atoi( width_arg );
height = atoi( height_arg );
return;
}
throw Exception(
"Failed to parse width, heigh from string '" +
std::string( arg ) +
"'" );
}
double sutil::currentTime()
{
#if defined(_WIN32)
// inv_freq is 1 over the number of ticks per second.
static double inv_freq;
static bool freq_initialized = 0;
static bool use_high_res_timer = 0;
if(!freq_initialized)
{
LARGE_INTEGER freq;
use_high_res_timer = ( QueryPerformanceFrequency( &freq ) != 0 );
inv_freq = 1.0/freq.QuadPart;
freq_initialized = 1;
}
if (use_high_res_timer)
{
LARGE_INTEGER c_time;
if( QueryPerformanceCounter( &c_time ) )
return c_time.QuadPart*inv_freq;
else
throw Exception( "sutil::currentTime: QueryPerformanceCounter failed" );
}
return static_cast<double>( timeGetTime() ) * 1.0e-3;
#else
struct timeval tv;
if( gettimeofday( &tv, 0 ) )
throw Exception( "sutil::urrentTime(): gettimeofday failed!\n" );
return tv.tv_sec+ tv.tv_usec * 1.0e-6;
#endif
}
void sutil::sleep( int seconds )
{
#if defined(_WIN32)
Sleep( seconds * 1000 );
#else
::sleep( seconds );
#endif
}
| 28.092879 | 140 | 0.642164 | kevinkingo |
db141668a5bf95cc0b6e79401c7c9bb54f844cf3 | 3,990 | cc | C++ | src/file/classicopts.cc | aaszodi/multovl | 00c5b74e65c7aa37cddea8b2ae277fe67fbc59a8 | [
"MIT"
] | 2 | 2018-03-06T02:36:25.000Z | 2020-01-13T10:55:35.000Z | src/file/classicopts.cc | aaszodi/multovl | 00c5b74e65c7aa37cddea8b2ae277fe67fbc59a8 | [
"MIT"
] | null | null | null | src/file/classicopts.cc | aaszodi/multovl | 00c5b74e65c7aa37cddea8b2ae277fe67fbc59a8 | [
"MIT"
] | null | null | null | /* <LICENSE>
License for the MULTOVL multiple genomic overlap tools
Copyright (c) 2007-2012, Dr Andras Aszodi,
Campus Science Support Facilities GmbH (CSF),
Dr-Bohr-Gasse 3, A-1030 Vienna, Austria, Europe.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the Campus Science Support Facilities GmbH
nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</LICENSE> */
// == MODULE classicopts.cc ==
// -- Standard headers --
#include <algorithm>
// -- Own header --
#include "classicopts.hh"
#include "thirdparty.h"
// -- Boost headers --
#include "boost/algorithm/string/case_conv.hpp"
// == Implementation ==
namespace multovl {
ClassicOpts::ClassicOpts():
MultovlOptbase()
{
add_option<std::string>("source", &_source, "multovl",
"Source field in GFF output", 's');
add_option<std::string>("outformat", &_outformat, "GFF",
"Output format {BED,GFF}, case-insensitive, default GFF", 'f');
add_option<std::string>("save", &_saveto, "",
"Save program data to archive file, default: do not save");
add_option<std::string>("load", &_loadfrom, "",
"Load program data from archive file, default: do not load");
}
bool ClassicOpts::check_variables()
{
MultovlOptbase::check_variables();
// canonicalize the output format: currently BED and GFF are accepted
boost::algorithm::to_upper(_outformat);
if (_outformat != "BED" && _outformat != "GFF")
_outformat = "GFF"; // default
// there must be at least 1 positional param
// unless --load has been set in which case
// all input comes from the archive
unsigned int filecnt = pos_opts().size();
if (_loadfrom == "" && filecnt < 1)
{
add_error("Must specify at least one input file");
}
return (!error_status());
}
std::string ClassicOpts::param_str() const
{
std::string outstr = MultovlOptbase::param_str();
outstr += " -s " + _source + " -f " + _outformat;
if (_loadfrom != "") outstr += " --load " + _loadfrom;
if (_saveto != "") outstr += " --save " + _saveto;
return outstr;
}
std::ostream& ClassicOpts::print_help(std::ostream& out) const
{
out << "Multiple Chromosome / Multiple Region Overlaps" << std::endl
<< "Usage: multovl [options] [<infile1> [ <infile2> ... ]]" << std::endl
<< "Accepted input file formats: BED, GFF/GTF" ;
if (config_have_bamtools()) {
out << ", BAM";
}
out << " (detected from extension)" << std::endl
<< "<infileX> arguments are ignored if --load is set" << std::endl
<< "Output goes to stdout, select format with the -f option" << std::endl;
Polite::print_help(out);
return out;
}
} // namespace multovl
| 35.625 | 79 | 0.704261 | aaszodi |
db1448e88f99dd32970373dfb5ff0ee103d6ed9f | 40,214 | cpp | C++ | GCG_Source.build/module.requests.status_codes.cpp | Pckool/GCG | cee786d04ea30f3995e910bca82635f442b2a6a8 | [
"MIT"
] | null | null | null | GCG_Source.build/module.requests.status_codes.cpp | Pckool/GCG | cee786d04ea30f3995e910bca82635f442b2a6a8 | [
"MIT"
] | null | null | null | GCG_Source.build/module.requests.status_codes.cpp | Pckool/GCG | cee786d04ea30f3995e910bca82635f442b2a6a8 | [
"MIT"
] | null | null | null | /* Generated code for Python source for module 'requests.status_codes'
* created by Nuitka version 0.5.28.2
*
* This code is in part copyright 2017 Kay Hayen.
*
* 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 "nuitka/prelude.h"
#include "__helpers.h"
/* The _module_requests$status_codes is a Python object pointer of module type. */
/* Note: For full compatibility with CPython, every module variable access
* needs to go through it except for cases where the module cannot possibly
* have changed in the mean time.
*/
PyObject *module_requests$status_codes;
PyDictObject *moduledict_requests$status_codes;
/* The module constants used, if any. */
extern PyObject *const_str_plain_status_codes;
static PyObject *const_tuple_str_plain_LookupDict_tuple;
static PyObject *const_str_plain__codes;
extern PyObject *const_str_plain_ModuleSpec;
extern PyObject *const_str_plain___spec__;
extern PyObject *const_str_plain___package__;
extern PyObject *const_str_chr_47;
extern PyObject *const_str_plain_requests;
extern PyObject *const_int_pos_1;
extern PyObject *const_str_plain___file__;
static PyObject *const_tuple_tuple_str_chr_92_str_chr_47_tuple_tuple;
extern PyObject *const_str_plain_upper;
extern PyObject *const_str_plain_code;
extern PyObject *const_str_plain_codes;
static PyObject *const_str_digest_840f3e0b846ec96891b7f18eb56afcd8;
extern PyObject *const_tuple_str_chr_92_str_chr_47_tuple;
extern PyObject *const_str_plain_items;
static PyObject *const_str_digest_ac287d930ccff60e2a2e6a9bf4946046;
static PyObject *const_dict_35dd1864798a043a10ec23eaefcf5219;
extern PyObject *const_tuple_empty;
static PyObject *const_dict_38252060f20256dc080a28c7e1fb8512;
extern PyObject *const_str_plain_LookupDict;
extern PyObject *const_str_plain_structures;
extern PyObject *const_str_plain_title;
extern PyObject *const_str_plain___loader__;
static PyObject *const_str_digest_e26a01ee85033c35e44f056d847dbade;
static PyObject *const_str_plain_titles;
extern PyObject *const_str_plain_startswith;
extern PyObject *const_str_plain_name;
extern PyObject *const_str_chr_92;
extern PyObject *const_str_plain___doc__;
extern PyObject *const_str_plain___cached__;
static PyObject *module_filename_obj;
static bool constants_created = false;
static void createModuleConstants( void )
{
const_tuple_str_plain_LookupDict_tuple = PyTuple_New( 1 );
PyTuple_SET_ITEM( const_tuple_str_plain_LookupDict_tuple, 0, const_str_plain_LookupDict ); Py_INCREF( const_str_plain_LookupDict );
const_str_plain__codes = UNSTREAM_STRING( &constant_bin[ 71 ], 6, 1 );
const_tuple_tuple_str_chr_92_str_chr_47_tuple_tuple = PyTuple_New( 1 );
PyTuple_SET_ITEM( const_tuple_tuple_str_chr_92_str_chr_47_tuple_tuple, 0, const_tuple_str_chr_92_str_chr_47_tuple ); Py_INCREF( const_tuple_str_chr_92_str_chr_47_tuple );
const_str_digest_840f3e0b846ec96891b7f18eb56afcd8 = UNSTREAM_STRING( &constant_bin[ 1850620 ], 24, 0 );
const_str_digest_ac287d930ccff60e2a2e6a9bf4946046 = UNSTREAM_STRING( &constant_bin[ 1850644 ], 21, 0 );
const_dict_35dd1864798a043a10ec23eaefcf5219 = PyMarshal_ReadObjectFromString( (char *)&constant_bin[ 1850665 ], 2348 );
const_dict_38252060f20256dc080a28c7e1fb8512 = _PyDict_NewPresized( 1 );
PyDict_SetItem( const_dict_38252060f20256dc080a28c7e1fb8512, const_str_plain_name, const_str_plain_status_codes );
assert( PyDict_Size( const_dict_38252060f20256dc080a28c7e1fb8512 ) == 1 );
const_str_digest_e26a01ee85033c35e44f056d847dbade = UNSTREAM_STRING( &constant_bin[ 1853013 ], 30, 0 );
const_str_plain_titles = UNSTREAM_STRING( &constant_bin[ 1487553 ], 6, 1 );
constants_created = true;
}
#ifndef __NUITKA_NO_ASSERT__
void checkModuleConstants_requests$status_codes( void )
{
// The module may not have been used at all.
if (constants_created == false) return;
}
#endif
// The module code objects.
static PyCodeObject *codeobj_caa175f940b5d1e60f5a0891c7d91121;
static void createModuleCodeObjects(void)
{
module_filename_obj = MAKE_RELATIVE_PATH( const_str_digest_840f3e0b846ec96891b7f18eb56afcd8 );
codeobj_caa175f940b5d1e60f5a0891c7d91121 = MAKE_CODEOBJ( module_filename_obj, const_str_digest_e26a01ee85033c35e44f056d847dbade, 1, const_tuple_empty, 0, 0, CO_NOFREE );
}
// The module function declarations.
// The module function definitions.
#if PYTHON_VERSION >= 300
static struct PyModuleDef mdef_requests$status_codes =
{
PyModuleDef_HEAD_INIT,
"requests.status_codes", /* m_name */
NULL, /* m_doc */
-1, /* m_size */
NULL, /* m_methods */
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
#endif
#if PYTHON_VERSION >= 300
extern PyObject *metapath_based_loader;
#endif
#if PYTHON_VERSION >= 330
extern PyObject *const_str_plain___loader__;
#endif
extern void _initCompiledCellType();
extern void _initCompiledGeneratorType();
extern void _initCompiledFunctionType();
extern void _initCompiledMethodType();
extern void _initCompiledFrameType();
#if PYTHON_VERSION >= 350
extern void _initCompiledCoroutineTypes();
#endif
#if PYTHON_VERSION >= 360
extern void _initCompiledAsyncgenTypes();
#endif
// The exported interface to CPython. On import of the module, this function
// gets called. It has to have an exact function name, in cases it's a shared
// library export. This is hidden behind the MOD_INIT_DECL.
MOD_INIT_DECL( requests$status_codes )
{
#if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300
static bool _init_done = false;
// Modules might be imported repeatedly, which is to be ignored.
if ( _init_done )
{
return MOD_RETURN_VALUE( module_requests$status_codes );
}
else
{
_init_done = true;
}
#endif
#ifdef _NUITKA_MODULE
// In case of a stand alone extension module, need to call initialization
// the init here because that's the first and only time we are going to get
// called here.
// Initialize the constant values used.
_initBuiltinModule();
createGlobalConstants();
/* Initialize the compiled types of Nuitka. */
_initCompiledCellType();
_initCompiledGeneratorType();
_initCompiledFunctionType();
_initCompiledMethodType();
_initCompiledFrameType();
#if PYTHON_VERSION >= 350
_initCompiledCoroutineTypes();
#endif
#if PYTHON_VERSION >= 360
_initCompiledAsyncgenTypes();
#endif
#if PYTHON_VERSION < 300
_initSlotCompare();
#endif
#if PYTHON_VERSION >= 270
_initSlotIternext();
#endif
patchBuiltinModule();
patchTypeComparison();
// Enable meta path based loader if not already done.
setupMetaPathBasedLoader();
#if PYTHON_VERSION >= 300
patchInspectModule();
#endif
#endif
/* The constants only used by this module are created now. */
#ifdef _NUITKA_TRACE
puts("requests.status_codes: Calling createModuleConstants().");
#endif
createModuleConstants();
/* The code objects used by this module are created now. */
#ifdef _NUITKA_TRACE
puts("requests.status_codes: Calling createModuleCodeObjects().");
#endif
createModuleCodeObjects();
// puts( "in initrequests$status_codes" );
// Create the module object first. There are no methods initially, all are
// added dynamically in actual code only. Also no "__doc__" is initially
// set at this time, as it could not contain NUL characters this way, they
// are instead set in early module code. No "self" for modules, we have no
// use for it.
#if PYTHON_VERSION < 300
module_requests$status_codes = Py_InitModule4(
"requests.status_codes", // Module Name
NULL, // No methods initially, all are added
// dynamically in actual module code only.
NULL, // No __doc__ is initially set, as it could
// not contain NUL this way, added early in
// actual code.
NULL, // No self for modules, we don't use it.
PYTHON_API_VERSION
);
#else
module_requests$status_codes = PyModule_Create( &mdef_requests$status_codes );
#endif
moduledict_requests$status_codes = MODULE_DICT( module_requests$status_codes );
CHECK_OBJECT( module_requests$status_codes );
// Seems to work for Python2.7 out of the box, but for Python3, the module
// doesn't automatically enter "sys.modules", so do it manually.
#if PYTHON_VERSION >= 300
{
int r = PyObject_SetItem( PySys_GetObject( (char *)"modules" ), const_str_digest_ac287d930ccff60e2a2e6a9bf4946046, module_requests$status_codes );
assert( r != -1 );
}
#endif
// For deep importing of a module we need to have "__builtins__", so we set
// it ourselves in the same way than CPython does. Note: This must be done
// before the frame object is allocated, or else it may fail.
if ( GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___builtins__ ) == NULL )
{
PyObject *value = (PyObject *)builtin_module;
// Check if main module, not a dict then but the module itself.
#if !defined(_NUITKA_EXE) || !0
value = PyModule_GetDict( value );
#endif
UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___builtins__, value );
}
#if PYTHON_VERSION >= 330
UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___loader__, metapath_based_loader );
#endif
// Temp variables if any
PyObject *tmp_for_loop_1__for_iterator = NULL;
PyObject *tmp_for_loop_1__iter_value = NULL;
PyObject *tmp_for_loop_2__for_iterator = NULL;
PyObject *tmp_for_loop_2__iter_value = NULL;
PyObject *tmp_tuple_unpack_1__element_1 = NULL;
PyObject *tmp_tuple_unpack_1__element_2 = NULL;
PyObject *tmp_tuple_unpack_1__source_iter = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyTracebackObject *exception_tb = NULL;
NUITKA_MAY_BE_UNUSED int exception_lineno = 0;
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2;
PyObject *exception_keeper_type_3;
PyObject *exception_keeper_value_3;
PyTracebackObject *exception_keeper_tb_3;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3;
PyObject *exception_keeper_type_4;
PyObject *exception_keeper_value_4;
PyTracebackObject *exception_keeper_tb_4;
NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_4;
PyObject *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_assign_source_3;
PyObject *tmp_assign_source_4;
PyObject *tmp_assign_source_5;
PyObject *tmp_assign_source_6;
PyObject *tmp_assign_source_7;
PyObject *tmp_assign_source_8;
PyObject *tmp_assign_source_9;
PyObject *tmp_assign_source_10;
PyObject *tmp_assign_source_11;
PyObject *tmp_assign_source_12;
PyObject *tmp_assign_source_13;
PyObject *tmp_assign_source_14;
PyObject *tmp_assign_source_15;
PyObject *tmp_assign_source_16;
PyObject *tmp_assign_source_17;
PyObject *tmp_assign_source_18;
PyObject *tmp_assign_source_19;
PyObject *tmp_called_instance_1;
PyObject *tmp_called_instance_2;
PyObject *tmp_called_instance_3;
PyObject *tmp_called_name_1;
PyObject *tmp_called_name_2;
int tmp_cond_truth_1;
PyObject *tmp_cond_value_1;
PyObject *tmp_fromlist_name_1;
PyObject *tmp_globals_name_1;
PyObject *tmp_import_name_from_1;
PyObject *tmp_iter_arg_1;
PyObject *tmp_iter_arg_2;
PyObject *tmp_iter_arg_3;
PyObject *tmp_iterator_attempt;
PyObject *tmp_iterator_name_1;
PyObject *tmp_kw_name_1;
PyObject *tmp_level_name_1;
PyObject *tmp_locals_name_1;
PyObject *tmp_name_name_1;
PyObject *tmp_next_source_1;
PyObject *tmp_next_source_2;
PyObject *tmp_setattr_attr_1;
PyObject *tmp_setattr_attr_2;
PyObject *tmp_setattr_target_1;
PyObject *tmp_setattr_target_2;
PyObject *tmp_setattr_value_1;
PyObject *tmp_setattr_value_2;
PyObject *tmp_unpack_1;
PyObject *tmp_unpack_2;
NUITKA_MAY_BE_UNUSED PyObject *tmp_unused;
struct Nuitka_FrameObject *frame_caa175f940b5d1e60f5a0891c7d91121;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
// Module code.
tmp_assign_source_1 = Py_None;
UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 );
tmp_assign_source_2 = module_filename_obj;
UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 );
tmp_assign_source_3 = metapath_based_loader;
UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___loader__, tmp_assign_source_3 );
// Frame without reuse.
frame_caa175f940b5d1e60f5a0891c7d91121 = MAKE_MODULE_FRAME( codeobj_caa175f940b5d1e60f5a0891c7d91121, module_requests$status_codes );
// Push the new frame as the currently active one, and we should be exclusively
// owning it.
pushFrameStack( frame_caa175f940b5d1e60f5a0891c7d91121 );
assert( Py_REFCNT( frame_caa175f940b5d1e60f5a0891c7d91121 ) == 2 );
// Framed code:
frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 1;
{
PyObject *module = PyImport_ImportModule("importlib._bootstrap");
if (likely( module != NULL ))
{
tmp_called_name_1 = PyObject_GetAttr( module, const_str_plain_ModuleSpec );
}
else
{
tmp_called_name_1 = NULL;
}
}
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 1;
goto frame_exception_exit_1;
}
tmp_args_element_name_1 = const_str_digest_ac287d930ccff60e2a2e6a9bf4946046;
tmp_args_element_name_2 = metapath_based_loader;
frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 1;
{
PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 };
tmp_assign_source_4 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args );
}
if ( tmp_assign_source_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 1;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___spec__, tmp_assign_source_4 );
tmp_assign_source_5 = Py_None;
UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_5 );
tmp_assign_source_6 = const_str_plain_requests;
UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain___package__, tmp_assign_source_6 );
tmp_name_name_1 = const_str_plain_structures;
tmp_globals_name_1 = (PyObject *)moduledict_requests$status_codes;
tmp_locals_name_1 = Py_None;
tmp_fromlist_name_1 = const_tuple_str_plain_LookupDict_tuple;
tmp_level_name_1 = const_int_pos_1;
frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 3;
tmp_import_name_from_1 = IMPORT_MODULE5( tmp_name_name_1, tmp_globals_name_1, tmp_locals_name_1, tmp_fromlist_name_1, tmp_level_name_1 );
if ( tmp_import_name_from_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 3;
goto frame_exception_exit_1;
}
tmp_assign_source_7 = IMPORT_NAME( tmp_import_name_from_1, const_str_plain_LookupDict );
Py_DECREF( tmp_import_name_from_1 );
if ( tmp_assign_source_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 3;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_LookupDict, tmp_assign_source_7 );
tmp_assign_source_8 = PyDict_Copy( const_dict_35dd1864798a043a10ec23eaefcf5219 );
UPDATE_STRING_DICT1( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain__codes, tmp_assign_source_8 );
tmp_called_name_2 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_LookupDict );
if (unlikely( tmp_called_name_2 == NULL ))
{
tmp_called_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_LookupDict );
}
if ( tmp_called_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "LookupDict" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 85;
goto frame_exception_exit_1;
}
tmp_kw_name_1 = PyDict_Copy( const_dict_38252060f20256dc080a28c7e1fb8512 );
frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 85;
tmp_assign_source_9 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_2, tmp_kw_name_1 );
Py_DECREF( tmp_kw_name_1 );
if ( tmp_assign_source_9 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 85;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_codes, tmp_assign_source_9 );
tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain__codes );
if (unlikely( tmp_called_instance_1 == NULL ))
{
tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain__codes );
}
if ( tmp_called_instance_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "_codes" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 87;
goto frame_exception_exit_1;
}
frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 87;
tmp_iter_arg_1 = CALL_METHOD_NO_ARGS( tmp_called_instance_1, const_str_plain_items );
if ( tmp_iter_arg_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 87;
goto frame_exception_exit_1;
}
tmp_assign_source_10 = MAKE_ITERATOR( tmp_iter_arg_1 );
Py_DECREF( tmp_iter_arg_1 );
if ( tmp_assign_source_10 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 87;
goto frame_exception_exit_1;
}
assert( tmp_for_loop_1__for_iterator == NULL );
tmp_for_loop_1__for_iterator = tmp_assign_source_10;
// Tried code:
loop_start_1:;
tmp_next_source_1 = tmp_for_loop_1__for_iterator;
CHECK_OBJECT( tmp_next_source_1 );
tmp_assign_source_11 = ITERATOR_NEXT( tmp_next_source_1 );
if ( tmp_assign_source_11 == NULL )
{
if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() )
{
goto loop_end_1;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 87;
goto try_except_handler_1;
}
}
{
PyObject *old = tmp_for_loop_1__iter_value;
tmp_for_loop_1__iter_value = tmp_assign_source_11;
Py_XDECREF( old );
}
// Tried code:
tmp_iter_arg_2 = tmp_for_loop_1__iter_value;
CHECK_OBJECT( tmp_iter_arg_2 );
tmp_assign_source_12 = MAKE_ITERATOR( tmp_iter_arg_2 );
if ( tmp_assign_source_12 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 87;
goto try_except_handler_2;
}
{
PyObject *old = tmp_tuple_unpack_1__source_iter;
tmp_tuple_unpack_1__source_iter = tmp_assign_source_12;
Py_XDECREF( old );
}
// Tried code:
tmp_unpack_1 = tmp_tuple_unpack_1__source_iter;
CHECK_OBJECT( tmp_unpack_1 );
tmp_assign_source_13 = UNPACK_NEXT( tmp_unpack_1, 0, 2 );
if ( tmp_assign_source_13 == NULL )
{
if ( !ERROR_OCCURRED() )
{
exception_type = PyExc_StopIteration;
Py_INCREF( exception_type );
exception_value = NULL;
exception_tb = NULL;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
}
exception_lineno = 87;
goto try_except_handler_3;
}
{
PyObject *old = tmp_tuple_unpack_1__element_1;
tmp_tuple_unpack_1__element_1 = tmp_assign_source_13;
Py_XDECREF( old );
}
tmp_unpack_2 = tmp_tuple_unpack_1__source_iter;
CHECK_OBJECT( tmp_unpack_2 );
tmp_assign_source_14 = UNPACK_NEXT( tmp_unpack_2, 1, 2 );
if ( tmp_assign_source_14 == NULL )
{
if ( !ERROR_OCCURRED() )
{
exception_type = PyExc_StopIteration;
Py_INCREF( exception_type );
exception_value = NULL;
exception_tb = NULL;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
}
exception_lineno = 87;
goto try_except_handler_3;
}
{
PyObject *old = tmp_tuple_unpack_1__element_2;
tmp_tuple_unpack_1__element_2 = tmp_assign_source_14;
Py_XDECREF( old );
}
tmp_iterator_name_1 = tmp_tuple_unpack_1__source_iter;
CHECK_OBJECT( tmp_iterator_name_1 );
// Check if iterator has left-over elements.
CHECK_OBJECT( tmp_iterator_name_1 ); assert( HAS_ITERNEXT( tmp_iterator_name_1 ) );
tmp_iterator_attempt = (*Py_TYPE( tmp_iterator_name_1 )->tp_iternext)( tmp_iterator_name_1 );
if (likely( tmp_iterator_attempt == NULL ))
{
PyObject *error = GET_ERROR_OCCURRED();
if ( error != NULL )
{
if ( EXCEPTION_MATCH_BOOL_SINGLE( error, PyExc_StopIteration ))
{
CLEAR_ERROR_OCCURRED();
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 87;
goto try_except_handler_3;
}
}
}
else
{
Py_DECREF( tmp_iterator_attempt );
// TODO: Could avoid PyErr_Format.
#if PYTHON_VERSION < 300
PyErr_Format( PyExc_ValueError, "too many values to unpack" );
#else
PyErr_Format( PyExc_ValueError, "too many values to unpack (expected 2)" );
#endif
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 87;
goto try_except_handler_3;
}
goto try_end_1;
// Exception handler code:
try_except_handler_3:;
exception_keeper_type_1 = exception_type;
exception_keeper_value_1 = exception_value;
exception_keeper_tb_1 = exception_tb;
exception_keeper_lineno_1 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_tuple_unpack_1__source_iter );
tmp_tuple_unpack_1__source_iter = NULL;
// Re-raise.
exception_type = exception_keeper_type_1;
exception_value = exception_keeper_value_1;
exception_tb = exception_keeper_tb_1;
exception_lineno = exception_keeper_lineno_1;
goto try_except_handler_2;
// End of try:
try_end_1:;
goto try_end_2;
// Exception handler code:
try_except_handler_2:;
exception_keeper_type_2 = exception_type;
exception_keeper_value_2 = exception_value;
exception_keeper_tb_2 = exception_tb;
exception_keeper_lineno_2 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_tuple_unpack_1__element_1 );
tmp_tuple_unpack_1__element_1 = NULL;
Py_XDECREF( tmp_tuple_unpack_1__element_2 );
tmp_tuple_unpack_1__element_2 = NULL;
// Re-raise.
exception_type = exception_keeper_type_2;
exception_value = exception_keeper_value_2;
exception_tb = exception_keeper_tb_2;
exception_lineno = exception_keeper_lineno_2;
goto try_except_handler_1;
// End of try:
try_end_2:;
Py_XDECREF( tmp_tuple_unpack_1__source_iter );
tmp_tuple_unpack_1__source_iter = NULL;
tmp_assign_source_15 = tmp_tuple_unpack_1__element_1;
CHECK_OBJECT( tmp_assign_source_15 );
UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_code, tmp_assign_source_15 );
Py_XDECREF( tmp_tuple_unpack_1__element_1 );
tmp_tuple_unpack_1__element_1 = NULL;
tmp_assign_source_16 = tmp_tuple_unpack_1__element_2;
CHECK_OBJECT( tmp_assign_source_16 );
UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_titles, tmp_assign_source_16 );
Py_XDECREF( tmp_tuple_unpack_1__element_2 );
tmp_tuple_unpack_1__element_2 = NULL;
Py_XDECREF( tmp_tuple_unpack_1__element_1 );
tmp_tuple_unpack_1__element_1 = NULL;
Py_XDECREF( tmp_tuple_unpack_1__element_2 );
tmp_tuple_unpack_1__element_2 = NULL;
tmp_iter_arg_3 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_titles );
if (unlikely( tmp_iter_arg_3 == NULL ))
{
tmp_iter_arg_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_titles );
}
if ( tmp_iter_arg_3 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "titles" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 88;
goto try_except_handler_1;
}
tmp_assign_source_17 = MAKE_ITERATOR( tmp_iter_arg_3 );
if ( tmp_assign_source_17 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 88;
goto try_except_handler_1;
}
{
PyObject *old = tmp_for_loop_2__for_iterator;
tmp_for_loop_2__for_iterator = tmp_assign_source_17;
Py_XDECREF( old );
}
// Tried code:
loop_start_2:;
tmp_next_source_2 = tmp_for_loop_2__for_iterator;
CHECK_OBJECT( tmp_next_source_2 );
tmp_assign_source_18 = ITERATOR_NEXT( tmp_next_source_2 );
if ( tmp_assign_source_18 == NULL )
{
if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() )
{
goto loop_end_2;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 88;
goto try_except_handler_4;
}
}
{
PyObject *old = tmp_for_loop_2__iter_value;
tmp_for_loop_2__iter_value = tmp_assign_source_18;
Py_XDECREF( old );
}
tmp_assign_source_19 = tmp_for_loop_2__iter_value;
CHECK_OBJECT( tmp_assign_source_19 );
UPDATE_STRING_DICT0( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_title, tmp_assign_source_19 );
tmp_setattr_target_1 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_codes );
if (unlikely( tmp_setattr_target_1 == NULL ))
{
tmp_setattr_target_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_codes );
}
if ( tmp_setattr_target_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "codes" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 89;
goto try_except_handler_4;
}
tmp_setattr_attr_1 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_title );
if (unlikely( tmp_setattr_attr_1 == NULL ))
{
tmp_setattr_attr_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_title );
}
if ( tmp_setattr_attr_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "title" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 89;
goto try_except_handler_4;
}
tmp_setattr_value_1 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_code );
if (unlikely( tmp_setattr_value_1 == NULL ))
{
tmp_setattr_value_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_code );
}
if ( tmp_setattr_value_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "code" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 89;
goto try_except_handler_4;
}
tmp_unused = BUILTIN_SETATTR( tmp_setattr_target_1, tmp_setattr_attr_1, tmp_setattr_value_1 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 89;
goto try_except_handler_4;
}
tmp_called_instance_2 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_title );
if (unlikely( tmp_called_instance_2 == NULL ))
{
tmp_called_instance_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_title );
}
if ( tmp_called_instance_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "title" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 90;
goto try_except_handler_4;
}
frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 90;
tmp_cond_value_1 = CALL_METHOD_WITH_ARGS1( tmp_called_instance_2, const_str_plain_startswith, &PyTuple_GET_ITEM( const_tuple_tuple_str_chr_92_str_chr_47_tuple_tuple, 0 ) );
if ( tmp_cond_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 90;
goto try_except_handler_4;
}
tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_1 );
exception_lineno = 90;
goto try_except_handler_4;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_no_1;
}
else
{
goto branch_yes_1;
}
branch_yes_1:;
tmp_setattr_target_2 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_codes );
if (unlikely( tmp_setattr_target_2 == NULL ))
{
tmp_setattr_target_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_codes );
}
if ( tmp_setattr_target_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "codes" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 91;
goto try_except_handler_4;
}
tmp_called_instance_3 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_title );
if (unlikely( tmp_called_instance_3 == NULL ))
{
tmp_called_instance_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_title );
}
if ( tmp_called_instance_3 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "title" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 91;
goto try_except_handler_4;
}
frame_caa175f940b5d1e60f5a0891c7d91121->m_frame.f_lineno = 91;
tmp_setattr_attr_2 = CALL_METHOD_NO_ARGS( tmp_called_instance_3, const_str_plain_upper );
if ( tmp_setattr_attr_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 91;
goto try_except_handler_4;
}
tmp_setattr_value_2 = GET_STRING_DICT_VALUE( moduledict_requests$status_codes, (Nuitka_StringObject *)const_str_plain_code );
if (unlikely( tmp_setattr_value_2 == NULL ))
{
tmp_setattr_value_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_code );
}
if ( tmp_setattr_value_2 == NULL )
{
Py_DECREF( tmp_setattr_attr_2 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "code" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 91;
goto try_except_handler_4;
}
tmp_unused = BUILTIN_SETATTR( tmp_setattr_target_2, tmp_setattr_attr_2, tmp_setattr_value_2 );
Py_DECREF( tmp_setattr_attr_2 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 91;
goto try_except_handler_4;
}
branch_no_1:;
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 88;
goto try_except_handler_4;
}
goto loop_start_2;
loop_end_2:;
goto try_end_3;
// Exception handler code:
try_except_handler_4:;
exception_keeper_type_3 = exception_type;
exception_keeper_value_3 = exception_value;
exception_keeper_tb_3 = exception_tb;
exception_keeper_lineno_3 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_for_loop_2__iter_value );
tmp_for_loop_2__iter_value = NULL;
Py_XDECREF( tmp_for_loop_2__for_iterator );
tmp_for_loop_2__for_iterator = NULL;
// Re-raise.
exception_type = exception_keeper_type_3;
exception_value = exception_keeper_value_3;
exception_tb = exception_keeper_tb_3;
exception_lineno = exception_keeper_lineno_3;
goto try_except_handler_1;
// End of try:
try_end_3:;
Py_XDECREF( tmp_for_loop_2__iter_value );
tmp_for_loop_2__iter_value = NULL;
Py_XDECREF( tmp_for_loop_2__for_iterator );
tmp_for_loop_2__for_iterator = NULL;
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 87;
goto try_except_handler_1;
}
goto loop_start_1;
loop_end_1:;
goto try_end_4;
// Exception handler code:
try_except_handler_1:;
exception_keeper_type_4 = exception_type;
exception_keeper_value_4 = exception_value;
exception_keeper_tb_4 = exception_tb;
exception_keeper_lineno_4 = exception_lineno;
exception_type = NULL;
exception_value = NULL;
exception_tb = NULL;
exception_lineno = 0;
Py_XDECREF( tmp_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = NULL;
// Re-raise.
exception_type = exception_keeper_type_4;
exception_value = exception_keeper_value_4;
exception_tb = exception_keeper_tb_4;
exception_lineno = exception_keeper_lineno_4;
goto frame_exception_exit_1;
// End of try:
try_end_4:;
// Restore frame exception if necessary.
#if 0
RESTORE_FRAME_EXCEPTION( frame_caa175f940b5d1e60f5a0891c7d91121 );
#endif
popFrameStack();
assertFrameObject( frame_caa175f940b5d1e60f5a0891c7d91121 );
goto frame_no_exception_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_caa175f940b5d1e60f5a0891c7d91121 );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_caa175f940b5d1e60f5a0891c7d91121, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_caa175f940b5d1e60f5a0891c7d91121->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_caa175f940b5d1e60f5a0891c7d91121, exception_lineno );
}
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto module_exception_exit;
frame_no_exception_1:;
Py_XDECREF( tmp_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = NULL;
return MOD_RETURN_VALUE( module_requests$status_codes );
module_exception_exit:
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return MOD_RETURN_VALUE( NULL );
}
| 33.344942 | 176 | 0.71781 | Pckool |
db1aecfdac52204fbfd78f9ec74e3461398d731a | 825 | cpp | C++ | Patterns/Misc/array_to_tuple.cpp | kant/Always-be-learning | 7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5 | [
"Unlicense"
] | null | null | null | Patterns/Misc/array_to_tuple.cpp | kant/Always-be-learning | 7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5 | [
"Unlicense"
] | null | null | null | Patterns/Misc/array_to_tuple.cpp | kant/Always-be-learning | 7c3b3b4f5e8f0dfcb4d8f4b7f7428d5c8ab164c5 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <array>
#include <tuple>
#include <type_traits>
// Convert array into a tuple
template<typename Array, std::size_t... I>
constexpr auto a2t_impl(const Array& a, std::index_sequence<I...>)
{
return std::make_tuple(a[I]...);
}
template<typename T, std::size_t N, typename Indices = std::make_index_sequence<N>>
constexpr auto a2t(const T(&arr)[N])
{
return a2t_impl(arr, Indices{});
}
template<typename T, std::size_t N, typename Indices = std::make_index_sequence<N>>
constexpr auto a2t(const std::array<T,N>& a)
{
return a2t_impl(a, Indices{});
}
int main()
{
constexpr const auto a1 = std::array<int, 4>{1,2,3,4};
constexpr int a2[4] = {1,2,3,4};
constexpr auto t1 = a2t(a1);
constexpr auto t2 = a2t(a2);
static_assert(t1 == t2, "Tuples are different");
}
| 23.571429 | 83 | 0.669091 | kant |
db1cd38671c039d3b0753c028af7f8478f147ebc | 309 | cpp | C++ | src/test/staticConstructors.cpp | kkysen/DifferentiableFuzzer | 22088a3871e4104c4afc463c05ce58f0221dbc43 | [
"MIT"
] | 1 | 2019-06-19T06:03:03.000Z | 2019-06-19T06:03:03.000Z | src/test/staticConstructors.cpp | kkysen/SmartNeuralFuzzer | 22088a3871e4104c4afc463c05ce58f0221dbc43 | [
"MIT"
] | null | null | null | src/test/staticConstructors.cpp | kkysen/SmartNeuralFuzzer | 22088a3871e4104c4afc463c05ce58f0221dbc43 | [
"MIT"
] | null | null | null | //
// Created by Khyber on 3/18/2019.
//
class A {
public:
static bool initialized;
A() noexcept {
initialized = true;
}
~A() {
initialized = false;
}
};
bool A::initialized = false;
A a;
int main() {
return static_cast<int>(A::initialized);
}
| 11.035714 | 44 | 0.517799 | kkysen |
db1d3dc96b67bbef9bdcc19d177f3e3f63a57935 | 43,655 | cpp | C++ | src/qt/qtbase/src/network/socket/qnativesocketengine_winrt.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-01-21T01:48:04.000Z | 2015-01-21T01:48:04.000Z | src/qt/qtbase/src/network/socket/qnativesocketengine_winrt.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtbase/src/network/socket/qnativesocketengine_winrt.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2017-03-19T13:03:23.000Z | 2017-03-19T13:03:23.000Z | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qt_windows.h>
#include "qnativesocketengine_winrt_p.h"
#include <qcoreapplication.h>
#include <qabstracteventdispatcher.h>
#include <qsocketnotifier.h>
#include <qdatetime.h>
#include <qnetworkinterface.h>
#include <qelapsedtimer.h>
#include <qthread.h>
#include <qabstracteventdispatcher.h>
#include <private/qeventdispatcher_winrt_p.h>
#include <wrl.h>
#include <windows.foundation.collections.h>
#include <windows.storage.streams.h>
#include <windows.networking.h>
#include <windows.networking.sockets.h>
#include <robuffer.h>
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Foundation::Collections;
using namespace ABI::Windows::Storage::Streams;
using namespace ABI::Windows::Networking;
using namespace ABI::Windows::Networking::Connectivity;
using namespace ABI::Windows::Networking::Sockets;
typedef ITypedEventHandler<StreamSocketListener *, StreamSocketListenerConnectionReceivedEventArgs *> ClientConnectedHandler;
typedef ITypedEventHandler<DatagramSocket *, DatagramSocketMessageReceivedEventArgs *> DatagramReceivedHandler;
typedef IAsyncOperationWithProgressCompletedHandler<IBuffer *, UINT32> SocketReadCompletedHandler;
typedef IAsyncOperationWithProgressCompletedHandler<UINT32, UINT32> SocketWriteCompletedHandler;
typedef IAsyncOperationWithProgress<IBuffer *, UINT32> IAsyncBufferOperation;
QT_BEGIN_NAMESPACE
// Common constructs
#define Q_CHECK_VALID_SOCKETLAYER(function, returnValue) do { \
if (!isValid()) { \
qWarning(""#function" was called on an uninitialized socket device"); \
return returnValue; \
} } while (0)
#define Q_CHECK_INVALID_SOCKETLAYER(function, returnValue) do { \
if (isValid()) { \
qWarning(""#function" was called on an already initialized socket device"); \
return returnValue; \
} } while (0)
#define Q_CHECK_STATE(function, checkState, returnValue) do { \
if (d->socketState != (checkState)) { \
qWarning(""#function" was not called in "#checkState); \
return (returnValue); \
} } while (0)
#define Q_CHECK_NOT_STATE(function, checkState, returnValue) do { \
if (d->socketState == (checkState)) { \
qWarning(""#function" was called in "#checkState); \
return (returnValue); \
} } while (0)
#define Q_CHECK_STATES(function, state1, state2, returnValue) do { \
if (d->socketState != (state1) && d->socketState != (state2)) { \
qWarning(""#function" was called" \
" not in "#state1" or "#state2); \
return (returnValue); \
} } while (0)
#define Q_CHECK_TYPE(function, type, returnValue) do { \
if (d->socketType != (type)) { \
qWarning(#function" was called by a" \
" socket other than "#type""); \
return (returnValue); \
} } while (0)
#define Q_TR(a) QT_TRANSLATE_NOOP(QNativeSocketEngine, a)
typedef QHash<qintptr, IStreamSocket *> TcpSocketHash;
struct SocketHandler
{
SocketHandler() : socketCount(0) {}
qintptr socketCount;
TcpSocketHash pendingTcpSockets;
};
Q_GLOBAL_STATIC(SocketHandler, gSocketHandler)
QString qt_QStringFromHSTRING(HSTRING string)
{
UINT32 length;
PCWSTR rawString = WindowsGetStringRawBuffer(string, &length);
return QString::fromWCharArray(rawString, length);
}
#define READ_BUFFER_SIZE 8192
class ByteArrayBuffer : public Microsoft::WRL::RuntimeClass<RuntimeClassFlags<WinRtClassicComMix>,
IBuffer, Windows::Storage::Streams::IBufferByteAccess>
{
public:
ByteArrayBuffer(int size) : m_bytes(size, Qt::Uninitialized), m_length(0)
{
}
ByteArrayBuffer(const char *data, int size) : m_bytes(data, size), m_length(size)
{
}
HRESULT __stdcall Buffer(byte **value)
{
*value = reinterpret_cast<byte *>(m_bytes.data());
return S_OK;
}
HRESULT __stdcall get_Capacity(UINT32 *value)
{
*value = m_bytes.size();
return S_OK;
}
HRESULT __stdcall get_Length(UINT32 *value)
{
*value = m_length;
return S_OK;
}
HRESULT __stdcall put_Length(UINT32 value)
{
Q_ASSERT(value <= UINT32(m_bytes.size()));
m_length = value;
return S_OK;
}
ComPtr<IInputStream> inputStream() const
{
return m_stream;
}
void setInputStream(ComPtr<IInputStream> stream)
{
m_stream = stream;
}
private:
QByteArray m_bytes;
UINT32 m_length;
ComPtr<IInputStream> m_stream;
};
template <typename T>
static AsyncStatus opStatus(const ComPtr<T> &op)
{
ComPtr<IAsyncInfo> info;
HRESULT hr = op.As(&info);
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to cast op to IAsyncInfo.");
return Error;
}
AsyncStatus status;
hr = info->get_Status(&status);
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to get AsyncStatus.");
return Error;
}
return status;
}
QNativeSocketEngine::QNativeSocketEngine(QObject *parent)
: QAbstractSocketEngine(*new QNativeSocketEnginePrivate(), parent)
{
connect(this, SIGNAL(connectionReady()), SLOT(connectionNotification()), Qt::QueuedConnection);
connect(this, SIGNAL(readReady()), SLOT(readNotification()), Qt::QueuedConnection);
connect(this, SIGNAL(writeReady()), SLOT(writeNotification()), Qt::QueuedConnection);
}
QNativeSocketEngine::~QNativeSocketEngine()
{
close();
}
bool QNativeSocketEngine::initialize(QAbstractSocket::SocketType type, QAbstractSocket::NetworkLayerProtocol protocol)
{
Q_D(QNativeSocketEngine);
if (isValid())
close();
// Create the socket
if (!d->createNewSocket(type, protocol))
return false;
d->socketType = type;
d->socketProtocol = protocol;
return true;
}
bool QNativeSocketEngine::initialize(qintptr socketDescriptor, QAbstractSocket::SocketState socketState)
{
Q_D(QNativeSocketEngine);
if (isValid())
close();
d->socketDescriptor = socketDescriptor;
// Currently, only TCP sockets are initialized this way.
SocketHandler *handler = gSocketHandler();
d->tcp = handler->pendingTcpSockets.take(socketDescriptor);
d->socketType = QAbstractSocket::TcpSocket;
if (!d->tcp || !d->fetchConnectionParameters())
return false;
d->socketState = socketState;
return true;
}
qintptr QNativeSocketEngine::socketDescriptor() const
{
Q_D(const QNativeSocketEngine);
return d->socketDescriptor;
}
bool QNativeSocketEngine::isValid() const
{
Q_D(const QNativeSocketEngine);
return d->socketDescriptor != -1;
}
bool QNativeSocketEngine::connectToHost(const QHostAddress &address, quint16 port)
{
const QString addressString = address.toString();
return connectToHostByName(addressString, port);
}
bool QNativeSocketEngine::connectToHostByName(const QString &name, quint16 port)
{
Q_D(QNativeSocketEngine);
HStringReference hostNameRef(reinterpret_cast<LPCWSTR>(name.utf16()));
ComPtr<IHostNameFactory> hostNameFactory;
GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
&hostNameFactory);
ComPtr<IHostName> remoteHost;
if (FAILED(hostNameFactory->CreateHostName(hostNameRef.Get(), &remoteHost))) {
qWarning("QNativeSocketEnginePrivate::nativeConnect:: Could not create hostname");
return false;
}
ComPtr<IAsyncAction> op;
const QString portString = QString::number(port);
HStringReference portReference(reinterpret_cast<LPCWSTR>(portString.utf16()));
HRESULT hr = E_FAIL;
if (d->socketType == QAbstractSocket::TcpSocket)
hr = d->tcp->ConnectAsync(remoteHost.Get(), portReference.Get(), &op);
else if (d->socketType == QAbstractSocket::UdpSocket)
hr = d->udp->ConnectAsync(remoteHost.Get(), portReference.Get(), &op);
if (FAILED(hr)) {
qWarning("QNativeSocketEnginePrivate::nativeConnect:: Could not obtain connect action");
return false;
}
hr = op->put_Completed(Callback<IAsyncActionCompletedHandler>(
d, &QNativeSocketEnginePrivate::handleConnectToHost).Get());
if (FAILED(hr)) {
qErrnoWarning(hr, "Unable to set host connection callback.");
return false;
}
d->socketState = QAbstractSocket::ConnectingState;
while (opStatus(op) == Started)
d->eventLoop.processEvents();
AsyncStatus status = opStatus(op);
if (status == Error || status == Canceled)
return false;
if (hr == 0x8007274c) { // A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
d->setError(QAbstractSocket::NetworkError, d->ConnectionTimeOutErrorString);
d->socketState = QAbstractSocket::UnconnectedState;
return false;
}
if (hr == 0x8007274d) { // No connection could be made because the target machine actively refused it.
d->setError(QAbstractSocket::ConnectionRefusedError, d->ConnectionRefusedErrorString);
d->socketState = QAbstractSocket::UnconnectedState;
return false;
}
if (FAILED(hr)) {
d->setError(QAbstractSocket::UnknownSocketError, d->UnknownSocketErrorString);
d->socketState = QAbstractSocket::UnconnectedState;
return false;
}
if (d->socketType == QAbstractSocket::TcpSocket) {
IInputStream *stream;
hr = d->tcp->get_InputStream(&stream);
if (FAILED(hr))
return false;
ByteArrayBuffer *buffer = static_cast<ByteArrayBuffer *>(d->readBuffer.Get());
buffer->setInputStream(stream);
ComPtr<IAsyncBufferOperation> op;
hr = stream->ReadAsync(buffer, READ_BUFFER_SIZE, InputStreamOptions_Partial, &op);
if (FAILED(hr))
return false;
hr = op->put_Completed(Callback<SocketReadCompletedHandler>(d, &QNativeSocketEnginePrivate::handleReadyRead).Get());
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to set socket read callback.");
return false;
}
}
d->socketState = QAbstractSocket::ConnectedState;
return true;
}
bool QNativeSocketEngine::bind(const QHostAddress &address, quint16 port)
{
Q_D(QNativeSocketEngine);
ComPtr<IHostName> hostAddress;
if (address != QHostAddress::Any && address != QHostAddress::AnyIPv4 && address != QHostAddress::AnyIPv6) {
ComPtr<IHostNameFactory> hostNameFactory;
GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
&hostNameFactory);
const QString addressString = address.toString();
HStringReference addressRef(reinterpret_cast<LPCWSTR>(addressString.utf16()));
hostNameFactory->CreateHostName(addressRef.Get(), &hostAddress);
}
HRESULT hr;
QString portQString = port ? QString::number(port) : QString();
HStringReference portString(reinterpret_cast<LPCWSTR>(portQString.utf16()));
ComPtr<IAsyncAction> op;
if (d->socketType == QAbstractSocket::TcpSocket) {
if (!d->tcpListener
&& FAILED(RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_StreamSocketListener).Get(),
&d->tcpListener))) {
qWarning("Failed to create listener");
return false;
}
EventRegistrationToken token;
d->tcpListener->add_ConnectionReceived(Callback<ClientConnectedHandler>(d, &QNativeSocketEnginePrivate::handleClientConnection).Get(), &token);
hr = d->tcpListener->BindEndpointAsync(hostAddress.Get(), portString.Get(), &op);
if (FAILED(hr)) {
qErrnoWarning(hr, "Unable to bind socket."); // ### Set error message
return false;
}
} else if (d->socketType == QAbstractSocket::UdpSocket) {
hr = d->udp->BindEndpointAsync(hostAddress.Get(), portString.Get(), &op);
if (FAILED(hr)) {
qErrnoWarning(hr, "Unable to bind socket."); // ### Set error message
return false;
}
hr = op->put_Completed(Callback<IAsyncActionCompletedHandler>(d, &QNativeSocketEnginePrivate::handleBindCompleted).Get());
if (FAILED(hr)) {
qErrnoWarning(hr, "Unable to set bind callback.");
return false;
}
}
if (op) {
while (opStatus(op) == Started)
d->eventLoop.processEvents();
AsyncStatus status = opStatus(op);
if (status == Error || status == Canceled)
return false;
hr = op->GetResults();
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to bind socket");
return false;
}
d->socketState = QAbstractSocket::BoundState;
d->fetchConnectionParameters();
return true;
}
return false;
}
bool QNativeSocketEngine::listen()
{
Q_D(QNativeSocketEngine);
Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::listen(), false);
Q_CHECK_STATE(QNativeSocketEngine::listen(), QAbstractSocket::BoundState, false);
Q_CHECK_TYPE(QNativeSocketEngine::listen(), QAbstractSocket::TcpSocket, false);
if (d->tcpListener && d->socketDescriptor != -1) {
d->socketState = QAbstractSocket::ListeningState;
return true;
}
return false;
}
int QNativeSocketEngine::accept()
{
Q_D(QNativeSocketEngine);
Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::accept(), -1);
Q_CHECK_STATE(QNativeSocketEngine::accept(), QAbstractSocket::ListeningState, -1);
Q_CHECK_TYPE(QNativeSocketEngine::accept(), QAbstractSocket::TcpSocket, -1);
if (d->socketDescriptor == -1 || d->pendingConnections.isEmpty())
return -1;
// Start processing incoming data
if (d->socketType == QAbstractSocket::TcpSocket) {
IStreamSocket *socket = d->pendingConnections.takeFirst();
IInputStream *stream;
socket->get_InputStream(&stream);
// TODO: delete buffer and stream on socket close
ByteArrayBuffer *buffer = static_cast<ByteArrayBuffer *>(d->readBuffer.Get());
buffer->setInputStream(stream);
ComPtr<IAsyncBufferOperation> op;
HRESULT hr = stream->ReadAsync(buffer, READ_BUFFER_SIZE, InputStreamOptions_Partial, &op);
if (FAILED(hr)) {
qErrnoWarning(hr, "Faild to read from the socket buffer.");
return -1;
}
hr = op->put_Completed(Callback<SocketReadCompletedHandler>(d, &QNativeSocketEnginePrivate::handleReadyRead).Get());
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to set socket read callback.");
return -1;
}
d->currentConnections.append(socket);
SocketHandler *handler = gSocketHandler();
handler->pendingTcpSockets.insert(++handler->socketCount, socket);
return handler->socketCount;
}
return -1;
}
void QNativeSocketEngine::close()
{
Q_D(QNativeSocketEngine);
if (d->socketDescriptor != -1) {
IClosable *socket = 0;
if (d->socketType == QAbstractSocket::TcpSocket)
d->tcp->QueryInterface(IID_PPV_ARGS(&socket));
else if (d->socketType == QAbstractSocket::UdpSocket)
d->udp->QueryInterface(IID_PPV_ARGS(&socket));
if (socket) {
d->closingDown = true;
socket->Close();
socket->Release();
d->socketDescriptor = -1;
}
d->socketDescriptor = -1;
}
d->socketState = QAbstractSocket::UnconnectedState;
d->hasSetSocketError = false;
d->localPort = 0;
d->localAddress.clear();
d->peerPort = 0;
d->peerAddress.clear();
}
bool QNativeSocketEngine::joinMulticastGroup(const QHostAddress &groupAddress, const QNetworkInterface &iface)
{
Q_UNUSED(groupAddress);
Q_UNUSED(iface);
Q_UNIMPLEMENTED();
return false;
}
bool QNativeSocketEngine::leaveMulticastGroup(const QHostAddress &groupAddress, const QNetworkInterface &iface)
{
Q_UNUSED(groupAddress);
Q_UNUSED(iface);
Q_UNIMPLEMENTED();
return false;
}
QNetworkInterface QNativeSocketEngine::multicastInterface() const
{
Q_UNIMPLEMENTED();
return QNetworkInterface();
}
bool QNativeSocketEngine::setMulticastInterface(const QNetworkInterface &iface)
{
Q_UNUSED(iface);
Q_UNIMPLEMENTED();
return false;
}
qint64 QNativeSocketEngine::bytesAvailable() const
{
Q_D(const QNativeSocketEngine);
if (d->socketType != QAbstractSocket::TcpSocket)
return -1;
return d->readBytes.size() - d->readBytes.pos();
}
qint64 QNativeSocketEngine::read(char *data, qint64 maxlen)
{
Q_D(QNativeSocketEngine);
if (d->socketType != QAbstractSocket::TcpSocket)
return -1;
QMutexLocker mutexLocker(&d->readMutex);
return d->readBytes.read(data, maxlen);
}
qint64 QNativeSocketEngine::write(const char *data, qint64 len)
{
Q_D(QNativeSocketEngine);
HRESULT hr = E_FAIL;
ComPtr<IOutputStream> stream;
if (d->socketType == QAbstractSocket::TcpSocket)
hr = d->tcp->get_OutputStream(&stream);
else if (d->socketType == QAbstractSocket::UdpSocket)
hr = d->udp->get_OutputStream(&stream);
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to get output stream to socket.");
return -1;
}
ComPtr<ByteArrayBuffer> buffer = Make<ByteArrayBuffer>(data, len);
ComPtr<IAsyncOperationWithProgress<UINT32, UINT32>> op;
hr = stream->WriteAsync(buffer.Get(), &op);
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to write to socket.");
return -1;
}
hr = op->put_Completed(Callback<IAsyncOperationWithProgressCompletedHandler<UINT32, UINT32>>(
d, &QNativeSocketEnginePrivate::handleWriteCompleted).Get());
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to set socket write callback.");
return -1;
}
while (opStatus(op) == Started)
d->eventLoop.processEvents();
AsyncStatus status = opStatus(op);
if (status == Error || status == Canceled)
return -1;
UINT32 bytesWritten;
hr = op->GetResults(&bytesWritten);
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to get written socket length.");
return -1;
}
if (bytesWritten && d->notifyOnWrite)
emit writeReady();
return bytesWritten;
}
qint64 QNativeSocketEngine::readDatagram(char *data, qint64 maxlen, QHostAddress *addr, quint16 *port)
{
Q_D(QNativeSocketEngine);
if (d->socketType != QAbstractSocket::UdpSocket)
return -1;
QHostAddress returnAddress;
quint16 returnPort;
for (int i = 0; i < d->pendingDatagrams.size(); ++i) {
IDatagramSocketMessageReceivedEventArgs *arg = d->pendingDatagrams.at(i);
ComPtr<IHostName> remoteHost;
HSTRING remoteHostString;
HSTRING remotePort;
arg->get_RemoteAddress(&remoteHost);
arg->get_RemotePort(&remotePort);
remoteHost->get_CanonicalName(&remoteHostString);
returnAddress.setAddress(qt_QStringFromHSTRING(remoteHostString));
returnPort = qt_QStringFromHSTRING(remotePort).toInt();
ComPtr<IDataReader> reader;
arg->GetDataReader(&reader);
if (!reader)
continue;
BYTE buffer[1024];
reader->ReadBytes(maxlen, buffer);
*addr = returnAddress;
*port = returnPort;
arg = d->pendingDatagrams.takeFirst();
// TODO: fill data
Q_UNUSED(data);
arg->Release();
delete arg;
--i;
return maxlen;
}
return -1;
}
qint64 QNativeSocketEngine::writeDatagram(const char *data, qint64 len, const QHostAddress &addr, quint16 port)
{
Q_D(QNativeSocketEngine);
if (d->socketType != QAbstractSocket::UdpSocket)
return -1;
ComPtr<IHostName> remoteHost;
ComPtr<IHostNameFactory> hostNameFactory;
if (FAILED(GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Networking_HostName).Get(),
&hostNameFactory))) {
qWarning("QNativeSocketEnginePrivate::nativeSendDatagram: could not obtain hostname factory");
return -1;
}
const QString addressString = addr.toString();
HStringReference hostNameRef(reinterpret_cast<LPCWSTR>(addressString.utf16()));
hostNameFactory->CreateHostName(hostNameRef.Get(), &remoteHost);
ComPtr<IAsyncOperation<IOutputStream *>> streamOperation;
ComPtr<IOutputStream> stream;
const QString portString = QString::number(port);
HStringReference portRef(reinterpret_cast<LPCWSTR>(portString.utf16()));
if (FAILED(d->udp->GetOutputStreamAsync(remoteHost.Get(), portRef.Get(), &streamOperation)))
return -1;
HRESULT hr;
while (hr = streamOperation->GetResults(&stream) == E_ILLEGAL_METHOD_CALL)
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
ComPtr<IDataWriterFactory> dataWriterFactory;
GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Storage_Streams_DataWriter).Get(), &dataWriterFactory);
ComPtr<IDataWriter> writer;
dataWriterFactory->CreateDataWriter(stream.Get(), &writer);
writer->WriteBytes(len, (unsigned char *)data);
return len;
}
bool QNativeSocketEngine::hasPendingDatagrams() const
{
Q_D(const QNativeSocketEngine);
return d->pendingDatagrams.length() > 0;
}
qint64 QNativeSocketEngine::pendingDatagramSize() const
{
Q_D(const QNativeSocketEngine);
qint64 ret = 0;
foreach (IDatagramSocketMessageReceivedEventArgs *arg, d->pendingDatagrams) {
ComPtr<IDataReader> reader;
UINT32 unconsumedBufferLength;
arg->GetDataReader(&reader);
if (!reader)
return -1;
reader->get_UnconsumedBufferLength(&unconsumedBufferLength);
ret += unconsumedBufferLength;
}
return ret;
}
qint64 QNativeSocketEngine::bytesToWrite() const
{
return 0;
}
qint64 QNativeSocketEngine::receiveBufferSize() const
{
Q_D(const QNativeSocketEngine);
return d->option(QAbstractSocketEngine::ReceiveBufferSocketOption);
}
void QNativeSocketEngine::setReceiveBufferSize(qint64 bufferSize)
{
Q_D(QNativeSocketEngine);
d->setOption(QAbstractSocketEngine::ReceiveBufferSocketOption, bufferSize);
}
qint64 QNativeSocketEngine::sendBufferSize() const
{
Q_D(const QNativeSocketEngine);
return d->option(QAbstractSocketEngine::SendBufferSocketOption);
}
void QNativeSocketEngine::setSendBufferSize(qint64 bufferSize)
{
Q_D(QNativeSocketEngine);
d->setOption(QAbstractSocketEngine::SendBufferSocketOption, bufferSize);
}
int QNativeSocketEngine::option(QAbstractSocketEngine::SocketOption option) const
{
Q_D(const QNativeSocketEngine);
return d->option(option);
}
bool QNativeSocketEngine::setOption(QAbstractSocketEngine::SocketOption option, int value)
{
Q_D(QNativeSocketEngine);
return d->setOption(option, value);
}
bool QNativeSocketEngine::waitForRead(int msecs, bool *timedOut)
{
Q_D(QNativeSocketEngine);
Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::waitForRead(), false);
Q_CHECK_NOT_STATE(QNativeSocketEngine::waitForRead(),
QAbstractSocket::UnconnectedState, false);
if (timedOut)
*timedOut = false;
QElapsedTimer timer;
timer.start();
while (msecs > timer.elapsed()) {
// Servers with active connections are ready for reading
if (!d->currentConnections.isEmpty())
return true;
// If we are a client, we are ready to read if our buffer has data
QMutexLocker locker(&d->readMutex);
if (!d->readBytes.atEnd())
return true;
// Nothing to do, wait for more events
d->eventLoop.processEvents();
}
d->setError(QAbstractSocket::SocketTimeoutError,
QNativeSocketEnginePrivate::TimeOutErrorString);
if (timedOut)
*timedOut = true;
return false;
}
bool QNativeSocketEngine::waitForWrite(int msecs, bool *timedOut)
{
Q_UNUSED(msecs);
Q_UNUSED(timedOut);
return false;
}
bool QNativeSocketEngine::waitForReadOrWrite(bool *readyToRead, bool *readyToWrite, bool checkRead, bool checkWrite, int msecs, bool *timedOut)
{
Q_UNUSED(readyToRead);
Q_UNUSED(readyToWrite);
Q_UNUSED(checkRead);
Q_UNUSED(checkWrite);
Q_UNUSED(msecs);
Q_UNUSED(timedOut);
return false;
}
bool QNativeSocketEngine::isReadNotificationEnabled() const
{
Q_D(const QNativeSocketEngine);
return d->notifyOnRead;
}
void QNativeSocketEngine::setReadNotificationEnabled(bool enable)
{
Q_D(QNativeSocketEngine);
d->notifyOnRead = enable;
}
bool QNativeSocketEngine::isWriteNotificationEnabled() const
{
Q_D(const QNativeSocketEngine);
return d->notifyOnWrite;
}
void QNativeSocketEngine::setWriteNotificationEnabled(bool enable)
{
Q_D(QNativeSocketEngine);
d->notifyOnWrite = enable;
if (enable && d->socketState == QAbstractSocket::ConnectedState) {
if (bytesToWrite())
return; // will be emitted as a result of bytes written
writeNotification();
d->notifyOnWrite = false;
}
}
bool QNativeSocketEngine::isExceptionNotificationEnabled() const
{
Q_D(const QNativeSocketEngine);
return d->notifyOnException;
}
void QNativeSocketEngine::setExceptionNotificationEnabled(bool enable)
{
Q_D(QNativeSocketEngine);
d->notifyOnException = enable;
}
bool QNativeSocketEnginePrivate::createNewSocket(QAbstractSocket::SocketType socketType, QAbstractSocket::NetworkLayerProtocol &socketProtocol)
{
Q_UNUSED(socketProtocol);
SocketHandler *handler = gSocketHandler();
switch (socketType) {
case QAbstractSocket::TcpSocket: {
if (FAILED(RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_StreamSocket).Get(),
reinterpret_cast<IInspectable **>(&tcp)))) {
qWarning("Failed to create StreamSocket instance");
return false;
}
socketDescriptor = ++handler->socketCount;
return true;
}
case QAbstractSocket::UdpSocket: {
if (FAILED(RoActivateInstance(HString::MakeReference(RuntimeClass_Windows_Networking_Sockets_DatagramSocket).Get(),
reinterpret_cast<IInspectable **>(&udp)))) {
qWarning("Failed to create stream socket");
return false;
}
EventRegistrationToken token;
udp->add_MessageReceived(Callback<DatagramReceivedHandler>(this, &QNativeSocketEnginePrivate::handleNewDatagram).Get(), &token);
socketDescriptor = ++handler->socketCount;
return true;
}
default:
qWarning("Invalid socket type");
return false;
}
return false;
}
QNativeSocketEnginePrivate::QNativeSocketEnginePrivate()
: QAbstractSocketEnginePrivate()
, notifyOnRead(true)
, notifyOnWrite(true)
, notifyOnException(false)
, closingDown(false)
, socketDescriptor(-1)
{
ComPtr<ByteArrayBuffer> buffer = Make<ByteArrayBuffer>(READ_BUFFER_SIZE);
readBuffer = buffer;
}
QNativeSocketEnginePrivate::~QNativeSocketEnginePrivate()
{
}
void QNativeSocketEnginePrivate::setError(QAbstractSocket::SocketError error, ErrorString errorString) const
{
if (hasSetSocketError) {
// Only set socket errors once for one engine; expect the
// socket to recreate its engine after an error. Note: There's
// one exception: SocketError(11) bypasses this as it's purely
// a temporary internal error condition.
// Another exception is the way the waitFor*() functions set
// an error when a timeout occurs. After the call to setError()
// they reset the hasSetSocketError to false
return;
}
if (error != QAbstractSocket::SocketError(11))
hasSetSocketError = true;
socketError = error;
switch (errorString) {
case NonBlockingInitFailedErrorString:
socketErrorString = QNativeSocketEngine::tr("Unable to initialize non-blocking socket");
break;
case BroadcastingInitFailedErrorString:
socketErrorString = QNativeSocketEngine::tr("Unable to initialize broadcast socket");
break;
// should not happen anymore
case NoIpV6ErrorString:
socketErrorString = QNativeSocketEngine::tr("Attempt to use IPv6 socket on a platform with no IPv6 support");
break;
case RemoteHostClosedErrorString:
socketErrorString = QNativeSocketEngine::tr("The remote host closed the connection");
break;
case TimeOutErrorString:
socketErrorString = QNativeSocketEngine::tr("Network operation timed out");
break;
case ResourceErrorString:
socketErrorString = QNativeSocketEngine::tr("Out of resources");
break;
case OperationUnsupportedErrorString:
socketErrorString = QNativeSocketEngine::tr("Unsupported socket operation");
break;
case ProtocolUnsupportedErrorString:
socketErrorString = QNativeSocketEngine::tr("Protocol type not supported");
break;
case InvalidSocketErrorString:
socketErrorString = QNativeSocketEngine::tr("Invalid socket descriptor");
break;
case HostUnreachableErrorString:
socketErrorString = QNativeSocketEngine::tr("Host unreachable");
break;
case NetworkUnreachableErrorString:
socketErrorString = QNativeSocketEngine::tr("Network unreachable");
break;
case AccessErrorString:
socketErrorString = QNativeSocketEngine::tr("Permission denied");
break;
case ConnectionTimeOutErrorString:
socketErrorString = QNativeSocketEngine::tr("Connection timed out");
break;
case ConnectionRefusedErrorString:
socketErrorString = QNativeSocketEngine::tr("Connection refused");
break;
case AddressInuseErrorString:
socketErrorString = QNativeSocketEngine::tr("The bound address is already in use");
break;
case AddressNotAvailableErrorString:
socketErrorString = QNativeSocketEngine::tr("The address is not available");
break;
case AddressProtectedErrorString:
socketErrorString = QNativeSocketEngine::tr("The address is protected");
break;
case DatagramTooLargeErrorString:
socketErrorString = QNativeSocketEngine::tr("Datagram was too large to send");
break;
case SendDatagramErrorString:
socketErrorString = QNativeSocketEngine::tr("Unable to send a message");
break;
case ReceiveDatagramErrorString:
socketErrorString = QNativeSocketEngine::tr("Unable to receive a message");
break;
case WriteErrorString:
socketErrorString = QNativeSocketEngine::tr("Unable to write");
break;
case ReadErrorString:
socketErrorString = QNativeSocketEngine::tr("Network error");
break;
case PortInuseErrorString:
socketErrorString = QNativeSocketEngine::tr("Another socket is already listening on the same port");
break;
case NotSocketErrorString:
socketErrorString = QNativeSocketEngine::tr("Operation on non-socket");
break;
case InvalidProxyTypeString:
socketErrorString = QNativeSocketEngine::tr("The proxy type is invalid for this operation");
break;
case TemporaryErrorString:
socketErrorString = QNativeSocketEngine::tr("Temporary error");
break;
case UnknownSocketErrorString:
socketErrorString = QNativeSocketEngine::tr("Unknown error");
break;
}
}
int QNativeSocketEnginePrivate::option(QAbstractSocketEngine::SocketOption opt) const
{
ComPtr<IStreamSocketControl> control;
if (socketType == QAbstractSocket::TcpSocket) {
if (FAILED(tcp->get_Control(&control))) {
qWarning("QNativeSocketEnginePrivate::option: Could not obtain socket control");
return -1;
}
}
switch (opt) {
case QAbstractSocketEngine::NonBlockingSocketOption:
case QAbstractSocketEngine::BroadcastSocketOption:
case QAbstractSocketEngine::ReceiveOutOfBandData:
return 1;
case QAbstractSocketEngine::SendBufferSocketOption:
if (socketType == QAbstractSocket::UdpSocket)
return -1;
UINT32 bufferSize;
if (FAILED(control->get_OutboundBufferSizeInBytes(&bufferSize))) {
qWarning("Could not obtain OutboundBufferSizeInBytes information vom socket control");
return -1;
}
return bufferSize;
case QAbstractSocketEngine::LowDelayOption:
if (socketType == QAbstractSocket::UdpSocket)
return -1;
boolean noDelay;
if (FAILED(control->get_NoDelay(&noDelay))) {
qWarning("Could not obtain NoDelay information from socket control");
return -1;
}
return noDelay;
case QAbstractSocketEngine::KeepAliveOption:
if (socketType == QAbstractSocket::UdpSocket)
return -1;
boolean keepAlive;
if (FAILED(control->get_KeepAlive(&keepAlive))) {
qWarning("Could not obtain KeepAlive information from socket control");
return -1;
}
return keepAlive;
case QAbstractSocketEngine::ReceiveBufferSocketOption:
case QAbstractSocketEngine::AddressReusable:
case QAbstractSocketEngine::BindExclusively:
case QAbstractSocketEngine::MulticastTtlOption:
case QAbstractSocketEngine::MulticastLoopbackOption:
case QAbstractSocketEngine::TypeOfServiceOption:
default:
return -1;
}
return -1;
}
bool QNativeSocketEnginePrivate::setOption(QAbstractSocketEngine::SocketOption opt, int v)
{
ComPtr<IStreamSocketControl> control;
if (socketType == QAbstractSocket::TcpSocket) {
if (FAILED(tcp->get_Control(&control))) {
qWarning("QNativeSocketEnginePrivate::setOption: Could not obtain socket control");
return false;
}
}
switch (opt) {
case QAbstractSocketEngine::NonBlockingSocketOption:
case QAbstractSocketEngine::BroadcastSocketOption:
case QAbstractSocketEngine::ReceiveOutOfBandData:
return v != 0;
case QAbstractSocketEngine::SendBufferSocketOption:
if (socketType == QAbstractSocket::UdpSocket)
return false;
if (FAILED(control->put_OutboundBufferSizeInBytes(v))) {
qWarning("Could not set OutboundBufferSizeInBytes");
return false;
}
return true;
case QAbstractSocketEngine::LowDelayOption: {
if (socketType == QAbstractSocket::UdpSocket)
return false;
boolean noDelay = v;
if (FAILED(control->put_NoDelay(noDelay))) {
qWarning("Could not obtain NoDelay information from socket control");
return false;
}
return true;
}
case QAbstractSocketEngine::KeepAliveOption: {
if (socketType == QAbstractSocket::UdpSocket)
return false;
boolean keepAlive = v;
if (FAILED(control->put_KeepAlive(keepAlive))) {
qWarning("Could not set KeepAlive value");
return false;
}
return true;
}
case QAbstractSocketEngine::ReceiveBufferSocketOption:
case QAbstractSocketEngine::AddressReusable:
case QAbstractSocketEngine::BindExclusively:
case QAbstractSocketEngine::MulticastTtlOption:
case QAbstractSocketEngine::MulticastLoopbackOption:
case QAbstractSocketEngine::TypeOfServiceOption:
default:
return false;
}
return false;
}
bool QNativeSocketEnginePrivate::fetchConnectionParameters()
{
localPort = 0;
localAddress.clear();
peerPort = 0;
peerAddress.clear();
if (socketType == QAbstractSocket::TcpSocket) {
ComPtr<IHostName> hostName;
HSTRING tmpHString;
ComPtr<IStreamSocketInformation> info;
if (FAILED(tcp->get_Information(&info))) {
qWarning("QNativeSocketEnginePrivate::fetchConnectionParameters: Could not obtain socket info");
return false;
}
info->get_LocalAddress(&hostName);
if (hostName) {
hostName->get_CanonicalName(&tmpHString);
localAddress.setAddress(qt_QStringFromHSTRING(tmpHString));
info->get_LocalPort(&tmpHString);
localPort = qt_QStringFromHSTRING(tmpHString).toInt();
}
if (!localPort && tcpListener) {
ComPtr<IStreamSocketListenerInformation> listenerInfo = 0;
tcpListener->get_Information(&listenerInfo);
listenerInfo->get_LocalPort(&tmpHString);
localPort = qt_QStringFromHSTRING(tmpHString).toInt();
localAddress == QHostAddress::Any;
}
info->get_RemoteAddress(&hostName);
if (hostName) {
hostName->get_CanonicalName(&tmpHString);
peerAddress.setAddress(qt_QStringFromHSTRING(tmpHString));
info->get_RemotePort(&tmpHString);
peerPort = qt_QStringFromHSTRING(tmpHString).toInt();
}
} else if (socketType == QAbstractSocket::UdpSocket) {
ComPtr<IHostName> hostName;
HSTRING tmpHString;
ComPtr<IDatagramSocketInformation> info;
if (FAILED(udp->get_Information(&info))) {
qWarning("QNativeSocketEnginePrivate::fetchConnectionParameters: Could not obtain socket information");
return false;
}
info->get_LocalAddress(&hostName);
if (hostName) {
hostName->get_CanonicalName(&tmpHString);
localAddress.setAddress(qt_QStringFromHSTRING(tmpHString));
info->get_LocalPort(&tmpHString);
localPort = qt_QStringFromHSTRING(tmpHString).toInt();
}
info->get_RemoteAddress(&hostName);
if (hostName) {
hostName->get_CanonicalName(&tmpHString);
peerAddress.setAddress(qt_QStringFromHSTRING(tmpHString));
info->get_RemotePort(&tmpHString);
peerPort = qt_QStringFromHSTRING(tmpHString).toInt();
}
}
return true;
}
HRESULT QNativeSocketEnginePrivate::handleBindCompleted(IAsyncAction *, AsyncStatus)
{
return S_OK;
}
HRESULT QNativeSocketEnginePrivate::handleClientConnection(IStreamSocketListener *listener, IStreamSocketListenerConnectionReceivedEventArgs *args)
{
Q_Q(QNativeSocketEngine);
Q_ASSERT(tcpListener.Get() == listener);
IStreamSocket *socket;
args->get_Socket(&socket);
pendingConnections.append(socket);
emit q->connectionReady();
emit q->readReady();
return S_OK;
}
HRESULT QNativeSocketEnginePrivate::handleConnectToHost(ABI::Windows::Foundation::IAsyncAction *, ABI::Windows::Foundation::AsyncStatus)
{
return S_OK;
}
HRESULT QNativeSocketEnginePrivate::handleReadyRead(IAsyncBufferOperation *asyncInfo, AsyncStatus status)
{
Q_Q(QNativeSocketEngine);
if (wasDeleted || isDeletingChildren)
return S_OK;
if (status == Error || status == Canceled)
return S_OK;
ByteArrayBuffer *buffer = 0;
HRESULT hr = asyncInfo->GetResults((IBuffer **)&buffer);
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to get ready read results.");
return S_OK;
}
UINT32 len;
buffer->get_Length(&len);
if (!len) {
if (q->isReadNotificationEnabled())
emit q->readReady();
return S_OK;
}
byte *data;
buffer->Buffer(&data);
readMutex.lock();
if (readBytes.atEnd()) // Everything has been read; the buffer is safe to reset
readBytes.close();
if (!readBytes.isOpen())
readBytes.open(QBuffer::ReadWrite|QBuffer::Truncate);
qint64 readPos = readBytes.pos();
readBytes.seek(readBytes.size());
Q_ASSERT(readBytes.atEnd());
readBytes.write(reinterpret_cast<const char*>(data), qint64(len));
readBytes.seek(readPos);
readMutex.unlock();
if (q->isReadNotificationEnabled())
emit q->readReady();
ComPtr<IAsyncBufferOperation> op;
hr = buffer->inputStream()->ReadAsync(buffer, READ_BUFFER_SIZE, InputStreamOptions_Partial, &op);
if (FAILED(hr)) {
qErrnoWarning(hr, "Could not read into socket stream buffer.");
return S_OK;
}
hr = op->put_Completed(Callback<SocketReadCompletedHandler>(this, &QNativeSocketEnginePrivate::handleReadyRead).Get());
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to set socket read callback.");
return S_OK;
}
return S_OK;
}
HRESULT QNativeSocketEnginePrivate::handleWriteCompleted(IAsyncOperationWithProgress<UINT32, UINT32> *op, AsyncStatus status)
{
if (status == Error) {
ComPtr<IAsyncInfo> info;
HRESULT hr = op->QueryInterface(IID_PPV_ARGS(&info));
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to cast operation.");
return S_OK;
}
HRESULT errorCode;
hr = info->get_ErrorCode(&errorCode);
if (FAILED(hr)) {
qErrnoWarning(hr, "Failed to get error code.");
return S_OK;
}
qErrnoWarning(errorCode, "A socket error occurred.");
return S_OK;
}
return S_OK;
}
HRESULT QNativeSocketEnginePrivate::handleNewDatagram(IDatagramSocket *socket, IDatagramSocketMessageReceivedEventArgs *args)
{
Q_Q(QNativeSocketEngine);
Q_ASSERT(udp == socket);
pendingDatagrams.append(args);
emit q->readReady();
return S_OK;
}
QT_END_NAMESPACE
| 34.537184 | 214 | 0.679349 | viewdy |
db1e9cd7074462148a47c8f5a29b528c7f62e25d | 8,577 | cxx | C++ | main/sfx2/source/control/querystatus.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sfx2/source/control/querystatus.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sfx2/source/control/querystatus.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#include <sfx2/querystatus.hxx>
#include <svl/poolitem.hxx>
#include <svl/eitem.hxx>
#include <svl/stritem.hxx>
#include <svl/intitem.hxx>
#include <svl/itemset.hxx>
#include <svtools/itemdel.hxx>
#include <svl/visitem.hxx>
#include <cppuhelper/weak.hxx>
#include <comphelper/processfactory.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/frame/status/ItemStatus.hpp>
#include <com/sun/star/frame/status/ItemState.hpp>
#include <com/sun/star/frame/status/Visibility.hpp>
using ::rtl::OUString;
using namespace ::cppu;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
class SfxQueryStatus_Impl : public ::com::sun::star::frame::XStatusListener ,
public ::com::sun::star::lang::XTypeProvider ,
public ::cppu::OWeakObject
{
public:
SFX_DECL_XINTERFACE_XTYPEPROVIDER
SfxQueryStatus_Impl( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& rDispatchProvider, sal_uInt16 nSlotId, const rtl::OUString& aCommand );
virtual ~SfxQueryStatus_Impl();
// Query method
SfxItemState QueryState( SfxPoolItem*& pPoolItem );
// XEventListener
virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException );
// XStatusListener
virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException );
private:
SfxQueryStatus_Impl( const SfxQueryStatus& );
SfxQueryStatus_Impl();
SfxQueryStatus_Impl& operator=( const SfxQueryStatus& );
sal_Bool m_bQueryInProgress;
SfxItemState m_eState;
SfxPoolItem* m_pItem;
sal_uInt16 m_nSlotID;
osl::Condition m_aCondition;
::com::sun::star::util::URL m_aCommand;
com::sun::star::uno::Reference< com::sun::star::frame::XDispatch > m_xDispatch;
};
SFX_IMPL_XINTERFACE_2( SfxQueryStatus_Impl, OWeakObject, ::com::sun::star::frame::XStatusListener, ::com::sun::star::lang::XEventListener )
SFX_IMPL_XTYPEPROVIDER_2( SfxQueryStatus_Impl, ::com::sun::star::frame::XStatusListener, ::com::sun::star::lang::XEventListener )
SfxQueryStatus_Impl::SfxQueryStatus_Impl( const Reference< XDispatchProvider >& rDispatchProvider, sal_uInt16 nSlotId, const OUString& rCommand ) :
cppu::OWeakObject(),
m_bQueryInProgress( sal_False ),
m_eState( SFX_ITEM_DISABLED ),
m_pItem( 0 ),
m_nSlotID( nSlotId )
{
m_aCommand.Complete = rCommand;
Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance(
rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), UNO_QUERY );
xTrans->parseStrict( m_aCommand );
if ( rDispatchProvider.is() )
m_xDispatch = rDispatchProvider->queryDispatch( m_aCommand, rtl::OUString(), 0 );
m_aCondition.reset();
}
SfxQueryStatus_Impl::~SfxQueryStatus_Impl()
{
}
void SAL_CALL SfxQueryStatus_Impl::disposing( const EventObject& )
throw( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
m_xDispatch.clear();
}
void SAL_CALL SfxQueryStatus_Impl::statusChanged( const FeatureStateEvent& rEvent)
throw( RuntimeException )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
m_pItem = NULL;
m_eState = SFX_ITEM_DISABLED;
if ( rEvent.IsEnabled )
{
m_eState = SFX_ITEM_AVAILABLE;
::com::sun::star::uno::Type pType = rEvent.State.getValueType();
if ( pType == ::getBooleanCppuType() )
{
sal_Bool bTemp = false;
rEvent.State >>= bTemp ;
m_pItem = new SfxBoolItem( m_nSlotID, bTemp );
}
else if ( pType == ::getCppuType((const sal_uInt16*)0) )
{
sal_uInt16 nTemp = 0;
rEvent.State >>= nTemp ;
m_pItem = new SfxUInt16Item( m_nSlotID, nTemp );
}
else if ( pType == ::getCppuType((const sal_uInt32*)0) )
{
sal_uInt32 nTemp = 0;
rEvent.State >>= nTemp ;
m_pItem = new SfxUInt32Item( m_nSlotID, nTemp );
}
else if ( pType == ::getCppuType((const ::rtl::OUString*)0) )
{
::rtl::OUString sTemp ;
rEvent.State >>= sTemp ;
m_pItem = new SfxStringItem( m_nSlotID, sTemp );
}
else if ( pType == ::getCppuType((const ::com::sun::star::frame::status::ItemStatus*)0) )
{
ItemStatus aItemStatus;
rEvent.State >>= aItemStatus;
m_eState = aItemStatus.State;
m_pItem = new SfxVoidItem( m_nSlotID );
}
else if ( pType == ::getCppuType((const ::com::sun::star::frame::status::Visibility*)0) )
{
Visibility aVisibilityStatus;
rEvent.State >>= aVisibilityStatus;
m_pItem = new SfxVisibilityItem( m_nSlotID, aVisibilityStatus.bVisible );
}
else
{
m_eState = SFX_ITEM_UNKNOWN;
m_pItem = new SfxVoidItem( m_nSlotID );
}
}
if ( m_pItem )
DeleteItemOnIdle( m_pItem );
try
{
m_aCondition.set();
m_xDispatch->removeStatusListener( Reference< XStatusListener >( static_cast< cppu::OWeakObject* >( this ), UNO_QUERY ),
m_aCommand );
}
catch ( Exception& )
{
}
}
// Query method
SfxItemState SfxQueryStatus_Impl::QueryState( SfxPoolItem*& rpPoolItem )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
if ( !m_bQueryInProgress )
{
m_pItem = NULL;
m_eState = SFX_ITEM_DISABLED;
if ( m_xDispatch.is() )
{
try
{
m_aCondition.reset();
m_bQueryInProgress = sal_True;
m_xDispatch->addStatusListener( Reference< XStatusListener >( static_cast< cppu::OWeakObject* >( this ), UNO_QUERY ),
m_aCommand );
}
catch ( Exception& )
{
m_aCondition.set();
}
}
else
m_aCondition.set();
}
m_aCondition.wait();
m_bQueryInProgress = sal_False;
rpPoolItem = m_pItem;
return m_eState;
}
//*************************************************************************
SfxQueryStatus::SfxQueryStatus( const Reference< XDispatchProvider >& rDispatchProvider, sal_uInt16 nSlotId, const OUString& rCommand )
{
m_pSfxQueryStatusImpl = new SfxQueryStatus_Impl( rDispatchProvider, nSlotId, rCommand );
m_xStatusListener = Reference< XStatusListener >(
static_cast< cppu::OWeakObject* >( m_pSfxQueryStatusImpl ),
UNO_QUERY );
}
SfxQueryStatus::~SfxQueryStatus()
{
}
SfxItemState SfxQueryStatus::QueryState( SfxPoolItem*& rpPoolItem )
{
::vos::OGuard aGuard( Application::GetSolarMutex() );
return m_pSfxQueryStatusImpl->QueryState( rpPoolItem );
}
| 36.037815 | 186 | 0.609187 | Grosskopf |
db209eb8ac7f14758ae5fc9be4943d235b4d43da | 4,342 | cpp | C++ | source/ham/softjoystick.cpp | Hypexion/HamSandwich | e5adb6b45d822cbef1be1a52d0ce51513dc24bc8 | [
"MIT"
] | 24 | 2019-05-12T12:03:21.000Z | 2022-03-30T01:05:46.000Z | source/ham/softjoystick.cpp | Hypexion/HamSandwich | e5adb6b45d822cbef1be1a52d0ce51513dc24bc8 | [
"MIT"
] | 6 | 2019-05-12T11:54:54.000Z | 2022-02-26T11:47:20.000Z | source/ham/softjoystick.cpp | Hypexion/HamSandwich | e5adb6b45d822cbef1be1a52d0ce51513dc24bc8 | [
"MIT"
] | 12 | 2019-05-12T13:48:57.000Z | 2022-02-25T15:25:24.000Z | #include "softjoystick.h"
#include "control.h"
#include <algorithm>
#include <math.h>
#include <SDL_image.h>
#ifndef M_PI
#define M_PI 3.1415926535897
#endif
static byte numButtons = 2;
static byte state = 0;
static byte taps = 0;
void SoftJoystickNumButtons(byte n) {
numButtons = std::max((byte) 1, std::min(n, (byte) 4));
}
byte SoftJoystickState() {
return state;
}
byte SoftJoystickTaps() {
byte w = taps;
taps = 0;
return w;
}
static inline bool rect_contains(const SDL_Rect &r, int x, int y) {
return r.x <= x && x < r.x + r.w && r.y <= y && y < r.y + r.h;
}
void Element::draw(SDL_Renderer* renderer) {
SDL_RenderCopy(renderer, tex, NULL, &rect);
}
SoftJoystick::SoftJoystick(MGLDraw* mgl) {
SDL_Renderer* renderer = mgl->renderer;
stick.tex = IMG_LoadTexture(renderer, "soft_stick.png");
trough.tex = IMG_LoadTexture(renderer, "soft_trough.png");
esc.tex = IMG_LoadTexture(renderer, "soft_esc.png");
keyboard.tex = IMG_LoadTexture(renderer, "soft_keyboard.png");
button[0].tex = IMG_LoadTexture(renderer, "soft_b1.png");
button[1].tex = IMG_LoadTexture(renderer, "soft_b2.png");
button[2].tex = IMG_LoadTexture(renderer, "soft_b3.png");
button[3].tex = IMG_LoadTexture(renderer, "soft_b4.png");
}
SoftJoystick::~SoftJoystick() {
}
void SoftJoystick::update(MGLDraw* mgl, float scale) {
int spare = (int)(mgl->winWidth - mgl->xRes * scale) / 2;
int right = mgl->winWidth - spare;
trough.rect = { 0, 0, 3 * spare, 3 * spare };
stick.rect = { 0, 0, 3 * spare, 3 * spare };
if (state & CONTROL_UP) stick.rect.y -= spare;
if (state & CONTROL_DN) stick.rect.y += spare;
if (state & CONTROL_LF) stick.rect.x -= spare;
if (state & CONTROL_RT) stick.rect.x += spare;
esc.rect = { right, mgl->winHeight - spare, spare, spare };
keyboard.rect = { right, mgl->winHeight - 2 * spare, spare, spare };
for (int i = 0; i < numButtons; ++i) {
button[i].rect = { right, i * spare, spare, spare };
}
}
void SoftJoystick::render(SDL_Renderer* renderer) {
stick.draw(renderer);
trough.draw(renderer);
esc.draw(renderer);
keyboard.draw(renderer);
for (int i = 0; i < numButtons; ++i) {
button[i].draw(renderer);
}
}
void SoftJoystick::handle_event(MGLDraw *mgl, const SDL_Event& e) {
if (e.type == SDL_FINGERDOWN) {
int x = (int)(e.tfinger.x * mgl->winWidth);
int y = (int)(e.tfinger.y * mgl->winHeight);
if (rect_contains(esc.rect, x, y)) {
mgl->lastKeyPressed = SDLK_ESCAPE;
} else if (rect_contains(keyboard.rect, x, y)) {
SDL_StartTextInput();
}
int bit = CONTROL_B1;
for (int i = 0; i < numButtons; ++i) {
if (rect_contains(button[i].rect, x, y)) {
fingerHeld[e.tfinger.fingerId] |= bit;
state |= bit;
taps |= bit;
}
bit *= 2;
}
}
if (e.type == SDL_FINGERDOWN || e.type == SDL_FINGERMOTION) {
int x = (int)(e.tfinger.x * mgl->winWidth);
int y = (int)(e.tfinger.y * mgl->winHeight);
if (rect_contains(trough.rect, x, y)) {
const int DEADZONE = 2048;
byte curState = 0;
int ax = (x - trough.rect.x - trough.rect.w / 2) * 32767 / trough.rect.w;
int ay = (y - trough.rect.y - trough.rect.h / 2) * 32767 / trough.rect.h;
if (ax * ax + ay * ay >= DEADZONE * DEADZONE) {
double angle = atan2(ay, ax) * 180.0 / M_PI;
if (angle < 22.5 + -4*45) {
curState = CONTROL_LF;
} else if (angle < 22.5 + -3*45) {
curState = CONTROL_LF | CONTROL_UP;
} else if (angle < 22.5 + -2*45) {
curState = CONTROL_UP;
} else if (angle < 22.5 + -1*45) {
curState = CONTROL_UP | CONTROL_RT;
} else if (angle < 22.5 + 0*45) {
curState = CONTROL_RT;
} else if (angle < 22.5 + 1*45) {
curState = CONTROL_RT | CONTROL_DN;
} else if (angle < 22.5 + 2*45) {
curState = CONTROL_DN;
} else if (angle < 22.5 + 3*45) {
curState = CONTROL_DN | CONTROL_LF;
} else if (angle < 22.5 + 4*45) {
curState = CONTROL_LF;
}
}
byte last = fingerHeld[e.tfinger.fingerId];
fingerHeld[e.tfinger.fingerId] = curState;
recalculate_state();
taps |= (curState & ~last);
}
}
if (e.type == SDL_FINGERUP) {
auto iter = fingerHeld.find(e.tfinger.fingerId);
if (iter != fingerHeld.end()) {
fingerHeld.erase(iter);
recalculate_state();
}
}
}
void SoftJoystick::recalculate_state() {
state = 0;
for (const auto& pair : fingerHeld) {
state |= pair.second;
}
}
| 27.656051 | 76 | 0.631506 | Hypexion |
db23cc892c19ff1989a737ffc99aea47d34fbd7d | 1,528 | hpp | C++ | src/lib/repository/extractor.hpp | bunsanorg/pm | 67300580a21591cf84d64f1239dd219659797dca | [
"Apache-2.0"
] | null | null | null | src/lib/repository/extractor.hpp | bunsanorg/pm | 67300580a21591cf84d64f1239dd219659797dca | [
"Apache-2.0"
] | 1 | 2015-02-12T10:02:56.000Z | 2015-02-12T10:02:56.000Z | src/lib/repository/extractor.hpp | bunsanorg/pm | 67300580a21591cf84d64f1239dd219659797dca | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "cache.hpp"
#include <bunsan/pm/repository.hpp>
#include <boost/noncopyable.hpp>
namespace bunsan {
namespace pm {
class repository::extractor : private boost::noncopyable {
public:
extractor(repository &self, const extract_config &config);
void extract(const entry &package,
const boost::filesystem::path &destination);
void install(const entry &package,
const boost::filesystem::path &destination);
void update(const entry &package, const boost::filesystem::path &destination);
bool need_update(const boost::filesystem::path &destination,
std::time_t lifetime);
/*!
* \note Will merge directories but will fail on file collisions
* \warning Will work only on the local_system_().tempdir_for_build()'s
* filesystem
*/
void extract_source(const entry &package, const std::string &source_id,
const boost::filesystem::path &destination);
void extract_build(const entry &package,
const boost::filesystem::path &destination);
void extract_installation(const entry &package,
const boost::filesystem::path &destination);
private:
static void merge_directories(const boost::filesystem::path &source,
const boost::filesystem::path &destination);
private:
cache &cache_();
local_system &local_system_();
private:
repository &m_self;
extract_config m_config;
};
} // namespace pm
} // namespace bunsan
| 27.285714 | 80 | 0.672775 | bunsanorg |
db23e629dce0b969ffcd105dca1bdd067ddad091 | 916 | cpp | C++ | DOJ/#843.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | null | null | null | DOJ/#843.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | 1 | 2021-11-18T15:10:29.000Z | 2021-11-20T07:13:31.000Z | DOJ/#843.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | null | null | null | /*
* @author Nickel_Angel (1239004072@qq.com)
* @copyright Copyright (c) 2022
*/
#include <algorithm>
#include <cstdio>
#include <cstring>
int n, a[5010], f[5010][5010];
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
scanf("%d", a + i);
std::sort(a + 1, a + n + 1);
for (int i = 1; i <= n; ++i)
{
for (int j = i + 1; j <= n; ++j)
f[i][j] = 2;
}
int ans = 2;
for (int i = 1, l, r; i <= n; ++i)
{
l = i - 1, r = i + 1;
while (l > 0 && r <= n)
{
if (1ll * a[l] + a[r] == 2ll * a[i])
{
f[i][r] = std::max(f[i][r], f[l][i] + 1);
ans = std::max(ans, f[i][r]);
++r;
}
else if (1ll * a[l] + a[r] > 2ll * a[i])
--l;
else
++r;
}
}
printf("%d\n", ans);
return 0;
} | 21.302326 | 57 | 0.340611 | Nickel-Angel |
db2650a172cad32216f4aade255039bee638bd03 | 882 | cc | C++ | src/experiment-prime-sieve/checked-basic.cc | D-iii-S/teaching-performance-evaluation | 090d04aca56e604ea685f9b2c1e036f5182572df | [
"Apache-2.0"
] | null | null | null | src/experiment-prime-sieve/checked-basic.cc | D-iii-S/teaching-performance-evaluation | 090d04aca56e604ea685f9b2c1e036f5182572df | [
"Apache-2.0"
] | null | null | null | src/experiment-prime-sieve/checked-basic.cc | D-iii-S/teaching-performance-evaluation | 090d04aca56e604ea685f9b2c1e036f5182572df | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#ifndef N
// By default consider about 150 million numbers.
#define N (1<<27)
#endif
bool can_be_prime [N];
int main () {
// Mark all numbers as potentially prime.
for (int i = 2 ; i < N ; i ++) {
can_be_prime [i] = true;
}
int primes = 0;
// Check numbers from smallest to largest.
for (int i = 2 ; i < N ; i ++) {
// Any number that is still marked
// as potentially prime is prime.
if (can_be_prime [i]) {
primes ++;
// All multiples of any prime are not prime.
for (int j = 2 * i ; j < N ; j += i) {
if (can_be_prime [j]) {
can_be_prime [j] = false;
}
}
}
}
std::cout << "Counted " << primes << " primes from " << 2 << " to " << N << "." << std::endl;
return (0);
}
| 23.210526 | 97 | 0.468254 | D-iii-S |
db270a141b74392659232fe28e05457c9045a780 | 20,260 | cc | C++ | content/browser/storage_partition_impl_map.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/storage_partition_impl_map.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/storage_partition_impl_map.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // 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 "content/browser/storage_partition_impl_map.h"
#include <unordered_set>
#include <utility>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "content/browser/appcache/chrome_appcache_service.h"
#include "content/browser/background_fetch/background_fetch_context.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/browser/code_cache/generated_code_cache_context.h"
#include "content/browser/cookie_store/cookie_store_context.h"
#include "content/browser/file_system/browser_file_system_helper.h"
#include "content/browser/loader/prefetch_url_loader_service.h"
#include "content/browser/resource_context_impl.h"
#include "content/browser/storage_partition_impl.h"
#include "content/browser/webui/url_data_manager_backend.h"
#include "content/common/service_worker/service_worker_utils.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "crypto/sha2.h"
#include "services/network/public/cpp/features.h"
#include "storage/browser/blob/blob_storage_context.h"
namespace content {
namespace {
// These constants are used to create the directory structure under the profile
// where renderers with a non-default storage partition keep their persistent
// state. This will contain a set of directories that partially mirror the
// directory structure of BrowserContext::GetPath().
//
// The kStoragePartitionDirname contains an extensions directory which is
// further partitioned by extension id, followed by another level of directories
// for the "default" extension storage partition and one directory for each
// persistent partition used by a webview tag. Example:
//
// Storage/ext/ABCDEF/def
// Storage/ext/ABCDEF/hash(partition name)
//
// The code in GetStoragePartitionPath() constructs these path names.
//
// TODO(nasko): Move extension related path code out of content.
const base::FilePath::CharType kStoragePartitionDirname[] =
FILE_PATH_LITERAL("Storage");
const base::FilePath::CharType kExtensionsDirname[] =
FILE_PATH_LITERAL("ext");
const base::FilePath::CharType kDefaultPartitionDirname[] =
FILE_PATH_LITERAL("def");
const base::FilePath::CharType kTrashDirname[] =
FILE_PATH_LITERAL("trash");
// Because partition names are user specified, they can be arbitrarily long
// which makes them unsuitable for paths names. We use a truncation of a
// SHA256 hash to perform a deterministic shortening of the string. The
// kPartitionNameHashBytes constant controls the length of the truncation.
// We use 6 bytes, which gives us 99.999% reliability against collisions over
// 1 million partition domains.
//
// Analysis:
// We assume that all partition names within one partition domain are
// controlled by the the same entity. Thus there is no chance for adverserial
// attack and all we care about is accidental collision. To get 5 9s over
// 1 million domains, we need the probability of a collision in any one domain
// to be
//
// p < nroot(1000000, .99999) ~= 10^-11
//
// We use the following birthday attack approximation to calculate the max
// number of unique names for this probability:
//
// n(p,H) = sqrt(2*H * ln(1/(1-p)))
//
// For a 6-byte hash, H = 2^(6*8). n(10^-11, H) ~= 75
//
// An average partition domain is likely to have less than 10 unique
// partition names which is far lower than 75.
//
// Note, that for 4 9s of reliability, the limit is 237 partition names per
// partition domain.
const int kPartitionNameHashBytes = 6;
// Needed for selecting all files in ObliterateOneDirectory() below.
#if defined(OS_POSIX)
const int kAllFileTypes = base::FileEnumerator::FILES |
base::FileEnumerator::DIRECTORIES |
base::FileEnumerator::SHOW_SYM_LINKS;
#else
const int kAllFileTypes = base::FileEnumerator::FILES |
base::FileEnumerator::DIRECTORIES;
#endif
base::FilePath GetStoragePartitionDomainPath(
const std::string& partition_domain) {
CHECK(base::IsStringUTF8(partition_domain));
return base::FilePath(kStoragePartitionDirname).Append(kExtensionsDirname)
.Append(base::FilePath::FromUTF8Unsafe(partition_domain));
}
// Helper function for doing a depth-first deletion of the data on disk.
// Examines paths directly in |current_dir| (no recursion) and tries to
// delete from disk anything that is in, or isn't a parent of something in
// |paths_to_keep|. Paths that need further expansion are added to
// |paths_to_consider|.
void ObliterateOneDirectory(const base::FilePath& current_dir,
const std::vector<base::FilePath>& paths_to_keep,
std::vector<base::FilePath>* paths_to_consider) {
CHECK(current_dir.IsAbsolute());
base::FileEnumerator enumerator(current_dir, false, kAllFileTypes);
for (base::FilePath to_delete = enumerator.Next(); !to_delete.empty();
to_delete = enumerator.Next()) {
// Enum tracking which of the 3 possible actions to take for |to_delete|.
enum { kSkip, kEnqueue, kDelete } action = kDelete;
for (auto to_keep = paths_to_keep.begin(); to_keep != paths_to_keep.end();
++to_keep) {
if (to_delete == *to_keep) {
action = kSkip;
break;
} else if (to_delete.IsParent(*to_keep)) {
// |to_delete| contains a path to keep. Add to stack for further
// processing.
action = kEnqueue;
break;
}
}
switch (action) {
case kDelete:
base::DeletePathRecursively(to_delete);
break;
case kEnqueue:
paths_to_consider->push_back(to_delete);
break;
case kSkip:
break;
}
}
}
// Synchronously attempts to delete |unnormalized_root|, preserving only
// entries in |paths_to_keep|. If there are no entries in |paths_to_keep| on
// disk, then it completely removes |unnormalized_root|. All paths must be
// absolute paths.
void BlockingObliteratePath(
const base::FilePath& unnormalized_browser_context_root,
const base::FilePath& unnormalized_root,
const std::vector<base::FilePath>& paths_to_keep,
const scoped_refptr<base::TaskRunner>& closure_runner,
base::OnceClosure on_gc_required) {
// Early exit required because MakeAbsoluteFilePath() will fail on POSIX
// if |unnormalized_root| does not exist. This is safe because there is
// nothing to do in this situation anwyays.
if (!base::PathExists(unnormalized_root)) {
return;
}
// Never try to obliterate things outside of the browser context root or the
// browser context root itself. Die hard.
base::FilePath root = base::MakeAbsoluteFilePath(unnormalized_root);
base::FilePath browser_context_root =
base::MakeAbsoluteFilePath(unnormalized_browser_context_root);
CHECK(!root.empty());
CHECK(!browser_context_root.empty());
CHECK(browser_context_root.IsParent(root) && browser_context_root != root);
// Reduce |paths_to_keep| set to those under the root and actually on disk.
std::vector<base::FilePath> valid_paths_to_keep;
for (auto it = paths_to_keep.begin(); it != paths_to_keep.end(); ++it) {
if (root.IsParent(*it) && base::PathExists(*it))
valid_paths_to_keep.push_back(*it);
}
// If none of the |paths_to_keep| are valid anymore then we just whack the
// root and be done with it. Otherwise, signal garbage collection and do
// a best-effort delete of the on-disk structures.
if (valid_paths_to_keep.empty()) {
base::DeletePathRecursively(root);
return;
}
closure_runner->PostTask(FROM_HERE, std::move(on_gc_required));
// Otherwise, start at the root and delete everything that is not in
// |valid_paths_to_keep|.
std::vector<base::FilePath> paths_to_consider;
paths_to_consider.push_back(root);
while(!paths_to_consider.empty()) {
base::FilePath path = paths_to_consider.back();
paths_to_consider.pop_back();
ObliterateOneDirectory(path, valid_paths_to_keep, &paths_to_consider);
}
}
// Ensures each path in |active_paths| is a direct child of storage_root.
void NormalizeActivePaths(const base::FilePath& storage_root,
std::unordered_set<base::FilePath>* active_paths) {
std::unordered_set<base::FilePath> normalized_active_paths;
for (auto iter = active_paths->begin(); iter != active_paths->end(); ++iter) {
base::FilePath relative_path;
if (!storage_root.AppendRelativePath(*iter, &relative_path))
continue;
std::vector<base::FilePath::StringType> components;
relative_path.GetComponents(&components);
DCHECK(!relative_path.empty());
normalized_active_paths.insert(storage_root.Append(components.front()));
}
active_paths->swap(normalized_active_paths);
}
// Deletes all entries inside the |storage_root| that are not in the
// |active_paths|. Deletion is done in 2 steps:
//
// (1) Moving all garbage collected paths into a trash directory.
// (2) Asynchronously deleting the trash directory.
//
// The deletion is asynchronous because after (1) completes, calling code can
// safely continue to use the paths that had just been garbage collected
// without fear of race conditions.
//
// This code also ignores failed moves rather than attempting a smarter retry.
// Moves shouldn't fail here unless there is some out-of-band error (eg.,
// FS corruption). Retry logic is dangerous in the general case because
// there is not necessarily a guaranteed case where the logic may succeed.
//
// This function is still named BlockingGarbageCollect() because it does
// execute a few filesystem operations synchronously.
void BlockingGarbageCollect(
const base::FilePath& storage_root,
const scoped_refptr<base::TaskRunner>& file_access_runner,
std::unique_ptr<std::unordered_set<base::FilePath>> active_paths) {
CHECK(storage_root.IsAbsolute());
NormalizeActivePaths(storage_root, active_paths.get());
base::FileEnumerator enumerator(storage_root, false, kAllFileTypes);
base::FilePath trash_directory;
if (!base::CreateTemporaryDirInDir(storage_root, kTrashDirname,
&trash_directory)) {
// Unable to continue without creating the trash directory so give up.
return;
}
for (base::FilePath path = enumerator.Next(); !path.empty();
path = enumerator.Next()) {
if (active_paths->find(path) == active_paths->end() &&
path != trash_directory) {
// Since |trash_directory| is unique for each run of this function there
// can be no colllisions on the move.
base::Move(path, trash_directory.Append(path.BaseName()));
}
}
file_access_runner->PostTask(
FROM_HERE, base::BindOnce(base::GetDeletePathRecursivelyCallback(),
trash_directory));
}
} // namespace
// static
base::FilePath StoragePartitionImplMap::GetStoragePartitionPath(
const std::string& partition_domain,
const std::string& partition_name) {
if (partition_domain.empty())
return base::FilePath();
base::FilePath path = GetStoragePartitionDomainPath(partition_domain);
// TODO(ajwong): Mangle in-memory into this somehow, either by putting
// it into the partition_name, or by manually adding another path component
// here. Otherwise, it's possible to have an in-memory StoragePartition and
// a persistent one that return the same FilePath for GetPath().
if (!partition_name.empty()) {
// For analysis of why we can ignore collisions, see the comment above
// kPartitionNameHashBytes.
char buffer[kPartitionNameHashBytes];
crypto::SHA256HashString(partition_name, &buffer[0],
sizeof(buffer));
return path.AppendASCII(base::HexEncode(buffer, sizeof(buffer)));
}
return path.Append(kDefaultPartitionDirname);
}
StoragePartitionImplMap::StoragePartitionImplMap(
BrowserContext* browser_context)
: browser_context_(browser_context),
file_access_runner_(base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::BEST_EFFORT})),
resource_context_initialized_(false) {}
StoragePartitionImplMap::~StoragePartitionImplMap() {
}
StoragePartitionImpl* StoragePartitionImplMap::Get(
const StoragePartitionConfig& partition_config,
bool can_create) {
// Find the previously created partition if it's available.
PartitionMap::const_iterator it = partitions_.find(partition_config);
if (it != partitions_.end())
return it->second.get();
if (!can_create)
return nullptr;
base::FilePath relative_partition_path = GetStoragePartitionPath(
partition_config.partition_domain(), partition_config.partition_name());
std::unique_ptr<StoragePartitionImpl> partition_ptr(
StoragePartitionImpl::Create(
browser_context_, partition_config.in_memory(),
relative_partition_path, partition_config.partition_domain()));
StoragePartitionImpl* partition = partition_ptr.get();
partitions_[partition_config] = std::move(partition_ptr);
partition->Initialize();
// Arm the serviceworker cookie change observation API.
partition->GetCookieStoreContext()->ListenToCookieChanges(
partition->GetNetworkContext(), /*success_callback=*/base::DoNothing());
PostCreateInitialization(partition, partition_config.in_memory());
return partition;
}
void StoragePartitionImplMap::AsyncObliterate(
const std::string& partition_domain,
base::OnceClosure on_gc_required) {
// Find the active partitions for the domain. Because these partitions are
// active, it is not possible to just delete the directories that contain
// the backing data structures without causing the browser to crash. Instead,
// of deleteing the directory, we tell each storage context later to
// remove any data they have saved. This will leave the directory structure
// intact but it will only contain empty databases.
std::vector<StoragePartitionImpl*> active_partitions;
std::vector<base::FilePath> paths_to_keep;
for (PartitionMap::const_iterator it = partitions_.begin();
it != partitions_.end();
++it) {
const StoragePartitionConfig& config = it->first;
if (config.partition_domain() == partition_domain) {
it->second->ClearData(
// All except shader cache.
~StoragePartition::REMOVE_DATA_MASK_SHADER_CACHE,
StoragePartition::QUOTA_MANAGED_STORAGE_MASK_ALL, GURL(),
base::Time(), base::Time::Max(), base::DoNothing());
if (!config.in_memory()) {
paths_to_keep.push_back(it->second->GetPath());
}
}
}
// Start a best-effort delete of the on-disk storage excluding paths that are
// known to still be in use. This is to delete any previously created
// StoragePartition state that just happens to not have been used during this
// run of the browser.
base::FilePath domain_root = browser_context_->GetPath().Append(
GetStoragePartitionDomainPath(partition_domain));
base::ThreadPool::PostTask(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
base::BindOnce(&BlockingObliteratePath, browser_context_->GetPath(),
domain_root, paths_to_keep,
base::ThreadTaskRunnerHandle::Get(),
std::move(on_gc_required)));
}
void StoragePartitionImplMap::GarbageCollect(
std::unique_ptr<std::unordered_set<base::FilePath>> active_paths,
base::OnceClosure done) {
// Include all paths for current StoragePartitions in the active_paths since
// they cannot be deleted safely.
for (PartitionMap::const_iterator it = partitions_.begin();
it != partitions_.end();
++it) {
const StoragePartitionConfig& config = it->first;
if (!config.in_memory())
active_paths->insert(it->second->GetPath());
}
// Find the directory holding the StoragePartitions and delete everything in
// there that isn't considered active.
base::FilePath storage_root = browser_context_->GetPath().Append(
GetStoragePartitionDomainPath(std::string()));
file_access_runner_->PostTaskAndReply(
FROM_HERE,
base::BindOnce(&BlockingGarbageCollect, storage_root, file_access_runner_,
std::move(active_paths)),
std::move(done));
}
void StoragePartitionImplMap::ForEach(
BrowserContext::StoragePartitionCallback callback) {
for (PartitionMap::const_iterator it = partitions_.begin();
it != partitions_.end();
++it) {
callback.Run(it->second.get());
}
}
void StoragePartitionImplMap::PostCreateInitialization(
StoragePartitionImpl* partition,
bool in_memory) {
// TODO(ajwong): ResourceContexts no longer have any storage related state.
// We should move this into a place where it is called once per
// BrowserContext creation rather than piggybacking off the default context
// creation.
// Note: moving this into Get() before partitions_[] is set causes reentrency.
if (!resource_context_initialized_) {
resource_context_initialized_ = true;
InitializeResourceContext(browser_context_);
}
if (StoragePartition::IsAppCacheEnabled()) {
partition->GetAppCacheService()->Initialize(
in_memory ? base::FilePath()
: partition->GetPath().Append(kAppCacheDirname),
browser_context_, browser_context_->GetSpecialStoragePolicy());
}
// Check first to avoid memory leak in unittests.
if (BrowserThread::IsThreadInitialized(BrowserThread::IO)) {
partition->GetCacheStorageContext()->SetBlobParametersForCache(
ChromeBlobStorageContext::GetFor(browser_context_));
if (!ServiceWorkerContext::IsServiceWorkerOnUIEnabled()) {
GetIOThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(
&ServiceWorkerContextWrapper::InitializeResourceContext,
partition->GetServiceWorkerContext(),
browser_context_->GetResourceContext()));
}
// Use PostTask() instead of RunOrPostTaskOnThread() because not posting a
// task causes it to run before the CacheStorageManager has been
// initialized, and then CacheStorageContextImpl::CacheManager() ends up
// returning null instead of using the CrossSequenceCacheStorageManager in
// unit tests that don't use a real IO thread, violating the DCHECK in
// BackgroundFetchDataManager::InitializeOnCoreThread().
// TODO(crbug.com/960012): This workaround should be unnecessary after
// CacheStorage moves off the IO thread to the thread pool.
base::PostTask(
FROM_HERE, {ServiceWorkerContext::GetCoreThreadId()},
base::BindOnce(&BackgroundFetchContext::InitializeOnCoreThread,
partition->GetBackgroundFetchContext()));
// We do not call InitializeURLRequestContext() for media contexts because,
// other than the HTTP cache, the media contexts share the same backing
// objects as their associated "normal" request context. Thus, the previous
// call serves to initialize the media request context for this storage
// partition as well.
}
}
} // namespace content
| 41.178862 | 80 | 0.728776 | mghgroup |
db29cda31dbc086c00bb3bb8acdc96f447ff6164 | 2,456 | cpp | C++ | keysmappingdialog.cpp | HankHenshaw/Chip8Qt | 968e7505b26b653397c8708a2514acfe12d294a4 | [
"MIT"
] | null | null | null | keysmappingdialog.cpp | HankHenshaw/Chip8Qt | 968e7505b26b653397c8708a2514acfe12d294a4 | [
"MIT"
] | null | null | null | keysmappingdialog.cpp | HankHenshaw/Chip8Qt | 968e7505b26b653397c8708a2514acfe12d294a4 | [
"MIT"
] | null | null | null | #include "keysmappingdialog.h"
#include "ui_keysmappingdialog.h"
KeysMappingDialog::KeysMappingDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::KeysMappingDialog)
{
ui->setupUi(this);
this->setWindowTitle("Keys Options");
connect(ui->A_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->B_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->C_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->D_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->E_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->F_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->G_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->H_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->I_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->J_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->K_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->L_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->M_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->N_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->O_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
connect(ui->P_pushButton, &QPushButton::pressed, this, &KeysMappingDialog::slotKeysMapping);
}
KeysMappingDialog::~KeysMappingDialog()
{
delete ui;
}
void KeysMappingDialog::on_buttonBox_accepted()
{
accept();
}
void KeysMappingDialog::on_buttonBox_rejected()
{
reject();
}
void KeysMappingDialog::slotKeysMapping()
{
QChar keyChar = sender()->objectName().at(0);
keyNumber = keyChar.unicode() - 65;
qDebug() << "Button:" << keyChar;
emit signalSetKeyNumber(keyNumber);
}
void KeysMappingDialog::slotGetKey(Qt::Key key)
{
KeyMappingDialog dialog(key, this);
if(dialog.exec() == QDialog::Accepted)
{
qDebug() << "Ok";
emit signalSendNewKeyValue(keyNumber, dialog.getNewKeyValue());
}
}
| 39.612903 | 96 | 0.739414 | HankHenshaw |
db2af2c45c57222ebbd5ff6617da32adbbd1d55b | 1,604 | cpp | C++ | examples/std_parts/fixed.cpp | denkoken/fase | 05d995170d53539f122b1318c084c99ca71fd393 | [
"MIT"
] | 2 | 2019-03-18T10:49:26.000Z | 2019-05-27T09:44:05.000Z | examples/std_parts/fixed.cpp | denkoken/fase | 05d995170d53539f122b1318c084c99ca71fd393 | [
"MIT"
] | null | null | null | examples/std_parts/fixed.cpp | denkoken/fase | 05d995170d53539f122b1318c084c99ca71fd393 | [
"MIT"
] | 1 | 2021-01-13T05:30:42.000Z | 2021-01-13T05:30:42.000Z |
#include <fase2/fase.h>
#include <fase2/imgui_editor/imgui_editor.h>
#include <fase2/stdparts.h>
#include <string>
#include <vector>
#include "../extra_parts.h"
#include "../fase_gl_utils.h"
#include "funcs.h"
int main() {
// Create Fase instance with GUI editor
fase::Fase<fase::ImGuiEditor, fase::FixedPipelineParts, NFDParts> app;
std::vector<std::string> in_arg{"red", "green", "blue", "count"};
std::vector<std::string> out_arg{
"dst_red",
"dst_green",
"dst_blue",
};
auto api = app.newPipeline<float, float, float>("fixed", in_arg, out_arg)
.fix<float, float, float, float>();
auto hook = [&](std::vector<float>* bg_col) {
try {
if (!api) {
return; // "fixed" is deleted or something went wrong.
}
bg_col->resize(3);
auto [r, g, b] =
api(bg_col->at(0), bg_col->at(1), bg_col->at(2), 0.f);
r = r > 1.f ? r - 1.f : r;
g = g > 1.f ? g - 1.f : g;
b = b > 1.f ? b - 1.f : b;
bg_col->at(0) = r;
bg_col->at(1) = g;
bg_col->at(2) = b;
} catch (fase::TryToGetEmptyVariable&) {
}
};
AddNFDButtons(app, app);
// Create OpenGL window
GLFWwindow* window = InitOpenGL("GUI Editor Example");
if (!window) {
return 0;
}
// Initialize ImGui
InitImGui(window, "../third_party/imgui/misc/fonts/Cousine-Regular.ttf");
// Start main loop
RunRenderingLoop(window, app, hook);
return 0;
}
| 25.870968 | 77 | 0.524938 | denkoken |
db2b3ad9178c762b697722051647f74d045c27f5 | 2,196 | cpp | C++ | solutions/1198/memory_allocating.cpp | buptlxb/hihoCoder | 1995bdfda29d4dab98c002870ef0bc138bc37ce7 | [
"Apache-2.0"
] | 44 | 2016-05-11T06:41:14.000Z | 2021-12-20T13:45:41.000Z | solutions/1198/memory_allocating.cpp | buptlxb/hihoCoder | 1995bdfda29d4dab98c002870ef0bc138bc37ce7 | [
"Apache-2.0"
] | null | null | null | solutions/1198/memory_allocating.cpp | buptlxb/hihoCoder | 1995bdfda29d4dab98c002870ef0bc138bc37ce7 | [
"Apache-2.0"
] | 10 | 2016-06-25T08:55:20.000Z | 2018-07-06T05:52:53.000Z | #include <iostream>
#include <vector>
#include <cassert>
#include <algorithm>
using namespace std;
struct Chunk{
int key;
int length;
Chunk *prev;
Chunk *next;
Chunk(int k=0, int len=0) : key(k), length(len), prev(nullptr), next(nullptr) {}
} *head;
void init(int m)
{
Chunk *t = new Chunk(0, m);
t->next = new Chunk(-1, 0);
t->prev = new Chunk(-1, 0);
t->next->prev = t;
t->prev->next = t;
head = t->prev;
}
Chunk *find_empty(int len)
{
Chunk *p = head->next;
for (Chunk *p = head->next; p->key != -1; p = p->next) {
if (p->key == 0 && p->length >= len)
return p;
}
return nullptr;
}
void insert(Chunk *p, int key, int len)
{
assert(p->key == 0 && p->length >= len);
if (p->length == len)
p->key = key;
else {
Chunk *t = new Chunk(0, p->length-len);
t->prev = p;
t->next = p->next;
t->next->prev = t;
p->next = t;
p->key = key;
p->length = len;
}
}
void release(Chunk *p)
{
Chunk *t = p->prev;
if (t->key == 0) {
p->length += t->length;
p->prev = t->prev;
p->prev->next = p;
delete t;
}
t = p->next;
if (t->key == 0) {
p->length += t->length;
p->next = t->next;
p->next->prev = p;
delete t;
}
p->key = 0;
}
int main(void)
{
int n, m;
cin >> n >> m;
init(m);
vector<Chunk *> pos(n+1);
for (int i = 1, last = 1; i <= n; ++i) {
int k;
cin >> k;
while (true) {
Chunk *p = find_empty(k);
if (p) {
insert(p, i, k);
pos[i] = p;
break;
} else {
release(pos[last]);
pos[last++] = nullptr;
}
}
}
vector<pair<int, int>> res;
int last = 0;
for (Chunk *p = head->next; p->key != -1; p = p->next) {
if (p->key)
res.push_back(make_pair(p->key, last));
last += p->length;
}
sort(res.begin(), res.end());
for (auto &pr : res)
cout << pr.first << " " << pr.second << '\n';
cout << flush;
return 0;
}
| 20.523364 | 84 | 0.435337 | buptlxb |
db2b633908571f8cbac6a03474dfd7c0878540d1 | 4,816 | cpp | C++ | core/ir/Input.cpp | p1x31/TRTorch | f99a6ca763eb08982e8b7172eb948a090bcbf11c | [
"BSD-3-Clause"
] | 944 | 2020-03-13T22:50:32.000Z | 2021-11-09T05:39:28.000Z | core/ir/Input.cpp | p1x31/TRTorch | f99a6ca763eb08982e8b7172eb948a090bcbf11c | [
"BSD-3-Clause"
] | 434 | 2020-03-18T03:00:29.000Z | 2021-11-09T00:26:36.000Z | core/ir/Input.cpp | p1x31/TRTorch | f99a6ca763eb08982e8b7172eb948a090bcbf11c | [
"BSD-3-Clause"
] | 106 | 2020-03-18T02:20:21.000Z | 2021-11-08T18:58:58.000Z | #include "core/ir/ir.h"
#include "core/util/prelude.h"
namespace trtorch {
namespace core {
namespace ir {
bool valid_dtype_format_combo(nvinfer1::DataType dtype, nvinfer1::TensorFormat format) {
switch (dtype) {
case nvinfer1::DataType::kINT8: // Supports just Linear (NCHW)
switch (format) {
case nvinfer1::TensorFormat::kLINEAR:
return true;
case nvinfer1::TensorFormat::kHWC:
default:
return false;
}
case nvinfer1::DataType::kINT32: // Supports just Linear (NCHW)
switch (format) {
case nvinfer1::TensorFormat::kLINEAR:
return true;
case nvinfer1::TensorFormat::kHWC:
default:
return false;
}
case nvinfer1::DataType::kHALF: // Supports just Linear (NCHW)
switch (format) {
case nvinfer1::TensorFormat::kLINEAR:
return true;
case nvinfer1::TensorFormat::kHWC:
default:
return false;
}
case nvinfer1::DataType::kFLOAT: // Supports both Linear (NCHW) and channel last (NHWC)
switch (format) {
case nvinfer1::TensorFormat::kLINEAR:
return true;
case nvinfer1::TensorFormat::kHWC:
return true;
default:
return false;
}
default:
return false;
}
}
bool valid_input_dtype(nvinfer1::DataType dtype) {
switch (dtype) {
case nvinfer1::DataType::kBOOL:
return false;
case nvinfer1::DataType::kFLOAT:
return true;
case nvinfer1::DataType::kHALF:
return true;
case nvinfer1::DataType::kINT8:
return true;
case nvinfer1::DataType::kINT32:
return true;
default:
return false;
}
}
Input::Input(
std::vector<int64_t> shape,
nvinfer1::DataType dtype,
nvinfer1::TensorFormat format,
bool dtype_is_user_defined) {
if (shape.size() > 5) {
LOG_WARNING("Verify that this dim size is accepted");
}
opt = util::toDims(shape);
min = util::toDims(shape);
max = util::toDims(shape);
input_shape = util::toDims(shape);
input_is_dynamic = false;
TRTORCH_CHECK(valid_input_dtype(dtype), "Unsupported input data type: " << dtype);
this->dtype = dtype;
TRTORCH_CHECK(
valid_dtype_format_combo(dtype, format),
"Unsupported combination of dtype and tensor format: ("
<< dtype << ", " << format
<< "), TRTorch only supports contiguous format (NCHW) except with input type Float32 where channel last (NHWC) is also supported");
this->format = format;
this->dtype_is_user_defined = dtype_is_user_defined;
}
Input::Input(
std::vector<int64_t> min_shape,
std::vector<int64_t> opt_shape,
std::vector<int64_t> max_shape,
nvinfer1::DataType dtype,
nvinfer1::TensorFormat format,
bool dtype_is_user_defined) {
if (min_shape.size() > 5 || opt_shape.size() > 5 || max_shape.size() > 5) {
LOG_WARNING("Verify that this dim size is accepted");
}
std::set<size_t> sizes;
sizes.insert(min_shape.size());
sizes.insert(opt_shape.size());
sizes.insert(max_shape.size());
if (sizes.size() != 1) {
LOG_ERROR(
"Expected all input sizes have the same dimensions, but found dimensions: min("
<< min_shape.size() << "), opt(" << opt_shape.size() << "), max(" << max_shape.size() << ")");
}
min = util::toDims(min_shape);
opt = util::toDims(opt_shape);
max = util::toDims(max_shape);
std::vector<int64_t> dyn_shape;
for (size_t i = 0; i < opt_shape.size(); i++) {
std::set<uint64_t> dim;
dim.insert(min_shape[i]);
dim.insert(opt_shape[i]);
dim.insert(max_shape[i]);
if (dim.size() != 1) {
dyn_shape.push_back(-1);
input_is_dynamic = true;
} else {
dyn_shape.push_back(opt_shape[i]);
}
}
input_shape = util::toDims(dyn_shape);
TRTORCH_CHECK(valid_input_dtype(dtype), "Unsupported input data type: " << dtype);
this->dtype = dtype;
TRTORCH_CHECK(
valid_dtype_format_combo(dtype, format),
"Unsupported combination of dtype and tensor format: ("
<< dtype << ", " << format
<< "), TRTorch only supports contiguous format (NCHW) except with input type Float32 where channel last (NHWC) is also supported");
this->format = format;
this->dtype_is_user_defined = dtype_is_user_defined;
}
std::ostream& operator<<(std::ostream& os, const Input& input) {
if (!input.input_is_dynamic) {
os << "Input(shape: " << input.input_shape << ", dtype: " << input.dtype << ", format: " << input.format << ')';
} else {
os << "Input(shape: " << input.input_shape << ", min: " << input.min << ", opt: " << input.opt
<< ", max: " << input.max << ", dtype: " << input.dtype << ", format: " << input.format << ')';
}
return os;
}
} // namespace ir
} // namespace core
} // namespace trtorch | 30.871795 | 141 | 0.628322 | p1x31 |
db2ce47578fab663169f7642a491179678fadcf2 | 361 | cpp | C++ | 2018/src/j1.cpp | Kytabyte/CCC | 6f98e81c7fef38bf70e68188db38863cc0cba2f4 | [
"Apache-2.0"
] | 8 | 2020-12-13T01:29:14.000Z | 2022-02-15T09:02:27.000Z | 2018/src/j1.cpp | Kytabyte/CCC | 6f98e81c7fef38bf70e68188db38863cc0cba2f4 | [
"Apache-2.0"
] | null | null | null | 2018/src/j1.cpp | Kytabyte/CCC | 6f98e81c7fef38bf70e68188db38863cc0cba2f4 | [
"Apache-2.0"
] | 2 | 2021-02-05T19:59:33.000Z | 2021-09-14T23:25:52.000Z | #include <bits/stdc++.h>
using namespace std;
/**
* Marks: 15/15
*/
int digits[4];
int main() {
for (int i = 0; i < 4; i++) {
scanf("%d", &digits[i]);
}
if (digits[0] != 8 && digits[0] != 9 || digits[3] != 8 && digits[3] != 9 || digits[1] != digits[2]) {
cout << "answer" << endl;
} else {
cout << "ignore" << endl;
}
return 0;
} | 15.695652 | 103 | 0.470914 | Kytabyte |
db2f038fba09c6f17406382ca0b25affad1a7e03 | 797 | cpp | C++ | Merge Nodes in Between Zeros.cpp | dishanp/Coding-In-C-and-C- | 889985ac136826cf9be88d6c5455f79fd805a069 | [
"BSD-2-Clause"
] | 2 | 2021-10-01T04:20:04.000Z | 2021-10-01T04:20:06.000Z | Merge Nodes in Between Zeros.cpp | dishanp/Coding-In-C-and-C- | 889985ac136826cf9be88d6c5455f79fd805a069 | [
"BSD-2-Clause"
] | null | null | null | Merge Nodes in Between Zeros.cpp | dishanp/Coding-In-C-and-C- | 889985ac136826cf9be88d6c5455f79fd805a069 | [
"BSD-2-Clause"
] | 8 | 2021-10-01T04:20:38.000Z | 2022-03-19T17:05:05.000Z | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeNodes(ListNode* head) {
ListNode* p=head;
p=p->next;
ListNode* l=new ListNode(0);
ListNode* res=l;
int sum=0;
while(p){
if(p->val!=0)
{
sum+=p->val;
}
else{
ListNode* temp=new ListNode(sum);
l->next=temp;
l=l->next;
sum=0;
}
p=p->next;
}
return res->next;
}
};
| 22.771429 | 62 | 0.430364 | dishanp |
db2f6ebce9b568be81e7fa60d41c9646f0761a96 | 3,627 | cpp | C++ | app/main.cpp | KPO-2020-2021/zad4-KrystianCyga | f055e0f13052646f8b55bc6a4b1f94ebce9db84a | [
"Unlicense"
] | null | null | null | app/main.cpp | KPO-2020-2021/zad4-KrystianCyga | f055e0f13052646f8b55bc6a4b1f94ebce9db84a | [
"Unlicense"
] | null | null | null | app/main.cpp | KPO-2020-2021/zad4-KrystianCyga | f055e0f13052646f8b55bc6a4b1f94ebce9db84a | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <fstream>
#include "vector.hh"
#include "matrix.hh"
#include "Prostopadloscian.hh"
#include "lacze_do_gnuplota.hh"
#include <string>
#include <unistd.h>
#include <stdlib.h>
Vector<double, 3> VecPrzesu;
Matrix<3> MROT;
Prostopadloscian<double> cuboid;
PzG::LaczeDoGNUPlota Lacze;
void menu();
int main()
{
if (!cuboid.wczytaj("../datasets/orginalny.dat"))
{
std::cerr << "Nie udalo sie wczytac prostopadloscianu!!!\n";
}
cuboid.boki();
cuboid.zapis("../datasets/anim.dat");
Lacze.DodajNazwePliku("../datasets/anim.dat", PzG::RR_Ciagly, 2);
Lacze.ZmienTrybRys(PzG::TR_3D);
Lacze.UstawZakresY(-155, 155);
Lacze.UstawZakresX(-155, 155);
Lacze.UstawZakresZ(-155, 155);
Lacze.Rysuj();
std::cout << "Naciśnij ENTER, aby kontynuowac" << std::endl;
std::cin.ignore(10000, '\n');
menu();
}
void menu()
{
char wyb;
std::cout << "\n"
<< "************************MENU************************\n";
std::cout << " o-obrot bryly o zadany kat wzgledem danej osi\n";
std::cout << " p-przesuniecie o dany wektor\n";
std::cout << " w-wyswietlenie wspolrzednych wierzcholkow\n";
std::cout << " m-powrot do menu\n";
std::cout << " k-koniec dzialania programu\n";
std::cout << " r-Rysuj prostokat w Gnuplocie\n";
std::cout << " t-wyswietlenie macierzy rotacji\n";
std::cout << " Twoj wybor -> :";
std::cin >> wyb;
std::cout << "\n";
switch (wyb)
{
case 'o':
char os;
double kat, ilosc;
std::cout << "Podaj kat obrotu: ";
std::cin >> kat;
std::cout << "Podaj ilosc operacji: ";
std::cin >> ilosc;
std::cout << "Podaj os operacji: ";
std::cin >> os;
MROT.Mobrot3D_tworzenie(kat, os);
if (ilosc > 1 && ilosc <= 720)
{
Lacze.Rysuj();
usleep(2000000);
for (int i = 0; i < ilosc; i++)
{
cuboid.obrot(kat, 1, os);
cuboid.zapis("../datasets/anim.dat");
Lacze.Rysuj();
int czas = 10000000 / ilosc;
usleep(czas);
}
}
else
{
cuboid.obrot(kat, ilosc, os);
cuboid.zapis("../datasets/anim.dat");
Lacze.Rysuj();
}
break;
case 'p':
std::cout << "Podaj wektor przesuniecia (x) (y) (z): ";
std::cin >> VecPrzesu;
cuboid.owektor(VecPrzesu);
std::cout << cuboid;
break;
case 'w':
std::cout << cuboid;
break;
case 'r':
cuboid.boki();
cuboid.zapis("../datasets/anim.dat");
Lacze.Rysuj();
break;
case 't':
std::cout << MROT;
break;
case 'm':
return menu();
break;
case 'k':
std::cout << "Koniec dzialania programu.\n ";
return;
break;
default:
std::cout << "Zly wybor !!! \n";
std::cout << "Mozliwe to o,r,p,w,m,k,t\n";
break;
}
return menu();
}
| 25.723404 | 77 | 0.435897 | KPO-2020-2021 |
db3228a6c5035e62578eb8bff186b13d000858bf | 1,746 | cpp | C++ | main.cpp | CaptainDreamcast/Torchbearer | 144a1d8eca66e994dc832fc4116431ea267e00d9 | [
"MIT"
] | null | null | null | main.cpp | CaptainDreamcast/Torchbearer | 144a1d8eca66e994dc832fc4116431ea267e00d9 | [
"MIT"
] | null | null | null | main.cpp | CaptainDreamcast/Torchbearer | 144a1d8eca66e994dc832fc4116431ea267e00d9 | [
"MIT"
] | null | null | null | #include <prism/framerateselectscreen.h>
#include <prism/physics.h>
#include <prism/file.h>
#include <prism/drawing.h>
#include <prism/log.h>
#include <prism/wrapper.h>
#include <prism/system.h>
#include <prism/stagehandler.h>
#include <prism/logoscreen.h>
#include <prism/mugentexthandler.h>
#include <prism/debug.h>
#include "gamescreen.h"
#include "datingscreen.h"
#include "bars.h"
#include "storyhandler.h"
#include "storyscreen.h"
#ifdef DREAMCAST
KOS_INIT_FLAGS(INIT_DEFAULT);
extern uint8 romdisk[];
KOS_INIT_ROMDISK(romdisk);
#endif
// #define DEVELOP
void exitGame() {
shutdownPrismWrapper();
#ifdef DEVELOP
if (isOnDreamcast()) {
abortSystem();
}
else {
returnToMenu();
}
#else
returnToMenu();
#endif
}
int main(int argc, char** argv) {
(void)argc;
(void)argv;
#ifdef DEVELOP
setDevelopMode();
#endif
setGameName("OlympicTorchCarrier");
setScreenSize(320, 240);
initPrismWrapperWithConfigFile("data/config.cfg");
setFont("$/rd/fonts/segoe.hdr", "$/rd/fonts/segoe.pkg");
addMugenFont(-1, "font/f4x6.fnt");
addMugenFont(1, "font/f6x9.fnt");
addMugenFont(2, "font/jg.fnt");
logg("Check framerate");
FramerateSelectReturnType framerateReturnType = selectFramerate();
if (framerateReturnType == FRAMERATE_SCREEN_RETURN_ABORT) {
exitGame();
}
if(isInDevelopMode()) {
ScreenSize sz = getScreenSize();
// setDisplayedScreenSize(sz.x, sz.y);
disableWrapperErrorRecovery();
setMinimumLogType(LOG_TYPE_NORMAL);
}
else {
setMinimumLogType(LOG_TYPE_NONE);
}
resetBarValues();
setScreenAfterWrapperLogoScreen(getLogoScreenFromWrapper());
setStoryHandlerPath("story/1.def");
setCurrentStoryDefinitionFile("INTRO");
startScreenHandling(getStoryScreen());
exitGame();
return 0;
}
| 19.186813 | 67 | 0.733677 | CaptainDreamcast |
db350e521c24fa8ca7fb1151352bcd20dfb7d855 | 9,610 | cc | C++ | chrome/browser/history/shortcuts_backend.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2016-03-10T09:13:57.000Z | 2016-03-10T09:13:57.000Z | chrome/browser/history/shortcuts_backend.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"BSD-3-Clause"
] | 1 | 2022-03-13T08:39:05.000Z | 2022-03-13T08:39:05.000Z | chrome/browser/history/shortcuts_backend.cc | gavinp/chromium | 681563ea0f892a051f4ef3d5e53438e0bb7d2261 | [
"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/history/shortcuts_backend.h"
#include <map>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/i18n/case_conversion.h"
#include "base/string_util.h"
#include "chrome/browser/autocomplete/autocomplete.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/history/history_notifications.h"
#include "chrome/browser/history/shortcuts_database.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/guid.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
using content::BrowserThread;
namespace {
// Takes Match classification vector and removes all matched positions,
// compacting repetitions if necessary.
void StripMatchMarkersFromClassifications(ACMatchClassifications* matches) {
DCHECK(matches);
ACMatchClassifications unmatched;
for (ACMatchClassifications::iterator i = matches->begin();
i != matches->end(); ++i) {
AutocompleteMatch::AddLastClassificationIfNecessary(&unmatched, i->offset,
i->style & ~ACMatchClassification::MATCH);
}
matches->swap(unmatched);
}
} // namespace
namespace history {
// ShortcutsBackend::Shortcut -------------------------------------------------
ShortcutsBackend::Shortcut::Shortcut(
const std::string& id,
const string16& text,
const GURL& url,
const string16& contents,
const ACMatchClassifications& contents_class,
const string16& description,
const ACMatchClassifications& description_class,
const base::Time& last_access_time,
int number_of_hits)
: id(id),
text(text),
url(url),
contents(contents),
contents_class(contents_class),
description(description),
description_class(description_class),
last_access_time(last_access_time),
number_of_hits(number_of_hits) {
StripMatchMarkersFromClassifications(&this->contents_class);
StripMatchMarkersFromClassifications(&this->description_class);
}
ShortcutsBackend::Shortcut::Shortcut()
: last_access_time(base::Time::Now()),
number_of_hits(0) {
}
ShortcutsBackend::Shortcut::~Shortcut() {
}
// ShortcutsBackend -----------------------------------------------------------
ShortcutsBackend::ShortcutsBackend(const FilePath& db_folder_path,
Profile *profile)
: current_state_(NOT_INITIALIZED),
db_(new ShortcutsDatabase(db_folder_path)),
no_db_access_(db_folder_path.empty()) {
// |profile| can be NULL in tests.
if (profile) {
notification_registrar_.Add(this, chrome::NOTIFICATION_OMNIBOX_OPENED_URL,
content::Source<Profile>(profile));
notification_registrar_.Add(this, chrome::NOTIFICATION_HISTORY_URLS_DELETED,
content::Source<Profile>(profile));
}
}
ShortcutsBackend::~ShortcutsBackend() {}
bool ShortcutsBackend::Init() {
if (current_state_ != NOT_INITIALIZED)
return false;
if (no_db_access_) {
current_state_ = INITIALIZED;
return true;
}
current_state_ = INITIALIZING;
return BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
base::Bind(&ShortcutsBackend::InitInternal, this));
}
bool ShortcutsBackend::AddShortcut(const Shortcut& shortcut) {
if (!initialized())
return false;
DCHECK(guid_map_.find(shortcut.id) == guid_map_.end());
guid_map_[shortcut.id] = shortcuts_map_.insert(
std::make_pair(base::i18n::ToLower(shortcut.text), shortcut));
FOR_EACH_OBSERVER(ShortcutsBackendObserver, observer_list_,
OnShortcutsChanged());
return no_db_access_ || BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
base::Bind(base::IgnoreResult(&ShortcutsDatabase::AddShortcut),
db_.get(), shortcut));
}
bool ShortcutsBackend::UpdateShortcut(const Shortcut& shortcut) {
if (!initialized())
return false;
GuidToShortcutsIteratorMap::iterator it = guid_map_.find(shortcut.id);
if (it != guid_map_.end())
shortcuts_map_.erase(it->second);
guid_map_[shortcut.id] = shortcuts_map_.insert(
std::make_pair(base::i18n::ToLower(shortcut.text), shortcut));
FOR_EACH_OBSERVER(ShortcutsBackendObserver, observer_list_,
OnShortcutsChanged());
return no_db_access_ || BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
base::Bind(base::IgnoreResult(&ShortcutsDatabase::UpdateShortcut),
db_.get(), shortcut));
}
bool ShortcutsBackend::DeleteShortcutsWithIds(
const std::vector<std::string>& shortcut_ids) {
if (!initialized())
return false;
for (size_t i = 0; i < shortcut_ids.size(); ++i) {
GuidToShortcutsIteratorMap::iterator it = guid_map_.find(shortcut_ids[i]);
if (it != guid_map_.end()) {
shortcuts_map_.erase(it->second);
guid_map_.erase(it);
}
}
FOR_EACH_OBSERVER(ShortcutsBackendObserver, observer_list_,
OnShortcutsChanged());
return no_db_access_ || BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
base::Bind(base::IgnoreResult(&ShortcutsDatabase::DeleteShortcutsWithIds),
db_.get(), shortcut_ids));
}
bool ShortcutsBackend::DeleteShortcutsWithUrl(const GURL& shortcut_url) {
if (!initialized())
return false;
std::vector<std::string> shortcut_ids;
for (GuidToShortcutsIteratorMap::iterator it = guid_map_.begin();
it != guid_map_.end();) {
if (it->second->second.url == shortcut_url) {
shortcut_ids.push_back(it->first);
shortcuts_map_.erase(it->second);
guid_map_.erase(it++);
} else {
++it;
}
}
FOR_EACH_OBSERVER(ShortcutsBackendObserver, observer_list_,
OnShortcutsChanged());
return no_db_access_ || BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
base::Bind(base::IgnoreResult(&ShortcutsDatabase::DeleteShortcutsWithUrl),
db_.get(), shortcut_url.spec()));
}
bool ShortcutsBackend::DeleteAllShortcuts() {
if (!initialized())
return false;
shortcuts_map_.clear();
guid_map_.clear();
FOR_EACH_OBSERVER(ShortcutsBackendObserver, observer_list_,
OnShortcutsChanged());
return no_db_access_ || BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,
base::Bind(base::IgnoreResult(&ShortcutsDatabase::DeleteAllShortcuts),
db_.get()));
}
void ShortcutsBackend::InitInternal() {
DCHECK(current_state_ == INITIALIZING);
db_->Init();
ShortcutsDatabase::GuidToShortcutMap shortcuts;
db_->LoadShortcuts(&shortcuts);
temp_shortcuts_map_.reset(new ShortcutMap);
temp_guid_map_.reset(new GuidToShortcutsIteratorMap);
for (ShortcutsDatabase::GuidToShortcutMap::iterator it = shortcuts.begin();
it != shortcuts.end(); ++it) {
(*temp_guid_map_)[it->first] = temp_shortcuts_map_->insert(
std::make_pair(base::i18n::ToLower(it->second.text), it->second));
}
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
base::Bind(&ShortcutsBackend::InitCompleted, this));
}
void ShortcutsBackend::InitCompleted() {
temp_guid_map_->swap(guid_map_);
temp_shortcuts_map_->swap(shortcuts_map_);
temp_shortcuts_map_.reset(NULL);
temp_guid_map_.reset(NULL);
current_state_ = INITIALIZED;
FOR_EACH_OBSERVER(ShortcutsBackendObserver, observer_list_,
OnShortcutsLoaded());
}
// content::NotificationObserver:
void ShortcutsBackend::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (current_state_ != INITIALIZED)
return;
if (type == chrome::NOTIFICATION_HISTORY_URLS_DELETED) {
if (content::Details<const history::URLsDeletedDetails>(details)->
all_history) {
DeleteAllShortcuts();
}
const std::set<GURL>& urls =
content::Details<const history::URLsDeletedDetails>(details)->urls;
std::vector<std::string> shortcut_ids;
for (GuidToShortcutsIteratorMap::iterator it = guid_map_.begin();
it != guid_map_.end(); ++it) {
if (urls.find(it->second->second.url) != urls.end())
shortcut_ids.push_back(it->first);
}
DeleteShortcutsWithIds(shortcut_ids);
return;
}
DCHECK(type == chrome::NOTIFICATION_OMNIBOX_OPENED_URL);
AutocompleteLog* log = content::Details<AutocompleteLog>(details).ptr();
string16 text_lowercase(base::i18n::ToLower(log->text));
const AutocompleteMatch& match(log->result.match_at(log->selected_index));
for (ShortcutMap::iterator it = shortcuts_map_.lower_bound(text_lowercase);
it != shortcuts_map_.end() &&
StartsWith(it->first, text_lowercase, true); ++it) {
if (match.destination_url == it->second.url) {
UpdateShortcut(Shortcut(it->second.id, log->text, match.destination_url,
match.contents, match.contents_class, match.description,
match.description_class, base::Time::Now(),
it->second.number_of_hits + 1));
return;
}
}
AddShortcut(Shortcut(guid::GenerateGUID(), log->text, match.destination_url,
match.contents, match.contents_class, match.description,
match.description_class, base::Time::Now(), 1));
}
} // namespace history
| 36.12782 | 80 | 0.696982 | gavinp |
db392ef179cff39ac26e263071c12e1e08373dc6 | 1,792 | cpp | C++ | src/VPetLCD/Screens/ProgressBarScreen.cpp | Perchindroid/DigimonVPet | 75ae638fb19a5b5d7073589734aa43f8a20813a4 | [
"MIT"
] | 23 | 2021-02-17T06:37:42.000Z | 2022-03-31T23:16:39.000Z | src/VPetLCD/Screens/ProgressBarScreen.cpp | Perchindroid/DigimonVPet | 75ae638fb19a5b5d7073589734aa43f8a20813a4 | [
"MIT"
] | 3 | 2021-03-09T14:39:48.000Z | 2022-03-22T12:27:52.000Z | src/VPetLCD/Screens/ProgressBarScreen.cpp | Perchindroid/DigimonVPet | 75ae638fb19a5b5d7073589734aa43f8a20813a4 | [
"MIT"
] | 13 | 2021-03-23T05:35:32.000Z | 2022-03-21T12:01:38.000Z | /////////////////////////////////////////////////////////////////
/*
Created by Berat Özdemir, January 24 , 2021.
*/
/////////////////////////////////////////////////////////////////
#include "ProgressBarScreen.h"
V20::ProgressBarScreen::ProgressBarScreen(char _text[], uint16_t _barLength, uint16_t _fillPercentage){
int textlength = strlen(_text);
char *buf = new char[textlength+1];
strcpy(buf,_text);
text=buf;
barLength=_barLength;
fillPercentage=_fillPercentage;
};
void V20::ProgressBarScreen::draw(VPetLCD *lcd){
lcd->drawCharArrayOnLCD(text, screenX, 0, pixelColor);
lcd->drawPixelOnLCD( screenX, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 1, pixelColor);
lcd->drawPixelOnLCD( screenX + barLength / 2 + 1, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 1, pixelColor);
lcd->drawPixelOnLCD( screenX + barLength + 1, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 1, pixelColor);
for (int i = 1; i <= barLength; i++) {
lcd->drawPixelOnLCD(i + screenX, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 2, pixelColor);
lcd->drawPixelOnLCD(i + screenX, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 2 + 5, pixelColor);
}
for (int i = 0; i < 4; i++) {
lcd->drawPixelOnLCD( screenX, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 3 + i, pixelColor);
lcd->drawPixelOnLCD( screenX + barLength + 1, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 3 + i, pixelColor);
}
uint16_t maxFill = barLength / 2;
uint16_t percentageBars = fillPercentage * maxFill / 100;
for (int i = 1; i <= percentageBars; i++) {
lcd->drawPixelOnLCD( screenX + i * 2, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 4, pixelColor);
lcd->drawPixelOnLCD( screenX + i * 2, screenY + SPRITES_UPPERCASE_ALPHABET_HEIGHT + 5, pixelColor);
}
} | 35.84 | 115 | 0.661272 | Perchindroid |
db3eef4d69ec56893bb291897520af8ad9d5b3e5 | 6,892 | hh | C++ | python/dune/xt/functions/interfaces/grid-function.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 2 | 2020-02-08T04:08:52.000Z | 2020-08-01T18:54:14.000Z | python/dune/xt/functions/interfaces/grid-function.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 35 | 2019-08-19T12:06:35.000Z | 2020-03-27T08:20:39.000Z | python/dune/xt/functions/interfaces/grid-function.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 1 | 2020-02-08T04:09:34.000Z | 2020-02-08T04:09:34.000Z | // This file is part of the dune-xt project:
// https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt
// Copyright 2009-2021 dune-xt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2020)
// René Fritze (2020)
//
// (http://opensource.org/licenses/BSD-2-Clause)
#ifndef PYTHON_DUNE_XT_FUNCTIONS_INTERFACES_GRID_FUNCTION_HH
#define PYTHON_DUNE_XT_FUNCTIONS_INTERFACES_GRID_FUNCTION_HH
#include <dune/pybindxi/pybind11.h>
#include <dune/xt/common/string.hh>
#include <dune/xt/functions/interfaces/grid-function.hh>
#include <dune/xt/functions/visualization.hh>
#include <dune/xt/grid/gridprovider/provider.hh>
#include <python/dune/xt/common/parameter.hh>
namespace Dune::XT::Functions::bindings {
template <class G, class E, size_t r = 1, size_t rC = 1, class R = double>
class GridFunctionInterface
{
using GP = XT::Grid::GridProvider<G>;
static constexpr size_t d = G::dimension;
template <bool vector = (r != 1 && rC == 1), bool matrix = (rC != 1), bool anything = false>
struct product_helper // <true, false, ...>
{
template <class T, typename... options>
static void addbind(pybind11::class_<T, options...>& c)
{
namespace py = pybind11;
c.def(
"__mul__",
[](const T& self, const Functions::GridFunctionInterface<E, r, 1, R>& other) {
return std::make_unique<decltype(self * other)>(self * other);
},
py::is_operator());
}
};
template <bool anything>
struct product_helper<false, true, anything>
{
template <class T, typename... options>
static void addbind(pybind11::class_<T, options...>& c)
{
namespace py = pybind11;
c.def(
"__mul__",
[](const T& self, const Functions::GridFunctionInterface<E, rC, 1, R>& other) {
return std::make_unique<decltype(self * other)>(self * other);
},
py::is_operator());
c.def(
"__mul__",
[](const T& self, const Functions::GridFunctionInterface<E, rC, 2, R>& other) {
return std::make_unique<decltype(self * other)>(self * other);
},
py::is_operator());
c.def(
"__mul__",
[](const T& self, const Functions::GridFunctionInterface<E, rC, 3, R>& other) {
return std::make_unique<decltype(self * other)>(self * other);
},
py::is_operator());
}
};
template <bool scalar = (r == 1 && rC == 1), bool anything = false>
struct fraction_helper // <true, ...>
{
template <class T, typename... options>
static void addbind(pybind11::class_<T, options...>& c)
{
namespace py = pybind11;
c.def(
"__truediv__",
[](const T& self, const type& other) { return std::make_unique<decltype(other / self)>(other / self); },
py::is_operator());
}
};
template <bool anything>
struct fraction_helper<false, anything>
{
template <class T, typename... options>
static void addbind(pybind11::class_<T, options...>& /*c*/)
{}
};
public:
using type = Functions::GridFunctionInterface<E, r, rC, R>;
using bound_type = pybind11::class_<type>;
static std::string class_name(const std::string& grid_id, const std::string& layer_id, const std::string& class_id)
{
std::string ret = class_id;
ret += "_" + grid_id;
if (!layer_id.empty())
ret += "_" + layer_id;
ret += "_to_" + Common::to_string(r);
if (rC > 1)
ret += "x" + Common::to_string(rC);
ret += "d";
if (!std::is_same<R, double>::value)
ret += "_" + Common::Typename<R>::value(/*fail_wo_typeid=*/true);
return ret;
} // ... class_name(...)
template <class T, typename... options>
static void addbind_methods(pybind11::class_<T, options...>& c)
{
namespace py = pybind11;
using namespace pybind11::literals;
// our methods
c.def(
"visualize",
[](const T& self, const GP& grid_provider, const std::string& filename, const bool subsampling) {
Functions::visualize(self, grid_provider.leaf_view(), filename, subsampling);
},
"grid"_a,
"filename"_a,
"subsampling"_a = true);
// our operators
c.def(
"__add__",
[](const T& self, const type& other) { return std::make_unique<decltype(self + other)>(self + other); },
py::is_operator());
c.def(
"__sub__",
[](const T& self, const type& other) { return std::make_unique<decltype(self - other)>(self - other); },
py::is_operator());
// we can always multiply with a scalar from the right ...
c.def(
"__mul__",
[](const T& self, const Functions::GridFunctionInterface<E, 1, 1, R>& other) {
return std::make_unique<decltype(self * other)>(self * other);
},
py::is_operator());
// .. and with lots of other dims
product_helper<>::addbind(c);
fraction_helper<>::addbind(c);
if constexpr (r == 1 && rC == 1)
c.def(
"__pow__",
[](const T& self) { return std::make_unique<decltype(self * self)>(self * self); },
py::is_operator());
// ParametricInterface methods
c.def(
"parse_parameter", [](const T& self, const Common::Parameter& mu) { return self.parse_parameter(mu); }, "mu"_a);
} // ... addbind_methods(...)
static bound_type bind(pybind11::module& m,
const std::string& grid_id,
const std::string& layer_id = "",
const std::string& class_id = "grid_function_interface")
{
using namespace pybind11::literals;
const auto ClassName = Common::to_camel_case(class_name(grid_id, layer_id, class_id));
bound_type c(m, ClassName.c_str(), Common::to_camel_case(class_id).c_str());
// our properties
c.def_property_readonly("dim_domain", [](type&) { return size_t(d); });
if (rC == 1)
c.def_property_readonly("dim_range", [](type&) { return size_t(r); });
else
c.def_property_readonly("dim_range", [](type&) { return std::make_pair(size_t(r), size_t(rC)); });
c.def_property_readonly("name", [](type& self) { return self.name(); });
// ParametricInterface properties
c.def_property_readonly("is_parametric", [](type& self) { return self.is_parametric(); });
c.def_property_readonly("parameter_type", [](type& self) { return self.parameter_type(); });
addbind_methods(c);
return c;
}
}; // class GridFunctionInterface
} // namespace Dune::XT::Functions::bindings
#endif // PYTHON_DUNE_XT_FUNCTIONS_INTERFACES_GRID_FUNCTION_HH
| 34.633166 | 120 | 0.613755 | dune-community |
db4145ec4b988968b77d9c5a9f98dae19495205c | 334 | cpp | C++ | libgenthrift/cassandra_constants.cpp | caoimhechaos/libcassandra | 0ae354dd5c41132404c7a5f3c99f6e150e7c823f | [
"BSD-3-Clause"
] | 1 | 2019-04-16T09:06:41.000Z | 2019-04-16T09:06:41.000Z | libgenthrift/cassandra_constants.cpp | tjake/libcassandra | a0f31a56fbd6584f8ffc4d4a61df9f13d4365522 | [
"BSD-3-Clause"
] | null | null | null | libgenthrift/cassandra_constants.cpp | tjake/libcassandra | a0f31a56fbd6584f8ffc4d4a61df9f13d4365522 | [
"BSD-3-Clause"
] | 3 | 2016-03-14T11:22:24.000Z | 2020-04-23T06:58:53.000Z | /**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
*/
#include "cassandra_constants.h"
namespace org { namespace apache { namespace cassandra {
const cassandraConstants g_cassandra_constants;
cassandraConstants::cassandraConstants() {
VERSION = "19.4.0";
}
}}} // namespace
| 17.578947 | 67 | 0.730539 | caoimhechaos |
db41fd6633b6b54cb20c9853c40f5427e2c8477f | 3,501 | cpp | C++ | mock_drivers/rosbag_mock_drivers/test/MockCameraDriverROSTest.cpp | adamlm/carma-platform | f6d46274cf6b6e14eddf8715b1a5204050d4c0e2 | [
"Apache-2.0",
"CC-BY-4.0",
"MIT"
] | 112 | 2020-04-27T17:06:46.000Z | 2022-03-31T15:27:14.000Z | mock_drivers/rosbag_mock_drivers/test/MockCameraDriverROSTest.cpp | adamlm/carma-platform | f6d46274cf6b6e14eddf8715b1a5204050d4c0e2 | [
"Apache-2.0",
"CC-BY-4.0",
"MIT"
] | 982 | 2020-04-17T11:28:04.000Z | 2022-03-31T21:12:19.000Z | mock_drivers/rosbag_mock_drivers/test/MockCameraDriverROSTest.cpp | adamlm/carma-platform | f6d46274cf6b6e14eddf8715b1a5204050d4c0e2 | [
"Apache-2.0",
"CC-BY-4.0",
"MIT"
] | 57 | 2020-05-07T15:48:11.000Z | 2022-03-09T23:31:45.000Z | /*
* Copyright (C) 2020-2021 LEIDOS.
*
* 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 <gmock/gmock.h>
#include <ros/ros.h>
#include <sensor_msgs/CameraInfo.h>
#include <sensor_msgs/Image.h>
#include <autoware_msgs/ProjectionMatrix.h>
#include "test_utils.h"
namespace mock_drivers
{
TEST(MockCameraDriver, camera_topic)
{
ros::NodeHandle nh;
bool got_info = false;
bool got_raw = false;
bool got_rect = false;
bool got_mat = false;
ros::Publisher info_pub = nh.advertise<sensor_msgs::CameraInfo>("/bag/hardware_interface/camera/camera_info", 5);
ros::Subscriber info_sub =
nh.subscribe<sensor_msgs::CameraInfo>("/hardware_interface/camera/camera_info", 5,
[&](const sensor_msgs::CameraInfoConstPtr& msg) -> void { got_info = true; });
ros::Publisher image_raw_pub = nh.advertise<sensor_msgs::Image>("/bag/hardware_interface/camera/image_raw", 5);
ros::Subscriber image_raw_sub =
nh.subscribe<sensor_msgs::Image>("/hardware_interface/camera/image_raw", 5,
[&](const sensor_msgs::ImageConstPtr& msg) -> void { got_raw = true; });
ros::Publisher rect_pub = nh.advertise<sensor_msgs::Image>("/bag/hardware_interface/camera/image_rect", 5);
ros::Subscriber rect_sub =
nh.subscribe<sensor_msgs::Image>("/hardware_interface/camera/image_rect", 5,
[&](const sensor_msgs::ImageConstPtr& msg) -> void { got_rect = true; });
ros::Publisher proj_pub = nh.advertise<autoware_msgs::ProjectionMatrix>("/bag/hardware_interface/camera/projection_matrix", 5);
ros::Subscriber proj_sub =
nh.subscribe<autoware_msgs::ProjectionMatrix>("/hardware_interface/camera/projection_matrix", 5,
[&](const autoware_msgs::ProjectionMatrixConstPtr& msg) -> void { got_mat = true; });
ASSERT_TRUE(testing::waitForSubscribers(info_pub, 2, 10000));
ASSERT_TRUE(testing::waitForSubscribers(image_raw_pub, 2, 10000));
ASSERT_TRUE(testing::waitForSubscribers(rect_pub, 2, 10000));
ASSERT_TRUE(testing::waitForSubscribers(proj_pub, 2, 10000));
sensor_msgs::CameraInfo msg1;
sensor_msgs::Image msg2;
sensor_msgs::Image msg3;
autoware_msgs::ProjectionMatrix msg4;
info_pub.publish(msg1);
image_raw_pub.publish(msg2);
rect_pub.publish(msg3);
proj_pub.publish(msg4);
ros::Rate r(10); // 10 hz
ros::WallTime endTime = ros::WallTime::now() + ros::WallDuration(10.0);
while (ros::ok() && endTime > ros::WallTime::now()
&& !(got_info && got_raw && got_rect && got_mat))
{
ros::spinOnce();
r.sleep();
}
ASSERT_TRUE(got_info);
ASSERT_TRUE(got_raw);
ASSERT_TRUE(got_rect);
ASSERT_TRUE(got_mat);
}
} // namespace mock_drivers
/*!
* \brief Main entrypoint for unit tests
*/
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
ros::init(argc, argv, "mock_camera_test");
auto res = RUN_ALL_TESTS();
ros::shutdown();
return res;
} | 33.990291 | 129 | 0.693516 | adamlm |
db42e0db1da8e23cbdc18eb73f8aebec5e5327cb | 5,093 | cc | C++ | examples/workbook/art-workbook/ExN/MassPlot_module.cc | JeffersonLab/ARIEL | 49054ac62a84d48e269f7171daabb98e12a0be90 | [
"BSD-3-Clause"
] | null | null | null | examples/workbook/art-workbook/ExN/MassPlot_module.cc | JeffersonLab/ARIEL | 49054ac62a84d48e269f7171daabb98e12a0be90 | [
"BSD-3-Clause"
] | null | null | null | examples/workbook/art-workbook/ExN/MassPlot_module.cc | JeffersonLab/ARIEL | 49054ac62a84d48e269f7171daabb98e12a0be90 | [
"BSD-3-Clause"
] | 2 | 2020-09-26T01:37:11.000Z | 2021-05-03T13:02:24.000Z | //
// Pull combinations out of the event and make TH1's, some TNtuples ...
//
#include "art-workbook/ExDataProducts/CombinationCollection.h"
#include "art-workbook/ExUtilities/PSetChecker.h"
#include "art-workbook/ExN/TrackCuts.h"
#include "toyExperiment/Geometry/Geometry.h"
#include "toyExperiment/Conditions/Conditions.h"
#include "toyExperiment/PDT/PDT.h"
#include "toyExperiment/RecoDataProducts/RecoTrk.h"
#include "toyExperiment/Reconstruction/FittedHelix.h"
#include "toyExperiment/RecoDataProducts/FittedHelixDataCollection.h"
#include "art/Framework/Core/EDAnalyzer.h"
#include "art/Framework/Core/ModuleMacros.h"
#include "art/Framework/Principal/Event.h"
#include "art_root_io/TFileService.h"
#include "TH1F.h"
#include "TNtuple.h"
#include "cetlib/exception.h"
#include "CLHEP/Units/SystemOfUnits.h"
#include <string>
namespace tex {
class MassPlot : public art::EDAnalyzer {
public:
explicit MassPlot(fhicl::ParameterSet const& pset);
void beginRun( art::Run const& run ) override;
void analyze ( art::Event const& event ) override;
private:
art::InputTag combinerTag_;
int maxPrint_;
TrackCuts cuts_;
art::ServiceHandle<Geometry> geom_;
art::ServiceHandle<Conditions> conditions_;
art::ServiceHandle<PDT> pdt_;
art::ServiceHandle<art::TFileService> tfs_;
// PDG mass of the phi meson.
double mphi_;
// z component of the magnetic field; only deined after the first begin run.
double bz_;
int printCount_;
TH1F* hNCombos_;
TH1F* hNHits_;
TH1F* hMinHits_;
TH1F* hPTrack_;
TH1F* hPMin_;
TH1F* hMass_;
TH1F* hSigM_;
TH1F* hPull_;
// Helper functions.
void checkParameterSet( fhicl::ParameterSet const& pset );
};
}
tex::MassPlot::MassPlot(fhicl::ParameterSet const& pset):
art::EDAnalyzer(pset),
combinerTag_( pset.get<std::string> ("combinerInputTag") ),
maxPrint_( pset.get<int> ("maxPrint",0) ),
cuts_( pset.get<fhicl::ParameterSet>("cuts")),
geom_(),
conditions_(),
pdt_(),
tfs_( art::ServiceHandle<art::TFileService>() ),
mphi_(pdt_->getById(PDGCode::phi).mass()),
bz_(0.),
printCount_(0),
hNCombos_(nullptr),
hNHits_(nullptr),
hMinHits_(nullptr),
hPTrack_(nullptr),
hPMin_(nullptr),
hMass_(nullptr),
hSigM_(nullptr),
hPull_(nullptr){
checkParameterSet( pset );
}
void tex::MassPlot::beginRun( art::Run const& ){
// The geometry is not defined until beginRun. So the next three variables cannot be
// properly initialized earlier.
bz_ = geom_->bz();
// Get the number of layers in the tracking system.
int nShells = geom_->tracker().nShells();
// Set the limits for the hits per track histograms.
int hitBins = nShells+5;
hNCombos_ = tfs_->make<TH1F>("NCombos", "Number of combinations per event", 10, 0., 10. );
hNHits_ = tfs_->make<TH1F>("NHits", "Number of hits Per Track", hitBins, 0., hitBins );
hMinHits_ = tfs_->make<TH1F>("MinHits", "Minimum Number of hits Per Track", hitBins, 0., hitBins );
hPTrack_ = tfs_->make<TH1F>("PTrack", "Momentum of each Track;[MeV]", 125, 0., 2500.);
hPMin_ = tfs_->make<TH1F>("PMin", "Minimum momentum of the two daughters;[MeV]", 125, 0., 2500.);
hMass_ = tfs_->make<TH1F>("Mass", "Reconstructed mass;[MeV]", 100, 1010., 1030. );
hSigM_ = tfs_->make<TH1F>("SigM", "Reconstructed sigma(Mass);[MeV]", 100, 0., 5. );
hPull_ = tfs_->make<TH1F>("Pull", "Mass (Reco-Gen)/sigma", 100, -5., 5. );
}
void tex::MassPlot::analyze( art::Event const& event){
auto combos = event.getValidHandle<CombinationCollection>( combinerTag_ );
hNCombos_->Fill( combos->size() );
for ( auto const& combo : *combos ){
FittedHelixData const& fit0(*combo.child(0));
FittedHelixData const& fit1(*combo.child(1));
int nhit0 = fit0.hits().size();
int nhit1 = fit1.hits().size();
hNHits_->Fill(nhit0);
hNHits_->Fill(nhit1);
int nhits = std::min( nhit0, nhit1 );
hMinHits_->Fill(nhits);
// By convention, this cut is disabled if minHitsPerTrack is negative.
if ( nhits < cuts_.minHitsPerTrack ) continue;
double p0 = fit0.helix().p(bz_);
double p1 = fit1.helix().p(bz_);
hPTrack_->Fill(p0);
hPTrack_->Fill(p1);
double pmin = std::min(p0,p1);
hPMin_->Fill(pmin);
if ( pmin < cuts_.pmin ) continue;
RecoTrk trk = combo.recoTrk();
double m = trk.momentum().mag();
double sigm = trk.sigmaMass();
double mpull = (sigm > 0 ) ? (( m-mphi_)/sigm) : -10.;
hMass_->Fill(m);
hSigM_->Fill(sigm);
hPull_->Fill(mpull);
}
} // end produce
void tex::MassPlot::checkParameterSet( fhicl::ParameterSet const& pset ){
std::vector<std::string> knownParameterNames = { "combinerInputTag", "maxPrint", "cuts" };
PSetChecker checker( knownParameterNames, pset );
if ( checker.bad() ){
throw cet::exception("PSET") << checker.message("MassPlot") << "\n";
}
}
DEFINE_ART_MODULE(tex::MassPlot)
| 28.138122 | 105 | 0.655017 | JeffersonLab |
b9cc6a75f6fc587a1942fd227445cd200057bad5 | 1,492 | cpp | C++ | 027-occlusion-query/HUD027.cpp | michalbb1/opengl4-tutorials-mbsoftworks | ddd5ac157173ccbac5baf864afa34ecb372e2f8a | [
"MIT"
] | 51 | 2018-06-01T05:05:20.000Z | 2022-03-03T16:10:20.000Z | 027-occlusion-query/HUD027.cpp | michalbb1/opengl4-tutorials-mbsoftworks | ddd5ac157173ccbac5baf864afa34ecb372e2f8a | [
"MIT"
] | null | null | null | 027-occlusion-query/HUD027.cpp | michalbb1/opengl4-tutorials-mbsoftworks | ddd5ac157173ccbac5baf864afa34ecb372e2f8a | [
"MIT"
] | 16 | 2019-04-03T04:35:29.000Z | 2022-02-16T01:27:00.000Z | // STL
#include <mutex>
// Project
#include "HUD027.h"
#include "../common_classes/ostreamUtils.h"
using namespace ostream_utils;
HUD027::HUD027(const OpenGLWindow& window)
: HUD(window)
{
static std::once_flag prepareOnceFlag;
std::call_once(prepareOnceFlag, []()
{
FreeTypeFontManager::getInstance().loadSystemFreeTypeFont(DEFAULT_FONT_KEY, "arial.ttf", 24);
});
}
void HUD027::renderHUD(size_t numObjects, size_t numVisibleObjects, bool isWireframeModeOn, bool visualizeOccluders) const
{
printBuilder().print(10, 10, "FPS: {}", _window.getFPS());
printBuilder().print(10, 40, "Vertical Synchronization: {} (Press F3 to toggle)", _window.isVerticalSynchronizationEnabled() ? "On" : "Off");
// Calculate percentage of visible objects
auto visiblePercentage = 0.0f;
if(numObjects > 0)
{
visiblePercentage = 100.0f * static_cast<float>(numVisibleObjects) / numObjects;
}
// Print information about wireframe mode and occlusion query statistics
printBuilder().print(10, 70, "Wireframe mode: {} (Press 'X' to toggle)", isWireframeModeOn ? "On" : "Off");
printBuilder().print(10, 100, "Visualize occluders: {} (Press 'C' to toggle)", visualizeOccluders ? "On" : "Off");
printBuilder().print(10, 130, " - Visible / total objects: {} / {} ({}%)", numVisibleObjects, numObjects, visiblePercentage);
printBuilder()
.fromRight()
.fromBottom()
.print(10, 10, "www.mbsoftworks.sk");
}
| 34.697674 | 145 | 0.677614 | michalbb1 |
b9cd0c71089bfd47e0d6072a1b5a08fd60a346f6 | 2,982 | cpp | C++ | src/core/shadow/DirectionalShadow.cpp | Dreambee0123/render-engine | a82b79dd39f12c3dbaacbd1ac700fb6969532f4c | [
"MIT"
] | 1 | 2021-11-25T11:15:37.000Z | 2021-11-25T11:15:37.000Z | src/core/shadow/DirectionalShadow.cpp | Dreambee0123/render-engine | a82b79dd39f12c3dbaacbd1ac700fb6969532f4c | [
"MIT"
] | null | null | null | src/core/shadow/DirectionalShadow.cpp | Dreambee0123/render-engine | a82b79dd39f12c3dbaacbd1ac700fb6969532f4c | [
"MIT"
] | 6 | 2020-03-09T12:37:26.000Z | 2020-04-01T16:55:33.000Z | //
// Created by Krisu on 2020/3/13.
//
#include "DirectionalShadow.hpp"
#include "Renderer.hpp"
#include "Mesh.hpp"
#include "Scene.hpp"
#include "Transform.hpp"
DirectionalShadow::DirectionalShadow(const int map_width, const int map_height)
:
width(map_width), height(map_height) {
glGenFramebuffers(1, &depthMapFBO);
glGenTextures(1, &depthMap);
glBindTexture(GL_TEXTURE_2D, depthMap);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT,
width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D, depthMap, 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
throw std::runtime_error("Shadow map frame buffer not complete");
}
}
void
DirectionalShadow::GenerateShadowMap(const glm::vec3 &position, const glm::vec3 &direction,
float cone_in_degree) {
glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO);
glViewport(0, 0, width, height);
glClear(GL_DEPTH_BUFFER_BIT);
static Shader shadowGenShader {"shader/shadow-mapping/directional-shadow.vert",
"shader/shadow-mapping/directional-shadow.frag"};
glm::mat4 lightProjection = glm::ortho<float>(
-10, 10, -10, 10,
1.0, 100
);
static const glm::vec3 global_up {0, 1, 0};
glm::vec3 right = glm::cross(direction, global_up);
glm::vec3 up = glm::cross(right, direction);
glm::mat4 lightView = glm::lookAt(position, direction, up);
this->lightSpaceTransform = lightProjection * lightView;
shadowGenShader.UseShaderProgram();
shadowGenShader.Set("lightSpaceTransform", lightSpaceTransform);
glCullFace(GL_FRONT); // fix peter panning
/* Rendering scene at light's space */
auto& scene = Engine::GetInstance().GetCurrentScene();
for (auto& up_game_obj : scene.GetListOfObeject()) {
try {
auto& mesh = up_game_obj->GetComponent<Mesh>();
auto& transform = up_game_obj->GetComponent<Transform>();
shadowGenShader.Set("model", transform.GetMatrix());
mesh.DrawCall();
} catch (NoComponent &) {
continue;
}
}
glCullFace(GL_BACK);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
Engine::GetInstance().GetRenderer().ResetViewport();
}
DirectionalShadow::~DirectionalShadow() {
glDeleteBuffers(1, &depthMapFBO);
glDeleteTextures(1, &depthMap);
}
| 35.927711 | 91 | 0.680751 | Dreambee0123 |
b9cd2302411dfa98e87b197b88213cb543802202 | 5,637 | hpp | C++ | src/3rd party/boost/boost/limits.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 8 | 2016-01-25T20:18:51.000Z | 2019-03-06T07:00:04.000Z | src/3rd party/boost/boost/limits.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 1 | 2018-01-09T10:08:18.000Z | 2018-01-09T10:08:18.000Z | src/3rd party/boost/boost/limits.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 3 | 2016-02-14T01:20:43.000Z | 2021-02-03T11:19:11.000Z |
// (C) Copyright Boost.org 1999. Permission to copy, use, modify, sell and
// distribute this software is granted provided this copyright notice appears
// in all copies. This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
// use this header as a workaround for missing <limits>
// See http://www.boost.org/libs/utility/limits.html for documentation.
#ifndef BOOST_LIMITS
#define BOOST_LIMITS
#include <boost/config.hpp>
#ifdef BOOST_NO_LIMITS
# include <boost/detail/limits.hpp>
#else
# include <limits>
#endif
#if (defined(BOOST_HAS_LONG_LONG) && defined(BOOST_NO_LONG_LONG_NUMERIC_LIMITS)) \
|| (defined(BOOST_HAS_MS_INT64) && defined(BOOST_NO_MS_INT64_NUMERIC_LIMITS))
// Add missing specializations for numeric_limits:
#ifdef BOOST_HAS_MS_INT64
# define BOOST_LLT __int64
#else
# define BOOST_LLT long long
#endif
namespace std
{
template<>
class numeric_limits<BOOST_LLT>
{
public:
BOOST_STATIC_CONSTANT(bool, is_specialized = true);
#ifdef BOOST_HAS_MS_INT64
static BOOST_LLT min(){ return 0x8000000000000000i64; }
static BOOST_LLT max(){ return 0x7FFFFFFFFFFFFFFFi64; }
#elif defined(LLONG_MAX)
static BOOST_LLT min(){ return LLONG_MIN; }
static BOOST_LLT max(){ return LLONG_MAX; }
#elif defined(LONGLONG_MAX)
static BOOST_LLT min(){ return LONGLONG_MIN; }
static BOOST_LLT max(){ return LONGLONG_MAX; }
#else
static BOOST_LLT min(){ return 1LL << (sizeof(BOOST_LLT) * CHAR_BIT - 1); }
static BOOST_LLT max(){ return ~min(); }
#endif
BOOST_STATIC_CONSTANT(int, digits = sizeof(BOOST_LLT) * CHAR_BIT -1);
BOOST_STATIC_CONSTANT(int, digits10 = (CHAR_BIT * sizeof (BOOST_LLT) - 1) * 301L / 1000);
BOOST_STATIC_CONSTANT(bool, is_signed = true);
BOOST_STATIC_CONSTANT(bool, is_integer = true);
BOOST_STATIC_CONSTANT(bool, is_exact = true);
BOOST_STATIC_CONSTANT(int, radix = 2);
static BOOST_LLT epsilon() throw() { return 0; };
static BOOST_LLT round_error() throw() { return 0; };
BOOST_STATIC_CONSTANT(int, min_exponent = 0);
BOOST_STATIC_CONSTANT(int, min_exponent10 = 0);
BOOST_STATIC_CONSTANT(int, max_exponent = 0);
BOOST_STATIC_CONSTANT(int, max_exponent10 = 0);
BOOST_STATIC_CONSTANT(bool, has_infinity = false);
BOOST_STATIC_CONSTANT(bool, has_quiet_NaN = false);
BOOST_STATIC_CONSTANT(bool, has_signaling_NaN = false);
BOOST_STATIC_CONSTANT(bool, has_denorm = false);
BOOST_STATIC_CONSTANT(bool, has_denorm_loss = false);
static BOOST_LLT infinity() throw() { return 0; };
static BOOST_LLT quiet_NaN() throw() { return 0; };
static BOOST_LLT signaling_NaN() throw() { return 0; };
static BOOST_LLT denorm_min() throw() { return 0; };
BOOST_STATIC_CONSTANT(bool, is_iec559 = false);
BOOST_STATIC_CONSTANT(bool, is_bounded = false);
BOOST_STATIC_CONSTANT(bool, is_modulo = false);
BOOST_STATIC_CONSTANT(bool, traps = false);
BOOST_STATIC_CONSTANT(bool, tinyness_before = false);
BOOST_STATIC_CONSTANT(float_round_style, round_style = round_toward_zero);
};
template<>
class numeric_limits<unsigned BOOST_LLT>
{
public:
BOOST_STATIC_CONSTANT(bool, is_specialized = true);
#ifdef BOOST_HAS_MS_INT64
static unsigned BOOST_LLT min(){ return 0ui64; }
static unsigned BOOST_LLT max(){ return 0xFFFFFFFFFFFFFFFFui64; }
#elif defined(ULLONG_MAX) && defined(ULLONG_MIN)
static unsigned BOOST_LLT min(){ return ULLONG_MIN; }
static unsigned BOOST_LLT max(){ return ULLONG_MAX; }
#elif defined(ULONGLONG_MAX) && defined(ULONGLONG_MIN)
static unsigned BOOST_LLT min(){ return ULONGLONG_MIN; }
static unsigned BOOST_LLT max(){ return ULONGLONG_MAX; }
#else
static unsigned BOOST_LLT min(){ return 0uLL; }
static unsigned BOOST_LLT max(){ return ~0uLL; }
#endif
BOOST_STATIC_CONSTANT(int, digits = sizeof(BOOST_LLT) * CHAR_BIT);
BOOST_STATIC_CONSTANT(int, digits10 = (CHAR_BIT * sizeof (BOOST_LLT)) * 301L / 1000);
BOOST_STATIC_CONSTANT(bool, is_signed = false);
BOOST_STATIC_CONSTANT(bool, is_integer = true);
BOOST_STATIC_CONSTANT(bool, is_exact = true);
BOOST_STATIC_CONSTANT(int, radix = 2);
static unsigned BOOST_LLT epsilon() throw() { return 0; };
static unsigned BOOST_LLT round_error() throw() { return 0; };
BOOST_STATIC_CONSTANT(int, min_exponent = 0);
BOOST_STATIC_CONSTANT(int, min_exponent10 = 0);
BOOST_STATIC_CONSTANT(int, max_exponent = 0);
BOOST_STATIC_CONSTANT(int, max_exponent10 = 0);
BOOST_STATIC_CONSTANT(bool, has_infinity = false);
BOOST_STATIC_CONSTANT(bool, has_quiet_NaN = false);
BOOST_STATIC_CONSTANT(bool, has_signaling_NaN = false);
BOOST_STATIC_CONSTANT(bool, has_denorm = false);
BOOST_STATIC_CONSTANT(bool, has_denorm_loss = false);
static unsigned BOOST_LLT infinity() throw() { return 0; };
static unsigned BOOST_LLT quiet_NaN() throw() { return 0; };
static unsigned BOOST_LLT signaling_NaN() throw() { return 0; };
static unsigned BOOST_LLT denorm_min() throw() { return 0; };
BOOST_STATIC_CONSTANT(bool, is_iec559 = false);
BOOST_STATIC_CONSTANT(bool, is_bounded = false);
BOOST_STATIC_CONSTANT(bool, is_modulo = false);
BOOST_STATIC_CONSTANT(bool, traps = false);
BOOST_STATIC_CONSTANT(bool, tinyness_before = false);
BOOST_STATIC_CONSTANT(float_round_style, round_style = round_toward_zero);
};
}
#endif
#endif
| 39.697183 | 95 | 0.712258 | OLR-xray |
b9d3f077eea00bb84395dbc78a804d41fe2a91fb | 1,863 | hh | C++ | test/geometry/LinearPropagator.test.hh | amandalund/celeritas | c631594b00c040d5eb4418fa2129f88c01e29316 | [
"Apache-2.0",
"MIT"
] | null | null | null | test/geometry/LinearPropagator.test.hh | amandalund/celeritas | c631594b00c040d5eb4418fa2129f88c01e29316 | [
"Apache-2.0",
"MIT"
] | null | null | null | test/geometry/LinearPropagator.test.hh | amandalund/celeritas | c631594b00c040d5eb4418fa2129f88c01e29316 | [
"Apache-2.0",
"MIT"
] | null | null | null | //----------------------------------*-C++-*----------------------------------//
// Copyright 2020 UT-Battelle, LLC, and other Celeritas developers.
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: (Apache-2.0 OR MIT)
//---------------------------------------------------------------------------//
//! \file LinearPropagator.test.hh
//---------------------------------------------------------------------------//
#pragma once
#include <vector>
#include "base/Assert.hh"
#include "geometry/GeoInterface.hh"
namespace celeritas_test
{
using celeritas::MemSpace;
using celeritas::Ownership;
using GeoParamsCRefDevice
= celeritas::GeoParamsData<Ownership::const_reference, MemSpace::device>;
using GeoStateRefDevice
= celeritas::GeoStateData<Ownership::reference, MemSpace::device>;
//---------------------------------------------------------------------------//
// TESTING INTERFACE
//---------------------------------------------------------------------------//
using LinPropTestInit = celeritas::GeoTrackInitializer;
//! Input data
struct LinPropTestInput
{
std::vector<LinPropTestInit> init;
int max_segments = 0;
GeoParamsCRefDevice params;
GeoStateRefDevice state;
};
//---------------------------------------------------------------------------//
//! Output results
struct LinPropTestOutput
{
std::vector<int> ids;
std::vector<double> distances;
};
//---------------------------------------------------------------------------//
//! Run on device and return results
LinPropTestOutput linprop_test(LinPropTestInput);
#if !CELERITAS_USE_CUDA
LinPropTestOutput linprop_test(LinPropTestInput)
{
CELER_NOT_CONFIGURED("CUDA");
}
#endif
//---------------------------------------------------------------------------//
} // namespace celeritas_test
| 31.576271 | 79 | 0.482555 | amandalund |
b9d44231041b2e604d559e809fa43e3c9d42eb73 | 1,805 | cxx | C++ | Servers/ServerManager/vtkSMAnimationCueManipulatorProxy.cxx | utkarshayachit/ParaView | 7bbb2aa16fdef9cfbcf4a3786cad905d6770771b | [
"BSD-3-Clause"
] | null | null | null | Servers/ServerManager/vtkSMAnimationCueManipulatorProxy.cxx | utkarshayachit/ParaView | 7bbb2aa16fdef9cfbcf4a3786cad905d6770771b | [
"BSD-3-Clause"
] | null | null | null | Servers/ServerManager/vtkSMAnimationCueManipulatorProxy.cxx | utkarshayachit/ParaView | 7bbb2aa16fdef9cfbcf4a3786cad905d6770771b | [
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: ParaView
Module: vtkSMAnimationCueManipulatorProxy.cxx
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSMAnimationCueManipulatorProxy.h"
#include "vtkObjectFactory.h"
//----------------------------------------------------------------------------
vtkSMAnimationCueManipulatorProxy::vtkSMAnimationCueManipulatorProxy()
{
}
//----------------------------------------------------------------------------
vtkSMAnimationCueManipulatorProxy::~vtkSMAnimationCueManipulatorProxy()
{
}
//----------------------------------------------------------------------------
// Overridden simply to set ObjectsCreated to 1, since this class does
// not create any server side objects.
void vtkSMAnimationCueManipulatorProxy::CreateVTKObjects()
{
this->ObjectsCreated = 1;
this->Superclass::CreateVTKObjects();
}
//----------------------------------------------------------------------------
void vtkSMAnimationCueManipulatorProxy::Copy(vtkSMProxy* src,
const char* exceptionClass, int proxyPropertyCopyFlag)
{
this->Superclass::Copy(src, exceptionClass, proxyPropertyCopyFlag);
this->MarkAllPropertiesAsModified();
}
//----------------------------------------------------------------------------
void vtkSMAnimationCueManipulatorProxy::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
| 34.711538 | 80 | 0.549584 | utkarshayachit |
b9d4c46e5be9f8a09dc3b66f311b6a0fdfbcc64a | 692 | cpp | C++ | src/Timer.cpp | zhiyiYo/Dont-Tap-White-Block | 6297cb922959683e581b4e35e8fd1a0926dfa3dc | [
"MIT"
] | null | null | null | src/Timer.cpp | zhiyiYo/Dont-Tap-White-Block | 6297cb922959683e581b4e35e8fd1a0926dfa3dc | [
"MIT"
] | null | null | null | src/Timer.cpp | zhiyiYo/Dont-Tap-White-Block | 6297cb922959683e581b4e35e8fd1a0926dfa3dc | [
"MIT"
] | null | null | null | #include "Timer.h"
using std::chrono::high_resolution_clock;
/* 打开计时器 */
void Timer::start()
{
if (m_isRunning)
return;
m_isRunning = true;
m_start = high_resolution_clock::now();
}
/* 停止计时器 */
void Timer::stop()
{
m_isRunning = false;
}
/* 重新打开计时器 */
void Timer::restart()
{
stop();
start();
}
/* 判断计时器是否正在运行 */
bool Timer::isRunning() const
{
return m_isRunning;
}
/* 返回自计时器打开之后到现在的时间间隔,以毫秒计,如果计时器没在运行,返回 0 */
int64_t Timer::getDuration()
{
if (!m_isRunning)
return 0;
auto now = high_resolution_clock::now();
int64_t duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_start).count();
return duration;
} | 17.3 | 100 | 0.641618 | zhiyiYo |
b9d65eeb1f513c29f10ba8d2620b97fbe032b6ea | 946 | cpp | C++ | Arrays-Insertion Sort.cpp | Apoorv0001/HackerBlogs-Practice-Questions | 52c95f9d0ade3f38596821c979604c0aa23c78cb | [
"MIT"
] | null | null | null | Arrays-Insertion Sort.cpp | Apoorv0001/HackerBlogs-Practice-Questions | 52c95f9d0ade3f38596821c979604c0aa23c78cb | [
"MIT"
] | null | null | null | Arrays-Insertion Sort.cpp | Apoorv0001/HackerBlogs-Practice-Questions | 52c95f9d0ade3f38596821c979604c0aa23c78cb | [
"MIT"
] | null | null | null | /*
Given an array A of size N , write a function that implements insertion sort on the array. Print the elements of sorted array.
Input Format
First line contains a single integer N denoting the size of the array. Next line contains N space seperated integers where ith integer is the ith element of the array.
Constraints
1 <= N <= 1000
|Ai| <= 1000000
Output Format
Output N space seperated integers of the sorted array in a single line.
Sample Input
4
3 4 2 1
Sample Output
1 2 3 4
Explanation
For each test case, write insertion sort to sort the array.
*/
#include<iostream>
using namespace std;
int main()
{
int size, arr[1001], i, j, temp;
cout<<" ";
cin>>size;
for(i=0; i<size; i++)
{
cin>>arr[i];
}
cout<<" ";
for(i=1; i<size; i++)
{
temp=arr[i];
j=i-1;
while((temp<arr[j]) && (j>=0))
{
arr[j+1]=arr[j];
j=j-1;
}
arr[j+1]=temp;
}
cout<<" ";
for(i=0; i<size; i++)
{
cout<<arr[i]<<" ";
}
return 0;
} | 18.54902 | 167 | 0.647992 | Apoorv0001 |
b9d694961356006758cb892928111d86b7976fd6 | 933 | cpp | C++ | test/runtime/23_threads_heap.cpp | ste-lam/TypeART | e563d3d1cd28245301f5f6d87f7f55d2b13d610a | [
"BSD-3-Clause"
] | 17 | 2020-04-23T14:51:32.000Z | 2022-03-30T08:41:45.000Z | test/runtime/23_threads_heap.cpp | ste-lam/TypeART | e563d3d1cd28245301f5f6d87f7f55d2b13d610a | [
"BSD-3-Clause"
] | 94 | 2020-09-03T12:26:17.000Z | 2022-02-28T14:56:17.000Z | test/runtime/23_threads_heap.cpp | ste-lam/TypeART | e563d3d1cd28245301f5f6d87f7f55d2b13d610a | [
"BSD-3-Clause"
] | 6 | 2020-10-07T22:06:17.000Z | 2021-12-06T12:07:08.000Z | // clang-format off
// RUN: %run %s --thread 2>&1 | FileCheck %s --check-prefix=CHECK-TSAN
// RUN: %run %s --thread 2>&1 | FileCheck %s
// REQUIRES: thread && softcounter
// clang-format on
#include <stdlib.h>
#include <thread>
#include <stdio.h>
void repeat_alloc_free(unsigned n) {
for (int i = 0; i < n; i++) {
double* d = (double*)malloc(sizeof(double) * n);
free(d);
}
}
int main(int argc, char** argv) {
constexpr unsigned n = 1000;
// CHECK: [Trace] TypeART Runtime Trace
std::thread t1(repeat_alloc_free, n);
std::thread t2(repeat_alloc_free, n);
std::thread t3(repeat_alloc_free, n);
t1.join();
t2.join();
t3.join();
// CHECK-TSAN-NOT: ThreadSanitizer
// CHECK-NOT: Error
// CHECK: Allocation type detail (heap, stack, global)
// CHECK: 6 : 3000 , 0 , 0 , double
// CHECK: Free allocation type detail (heap, stack)
// CHECK: 6 : 3000 , 0 , double
return 0;
}
| 22.214286 | 70 | 0.619507 | ste-lam |
b9d8e7dc999ba3064bee7105eff0f9553d825df8 | 9,818 | cpp | C++ | src/slave/containerizer/mesos/isolators/xfs/utils.cpp | m4rvin/Mesos_DRFH | 212486a9349cbec91724d13e6bbc82f1215706aa | [
"Apache-2.0"
] | 4 | 2016-03-15T14:54:34.000Z | 2018-01-03T13:52:10.000Z | src/slave/containerizer/mesos/isolators/xfs/utils.cpp | m4rvin/Mesos_DRFH | 212486a9349cbec91724d13e6bbc82f1215706aa | [
"Apache-2.0"
] | null | null | null | src/slave/containerizer/mesos/isolators/xfs/utils.cpp | m4rvin/Mesos_DRFH | 212486a9349cbec91724d13e6bbc82f1215706aa | [
"Apache-2.0"
] | null | null | null | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// The XFS API headers come from the xfsprogs package. xfsprogs versions
// earlier than 4.5 contain various internal macros that conflict with
// libstdc++.
// If ENABLE_GETTEXT is not defined, then the XFS headers will define
// textdomain() to a while(0) loop. When C++ standard headers try to
// use textdomain(), compilation errors ensue.
#define ENABLE_GETTEXT
#include <xfs/xfs.h>
#include <xfs/xqm.h>
#undef ENABLE_GETTEXT
// xfs/platform_defs-x86_64.h defines min() and max() macros which conflict
// with various min() and max() function definitions.
#undef min
#undef max
#include <fts.h>
#include <blkid/blkid.h>
#include <linux/quota.h>
#include <sys/quota.h>
#include <stout/check.hpp>
#include <stout/error.hpp>
#include <stout/numify.hpp>
#include <stout/path.hpp>
#include <stout/fs.hpp>
#include <stout/os.hpp>
#include "slave/containerizer/mesos/isolators/xfs/utils.hpp"
using std::string;
// Manually define this for old kernels. Compatible with the one in
// <linux/quota.h>.
#ifndef PRJQUOTA
#define PRJQUOTA 2
#endif
namespace mesos {
namespace internal {
namespace xfs {
// The quota API defines space limits in terms of in basic
// blocks (512 bytes).
static constexpr Bytes BASIC_BLOCK_SIZE = Bytes(512u);
// Although XFS itself doesn't define any invalid project IDs,
// we need a way to know whether or not a project ID was assigned
// so we use 0 as our sentinel value.
static constexpr prid_t NON_PROJECT_ID = 0u;
static Error nonProjectError()
{
return Error("Invalid project ID '0'");
}
static Try<int> openPath(
const string& path,
const struct stat& stat)
{
int flags = O_NOFOLLOW | O_RDONLY | O_CLOEXEC;
// Directories require O_DIRECTORY.
flags |= S_ISDIR(stat.st_mode) ? O_DIRECTORY : 0;
return os::open(path, flags);
}
static Try<Nothing> setAttributes(
int fd,
struct fsxattr& attr)
{
if (::xfsctl(nullptr, fd, XFS_IOC_FSSETXATTR, &attr) == -1) {
return ErrnoError();
}
return Nothing();
}
static Try<struct fsxattr> getAttributes(int fd)
{
struct fsxattr attr;
if (::xfsctl(nullptr, fd, XFS_IOC_FSGETXATTR, &attr) == -1) {
return ErrnoError();
}
return attr;
}
// Return the path of the device backing the filesystem containing
// the given path.
static Try<string> getDeviceForPath(const string& path)
{
struct stat statbuf;
if (::lstat(path.c_str(), &statbuf) == -1) {
return ErrnoError("Unable to access '" + path + "'");
}
char* name = blkid_devno_to_devname(statbuf.st_dev);
if (name == nullptr) {
return ErrnoError("Unable to get device for '" + path + "'");
}
string devname(name);
free(name);
return devname;
}
namespace internal {
static Try<Nothing> setProjectQuota(
const string& path,
prid_t projectId,
Bytes limit)
{
Try<string> devname = getDeviceForPath(path);
if (devname.isError()) {
return Error(devname.error());
}
fs_disk_quota_t quota = {0};
quota.d_version = FS_DQUOT_VERSION;
// Specify that we are setting a project quota for this ID.
quota.d_id = projectId;
quota.d_flags = XFS_PROJ_QUOTA;
// Set both the hard and the soft limit to the same quota, just
// for consistency. Functionally all we need is the hard quota.
quota.d_fieldmask = FS_DQ_BSOFT | FS_DQ_BHARD;
quota.d_blk_hardlimit = limit.bytes() / BASIC_BLOCK_SIZE.bytes();
quota.d_blk_softlimit = limit.bytes() / BASIC_BLOCK_SIZE.bytes();
if (::quotactl(QCMD(Q_XSETQLIM, PRJQUOTA),
devname.get().c_str(),
projectId,
reinterpret_cast<caddr_t>("a)) == -1) {
return ErrnoError("Failed to set quota for project ID " +
stringify(projectId));
}
return Nothing();
}
static Try<Nothing> setProjectId(
const string& path,
const struct stat& stat,
prid_t projectId)
{
Try<int> fd = openPath(path, stat);
if (fd.isError()) {
return Error("Failed to open '" + path + "': " + fd.error());
}
Try<struct fsxattr> attr = getAttributes(fd.get());
if (attr.isError()) {
os::close(fd.get());
return Error("Failed to get XFS attributes for '" + path + "': " +
attr.error());
}
attr->fsx_projid = projectId;
if (projectId == NON_PROJECT_ID) {
attr->fsx_xflags &= ~XFS_XFLAG_PROJINHERIT;
} else {
attr->fsx_xflags |= XFS_XFLAG_PROJINHERIT;
}
Try<Nothing> status = setAttributes(fd.get(), attr.get());
os::close(fd.get());
if (status.isError()) {
return Error("Failed to set XFS attributes for '" + path + "': " +
status.error());
}
return Nothing();
}
} // namespace internal {
Result<QuotaInfo> getProjectQuota(
const string& path,
prid_t projectId)
{
if (projectId == NON_PROJECT_ID) {
return nonProjectError();
}
Try<string> devname = getDeviceForPath(path);
if (devname.isError()) {
return Error(devname.error());
}
fs_disk_quota_t quota = {0};
quota.d_version = FS_DQUOT_VERSION;
quota.d_id = projectId;
quota.d_flags = XFS_PROJ_QUOTA;
// In principle, we should issue a Q_XQUOTASYNC to get an accurate accounting.
// However, we don't want to affect performance by continually syncing the
// disks, so we accept that the quota information will be slightly out of
// date.
if (::quotactl(QCMD(Q_XGETQUOTA, PRJQUOTA),
devname.get().c_str(),
projectId,
reinterpret_cast<caddr_t>("a)) == -1) {
return ErrnoError("Failed to get quota for project ID " +
stringify(projectId));
}
// Zero quota means that no quota is assigned.
if (quota.d_blk_hardlimit == 0 && quota.d_bcount == 0) {
return None();
}
QuotaInfo info;
info.limit = BASIC_BLOCK_SIZE * quota.d_blk_hardlimit;
info.used = BASIC_BLOCK_SIZE * quota.d_bcount;
return info;
}
Try<Nothing> setProjectQuota(
const string& path,
prid_t projectId,
Bytes limit)
{
if (projectId == NON_PROJECT_ID) {
return nonProjectError();
}
// A 0 limit deletes the quota record. Since the limit is in basic
// blocks that effectively means > 512 bytes.
if (limit < BASIC_BLOCK_SIZE) {
return Error("Quota limit must be >= " + stringify(BASIC_BLOCK_SIZE));
}
return internal::setProjectQuota(path, projectId, limit);
}
Try<Nothing> clearProjectQuota(
const string& path,
prid_t projectId)
{
if (projectId == NON_PROJECT_ID) {
return nonProjectError();
}
return internal::setProjectQuota(path, projectId, Bytes(0));
}
Result<prid_t> getProjectId(
const string& directory)
{
struct stat stat;
if (::lstat(directory.c_str(), &stat) == -1) {
return ErrnoError("Failed to access '" + directory);
}
Try<int> fd = openPath(directory, stat);
if (fd.isError()) {
return Error("Failed to open '" + directory + "': " + fd.error());
}
Try<struct fsxattr> attr = getAttributes(fd.get());
os::close(fd.get());
if (attr.isError()) {
return Error("Failed to get XFS attributes for '" + directory + "': " +
attr.error());
}
if (attr->fsx_projid == NON_PROJECT_ID) {
return None();
}
return attr->fsx_projid;
}
static Try<Nothing> setProjectIdRecursively(
const string& directory,
prid_t projectId)
{
if (os::stat::islink(directory) || !os::stat::isdir(directory)) {
return Error(directory + " is not a directory");
}
char* directory_[] = {const_cast<char*>(directory.c_str()), nullptr};
FTS* tree = ::fts_open(
directory_, FTS_NOCHDIR | FTS_PHYSICAL | FTS_XDEV, nullptr);
if (tree == nullptr) {
return ErrnoError("Failed to open '" + directory + "'");
}
for (FTSENT *node = ::fts_read(tree);
node != nullptr; node = ::fts_read(tree)) {
if (node->fts_info == FTS_D || node->fts_info == FTS_F) {
Try<Nothing> status = internal::setProjectId(
node->fts_path, *node->fts_statp, projectId);
if (status.isError()) {
::fts_close(tree);
return Error(status.error());
}
}
}
if (errno != 0) {
Error error = ErrnoError();
::fts_close(tree);
return error;
}
if (::fts_close(tree) != 0) {
return ErrnoError("Failed to stop traversing file system");
}
return Nothing();
}
Try<Nothing> setProjectId(
const string& directory,
prid_t projectId)
{
if (projectId == NON_PROJECT_ID) {
return nonProjectError();
}
return setProjectIdRecursively(directory, projectId);
}
Try<Nothing> clearProjectId(
const string& directory)
{
return setProjectIdRecursively(directory, NON_PROJECT_ID);
}
Option<Error> validateProjectIds(const IntervalSet<prid_t>& projectRange)
{
if (projectRange.contains(NON_PROJECT_ID)) {
return Error("XFS project ID range contains illegal " +
stringify(NON_PROJECT_ID) + " value");
}
return None();
}
bool pathIsXfs(const string& path)
{
return ::platform_test_xfs_path(path.c_str()) == 1;
}
} // namespace xfs {
} // namespace internal {
} // namespace mesos {
| 24.483791 | 80 | 0.666735 | m4rvin |
b9da7f22a2dd0367a2dfbd5ef23766ece3bfe902 | 6,297 | cpp | C++ | toolkit/Source/src/gs2d/src/Sprite.cpp | LuizTedesco/ethanon | c140bd360092dcdf11b242a11dee67e79fbbd025 | [
"Unlicense"
] | 64 | 2015-01-02T12:27:29.000Z | 2022-03-07T03:23:33.000Z | toolkit/Source/src/gs2d/src/Sprite.cpp | theomission/ethanon | c140bd360092dcdf11b242a11dee67e79fbbd025 | [
"Unlicense"
] | 5 | 2015-03-31T00:09:29.000Z | 2022-03-07T18:16:42.000Z | toolkit/Source/src/gs2d/src/Sprite.cpp | theomission/ethanon | c140bd360092dcdf11b242a11dee67e79fbbd025 | [
"Unlicense"
] | 40 | 2015-01-14T09:47:56.000Z | 2022-02-07T22:07:24.000Z | /*--------------------------------------------------------------------------------------
Ethanon Engine (C) Copyright 2008-2013 Andre Santee
http://ethanonengine.com/
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------------*/
#include "Sprite.h"
#include "Application.h"
namespace gs2d {
using namespace gs2d::math;
Sprite::Sprite() :
m_nColumns(0),
m_nRows(0),
m_normalizedOrigin(Vector2(0.0f, 0.0f)),
m_rect(Rect2Df(0,0,0,0)),
m_rectMode(RM_TWO_TRIANGLES),
m_currentRect(0),
m_flipX(false),
m_flipY(false),
m_multiply(1.0f, 1.0f),
m_scroll(0.0f, 0.0f)
{
}
void Sprite::GetFlipShaderParameters(Vector2& flipAdd, Vector2& flipMul) const
{
flipMul = Vector2(1,1);
flipAdd = Vector2(0,0);
if (m_flipX)
{
flipMul.x =-1;
flipAdd.x = 1;
}
if (m_flipY)
{
flipMul.y =-1;
flipAdd.y = 1;
}
}
void Sprite::SetRectMode(const RECT_MODE mode)
{
m_rectMode = mode;
}
Sprite::RECT_MODE Sprite::GetRectMode() const
{
return m_rectMode;
}
bool Sprite::Stretch(
const Vector2& a,
const Vector2& b,
const float width,
const Color& color0,
const Color& color1)
{
if (a == b || width <= 0.0f)
{
return true;
}
const Vector2 v2Dir(a - b);
const float len = Distance(a, b);
const float angle = RadianToDegree(GetAngle(v2Dir));
const float lineWidth = (m_rect.size.x <= 0) ? (float)GetProfile().width : (float)m_rect.size.x;
Vector2 origin = GetOrigin();
SetOrigin(EO_CENTER_BOTTOM);
const bool r =
DrawShaped(
a,
Vector2((width >= 0.0f) ? width : lineWidth, len),
color1,
color1,
color0,
color0,
angle);
SetOrigin(origin);
return r;
}
bool Sprite::SetupSpriteRects(const unsigned int columns, const unsigned int rows)
{
m_rects.reset();
if (columns <= 0 || rows <=0)
{
ShowMessage(GS_L("The number of rows or columns set can't be 0 or less - Sprite::SetupSpriteRects"), GSMT_ERROR);
return false;
}
m_nColumns = columns;
m_nRows = rows;
const unsigned int nRects = columns * rows;
m_rects = boost::shared_array<Rect2Df>(new Rect2Df [nRects]);
const Vector2i size(GetBitmapSize());
const unsigned int strideX = static_cast<unsigned int>(size.x) / columns, strideY = static_cast<unsigned int>(size.y) / rows;
unsigned int index = 0;
for (unsigned int y = 0; y < rows; y++)
{
for (unsigned int x = 0; x < columns; x++)
{
m_rects[index].pos.x = static_cast<float>(x * strideX);
m_rects[index].pos.y = static_cast<float>(y * strideY);
m_rects[index].size.x = static_cast<float>(strideX);
m_rects[index].size.y = static_cast<float>(strideY);
index++;
}
}
SetRect(0);
return true;
}
unsigned int Sprite::GetRectIndex() const
{
return m_currentRect;
}
bool Sprite::SetRect(const unsigned int rect)
{
m_currentRect = gs2d::math::Min(rect, GetNumRects() - 1);
m_rect = m_rects[m_currentRect];
return (m_currentRect == rect);
}
bool Sprite::SetRect(const unsigned int column, const unsigned int row)
{
return SetRect((row * m_nColumns) + column);
}
void Sprite::SetRect(const Rect2Df& rect)
{
m_rect = rect;
}
void Sprite::UnsetRect()
{
m_rect = Rect2Df(0, 0, 0, 0);
m_currentRect = 0;
}
Rect2Df Sprite::GetRect() const
{
return m_rect;
}
unsigned int Sprite::GetNumRects() const
{
return m_nColumns * m_nRows;
}
unsigned int Sprite::GetNumRows() const
{
return m_nRows;
}
unsigned int Sprite::GetNumColumns() const
{
return m_nColumns;
}
Rect2Df Sprite::GetRect(const unsigned int rect) const
{
return m_rects[Min(GetNumRects() - 1, rect)];
}
Vector2 Sprite::GetOrigin() const
{
return m_normalizedOrigin;
}
void Sprite::SetOrigin(const Vector2& origin)
{
m_normalizedOrigin = origin;
}
void Sprite::SetOrigin(const ENTITY_ORIGIN origin)
{
switch (origin)
{
case EO_RECT_CENTER:
case EO_CENTER:
m_normalizedOrigin.x = 1.0f / 2.0f;
m_normalizedOrigin.y = 1.0f / 2.0f;
break;
case EO_RECT_CENTER_BOTTOM:
case EO_CENTER_BOTTOM:
m_normalizedOrigin.x = 1.0f / 2.0f;
m_normalizedOrigin.y = 1.0f;
break;
case EO_RECT_CENTER_TOP:
case EO_CENTER_TOP:
m_normalizedOrigin.x = 1.0f / 2.0f;
m_normalizedOrigin.y = 0.0f;
break;
default:
m_normalizedOrigin.x = 0.0f;
m_normalizedOrigin.y = 0.0f;
break;
};
}
math::Vector2 Sprite::GetFrameSize() const
{
return (m_rect.size == Vector2(0, 0)) ? GetBitmapSizeF() : m_rect.size;
}
void Sprite::FlipX(const bool flip)
{
m_flipX = flip;
}
void Sprite::FlipY(const bool flip)
{
m_flipY = flip;
}
void Sprite::FlipX()
{
m_flipX = !(m_flipX);
}
void Sprite::FlipY()
{
m_flipY = !(m_flipY);
}
bool Sprite::GetFlipX() const
{
return m_flipX;
}
bool Sprite::GetFlipY() const
{
return m_flipY;
}
void Sprite::SetMultiply(const Vector2 &v2Multiply)
{
m_multiply = Vector2(Abs(v2Multiply.x), Abs(v2Multiply.y));
}
Vector2 Sprite::GetMultiply() const
{
return m_multiply;
}
#define GS_MAX_SCROLL (1024.0f*4.0f)
void Sprite::SetScroll(const Vector2 &v2Scroll)
{
m_scroll = v2Scroll;
if (m_scroll.x > GS_MAX_SCROLL)
m_scroll.x -= GS_MAX_SCROLL;
else if (m_scroll.x < -GS_MAX_SCROLL)
m_scroll.x += GS_MAX_SCROLL;
if (m_scroll.y > GS_MAX_SCROLL)
m_scroll.y -= GS_MAX_SCROLL;
else if (m_scroll.y < -GS_MAX_SCROLL)
m_scroll.y += GS_MAX_SCROLL;
}
Vector2 Sprite::GetScroll() const
{
return m_scroll;
}
} // namespace gs2d
| 21.491468 | 126 | 0.691282 | LuizTedesco |
b9de47b9c0a8fe266ae4a5a66d3847e33401100e | 3,972 | cc | C++ | CaloOnlineTools/EcalTools/plugins/EcalBxOrbitNumberGrapher.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | CaloOnlineTools/EcalTools/plugins/EcalBxOrbitNumberGrapher.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | CaloOnlineTools/EcalTools/plugins/EcalBxOrbitNumberGrapher.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | // -*- C++ -*-
//
// Package: EcalBxOrbitNumberGrapher
// Class: EcalBxOrbitNumberGrapher
//
/**\class EcalBxOrbitNumberGrapher EcalBxOrbitNumberGrapher.cc
Description: <one line class summary>
Implementation:
<Notes on implementation>
*/
//
// Original Author: Seth COOPER
// Created: Th Nov 22 5:46:22 CEST 2007
//
//
#include "CaloOnlineTools/EcalTools/plugins/EcalBxOrbitNumberGrapher.h"
using namespace cms;
using namespace edm;
using namespace std;
#include <iostream>
//
// constants, enums and typedefs
//
//
// static data member definitions
//
//
// constructors and destructor
//
EcalBxOrbitNumberGrapher::EcalBxOrbitNumberGrapher(const edm::ParameterSet& iConfig)
: digiProducer_(iConfig.getParameter<std::string>("RawDigis")),
runNum_(-1),
fileName_(iConfig.getUntrackedParameter<std::string>("fileName", std::string("ecalURechHitHists"))) {}
EcalBxOrbitNumberGrapher::~EcalBxOrbitNumberGrapher() {}
//
// member functions
//
// ------------ method called to for each event ------------
void EcalBxOrbitNumberGrapher::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) {
using namespace edm;
using namespace cms;
//int ievt = iEvent.id().event();
int orbit = -100;
int bx = -100;
int numorbiterrors = 0;
bool orbiterror = false;
edm::Handle<EcalRawDataCollection> DCCHeaders;
iEvent.getByLabel(digiProducer_, DCCHeaders);
if (!DCCHeaders.isValid()) {
edm::LogError("BxOrbitNumber") << "can't get the product for EcalRawDataCollection";
}
//-----------------BX STuff here
for (EcalRawDataCollection::const_iterator headerItr = DCCHeaders->begin(); headerItr != DCCHeaders->end();
++headerItr) {
headerItr->getEventSettings();
int myorbit = headerItr->getOrbit();
int mybx = headerItr->getBX();
if (orbit == -100) {
orbit = myorbit;
} else if (orbit != myorbit) {
std::cout << " NOOOO This header has a conflicting orbit OTHER " << orbit << " new " << myorbit << std::endl;
orbiterror = true;
numorbiterrors++;
orbitErrorBxDiffPlot_->Fill(myorbit - orbit);
}
if (bx == -100) {
bx = mybx;
} else if (bx != mybx) {
std::cout << " NOOOO This header has a conflicting bx OTHER " << bx << " new " << mybx << std::endl;
}
//LogDebug("EcalTimingCosmic") << " Lambda " << lambda; //hmm... this isn't good, I should keep a record of the wavelength in the headers as an inactive SM might have a different wavelength for this field and make this not go through.
}
if ((bx != -100) & (orbit != -100)) {
std::cout << " Interesting event Orbit " << orbit << " BX " << bx << std::endl;
bxnumberPlot_->Fill(bx);
if (orbiterror) {
orbitErrorPlot_->Fill(bx);
}
}
numberofOrbitDiffPlot_->Fill(numorbiterrors);
if (runNum_ == -1) {
runNum_ = iEvent.id().run();
}
}
// insert the hist map into the map keyed by FED number
void EcalBxOrbitNumberGrapher::initHists(int FED) {}
// ------------ method called once each job just before starting event loop ------------
void EcalBxOrbitNumberGrapher::beginJob() {
bxnumberPlot_ = new TH1F("bxnumber", "BX number of interexting events", 3600, 0., 3600.);
orbitErrorPlot_ = new TH1F("bxOfOrbitDiffs", "BX number of interexting events with orbit changes", 3600, 0., 3600.);
orbitErrorBxDiffPlot_ =
new TH1F("orbitErrorDiffPlot", "Orbit Difference of those HEADERS that have a difference", 20, -10., 10.);
numberofOrbitDiffPlot_ = new TH1F("numberOfOrbitDiffsPlot", "Number of Orbit Differences", 54, 0., 54.);
}
// ------------ method called once each job just after ending the event loop ------------
void EcalBxOrbitNumberGrapher::endJob() {
using namespace std;
fileName_ += ".bx.root";
TFile root_file_(fileName_.c_str(), "RECREATE");
bxnumberPlot_->Write();
orbitErrorPlot_->Write();
numberofOrbitDiffPlot_->Write();
orbitErrorBxDiffPlot_->Write();
root_file_.Close();
}
| 31.03125 | 238 | 0.664904 | ckamtsikis |
b9df9cd5ffe8182a8bb7864ccffc9db1654bc2fe | 584 | cpp | C++ | runtime/heap/JavaHeap.cpp | zhukovaskychina/X-JVM | 51b5404c53c3671af4af6407307234b13f40c43b | [
"MIT"
] | 1 | 2020-10-23T09:38:28.000Z | 2020-10-23T09:38:28.000Z | runtime/heap/JavaHeap.cpp | zhukovaskychina/X-JVM | 51b5404c53c3671af4af6407307234b13f40c43b | [
"MIT"
] | null | null | null | runtime/heap/JavaHeap.cpp | zhukovaskychina/X-JVM | 51b5404c53c3671af4af6407307234b13f40c43b | [
"MIT"
] | null | null | null | //
// Created by zhukovasky on 2020/8/19.
//
#include "JavaHeap.h"
namespace Runtime{
Object *JavaHeap::createJavaObject(JavaClass *javaClass) {
Object *object=new Object();
object->setJavaClass(javaClass);
object->setData(nullptr);
this->youngList.insert(object);
return object;
}
Object *JavaHeap::createJavaArrayObject(JavaClass *javaClass) {
Object *object=new Object();
object->setJavaClass(javaClass);
object->setData(nullptr);
this->eldenList.insert(object);
return nullptr;
}
} | 25.391304 | 67 | 0.636986 | zhukovaskychina |
b9dfb1c91341d9dfd6355096f1b6cd6b725ca486 | 4,805 | cpp | C++ | HiveGame/MyGUI/Tools/SkinEditor/StateListControl.cpp | lockie/HiveGame | bb1aa12561f1dfd956d78a53bfb7a746e119692a | [
"MIT"
] | 4 | 2018-01-08T10:15:52.000Z | 2020-11-15T14:05:50.000Z | HiveGame/MyGUI/Tools/SkinEditor/StateListControl.cpp | lockie/HiveGame | bb1aa12561f1dfd956d78a53bfb7a746e119692a | [
"MIT"
] | null | null | null | HiveGame/MyGUI/Tools/SkinEditor/StateListControl.cpp | lockie/HiveGame | bb1aa12561f1dfd956d78a53bfb7a746e119692a | [
"MIT"
] | 1 | 2019-08-29T18:19:56.000Z | 2019-08-29T18:19:56.000Z | /*!
@file
@author Albert Semenov
@date 08/2010
*/
#include "Precompiled.h"
#include "StateListControl.h"
#include "SkinManager.h"
#include "Binary.h"
#include "Localise.h"
namespace tools
{
enum PresetEnum
{
PresetNormalOnly = Binary<10>::value,
PresetFirst4States = Binary<1111>::value,
PresetAllStates = Binary<11111111>::value
};
StatesListControl::StatesListControl(MyGUI::Widget* _parent) :
wraps::BaseLayout("StateListControl.layout", _parent),
mList(nullptr),
mPresets(nullptr)
{
mTypeName = MyGUI::utility::toString((size_t)this);
assignWidget(mList, "List");
assignWidget(mPresets, "StatePreset");
fillStatePreset();
mList->eventListChangePosition += MyGUI::newDelegate(this, &StatesListControl::notifyChangePosition);
mPresets->eventComboChangePosition += MyGUI::newDelegate(this, &StatesListControl::notifyComboChangePosition);
initialiseAdvisor();
}
StatesListControl::~StatesListControl()
{
shutdownAdvisor();
mList->eventListChangePosition -= MyGUI::newDelegate(this, &StatesListControl::notifyChangePosition);
mPresets->eventComboChangePosition -= MyGUI::newDelegate(this, &StatesListControl::notifyComboChangePosition);
}
void StatesListControl::fillStatePreset()
{
mPresets->removeAllItems();
mPresets->addItem(replaceTags("PresetStateOnlyNormal"), PresetNormalOnly);
mPresets->addItem(replaceTags("PresetStateFirst4"), PresetFirst4States);
mPresets->addItem(replaceTags("PresetStateAll"), PresetAllStates);
mPresets->beginToItemFirst();
}
void StatesListControl::notifyChangePosition(MyGUI::ListBox* _sender, size_t _index)
{
if (getCurrentSkin() != nullptr)
{
StateItem* item = nullptr;
if (_index != MyGUI::ITEM_NONE)
item = *mList->getItemDataAt<StateItem*>(_index);
getCurrentSkin()->getStates().setItemSelected(item);
}
}
void StatesListControl::updateStateProperty(Property* _sender, const MyGUI::UString& _owner)
{
if (_sender->getName() == "Visible")
updateList();
if (_owner != mTypeName)
updatePreset();
}
void StatesListControl::updateStateProperties()
{
updateList();
}
void StatesListControl::updateSkinProperties()
{
updatePreset();
}
void StatesListControl::updateList()
{
if (getCurrentSkin() != nullptr)
{
StateItem* selectedItem = getCurrentSkin()->getStates().getItemSelected();
size_t selectedIndex = MyGUI::ITEM_NONE;
size_t index = 0;
ItemHolder<StateItem>::EnumeratorItem states = getCurrentSkin()->getStates().getChildsEnumerator();
while (states.next())
{
StateItem* item = states.current();
MyGUI::UString name;
if (item->getPropertySet()->getPropertyValue("Visible") != "True")
name = replaceTags("ColourDisabled") + item->getName();
else
name = item->getName();
if (index < mList->getItemCount())
{
mList->setItemNameAt(index, name);
mList->setItemDataAt(index, item);
}
else
{
mList->addItem(name, item);
}
if (item == selectedItem)
selectedIndex = index;
index ++;
}
while (index < mList->getItemCount())
mList->removeItemAt(mList->getItemCount() - 1);
mList->setIndexSelected(selectedIndex);
}
}
void StatesListControl::notifyComboChangePosition(MyGUI::ComboBox* _sender, size_t _index)
{
if (getCurrentSkin() == nullptr)
return;
if (_index == MyGUI::ITEM_NONE)
return;
PresetEnum preset = *_sender->getItemDataAt<PresetEnum>(_index);
size_t index = 0;
ItemHolder<StateItem>::EnumeratorItem states = getCurrentSkin()->getStates().getChildsEnumerator();
while (states.next())
{
StateItem* item = states.current();
MyGUI::UString value = ((preset & (1 << index)) != 0) ? "True" : "False";
item->getPropertySet()->setPropertyValue("Visible", value, mTypeName);
++index;
}
updateList();
}
void StatesListControl::updatePreset()
{
mPresets->setEnabled(getCurrentSkin() != nullptr);
if (getCurrentSkin() != nullptr)
{
int currentPreset = 0;
int bitIndex = 0;
ItemHolder<StateItem>::EnumeratorItem states = getCurrentSkin()->getStates().getChildsEnumerator();
while (states.next())
{
StateItem* item = states.current();
bool visible = item->getPropertySet()->getPropertyValue("Visible") == "True";
if (visible)
currentPreset |= (1 << bitIndex);
++ bitIndex;
}
size_t indexSelected = MyGUI::ITEM_NONE;
size_t count = mPresets->getItemCount();
for (size_t index = 0; index < count; ++index)
{
PresetEnum preset = *mPresets->getItemDataAt<PresetEnum>(index);
if (preset == currentPreset)
{
indexSelected = index;
break;
}
}
mPresets->setIndexSelected(indexSelected);
mPresets->setEnabled(true);
}
else
{
mPresets->setEnabled(false);
}
}
} // namespace tools
| 24.025 | 112 | 0.692196 | lockie |
b9e29e2b8b89ab02b9c8afe586c8636295530517 | 2,713 | cpp | C++ | src/callbacks.cpp | micro-ROS/rmw_embeddedrtps | 756e867f88f882a8db0c18e198fb6b9bbf22a8c2 | [
"Apache-2.0"
] | 3 | 2021-10-19T12:03:03.000Z | 2022-03-21T07:29:11.000Z | src/callbacks.cpp | micro-ROS/rmw_embeddedrtps | 756e867f88f882a8db0c18e198fb6b9bbf22a8c2 | [
"Apache-2.0"
] | null | null | null | src/callbacks.cpp | micro-ROS/rmw_embeddedrtps | 756e867f88f882a8db0c18e198fb6b9bbf22a8c2 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 "./callbacks.hpp"
#include "./types.hpp"
template<typename T>
void inner_callback(
void * callee, const rtps::ReaderCacheChange & cacheChange,
const rmw_ertps_mempool_t * memory)
{
rtps::Reader * reader = reinterpret_cast<rtps::Reader *>( callee);
rmw_ertps_mempool_item_t * item = memory->allocateditems;
while (item != NULL) {
T * element = reinterpret_cast<T *>(item->data);
if (element->reader == reader) {
rmw_ertps_mempool_item_t * memory_node = get_memory(&static_buffer_memory);
if (!memory_node) {
RMW_SET_ERROR_MSG("Not available static buffer memory node");
return;
}
rmw_ertps_static_input_buffer_t * static_buffer =
reinterpret_cast<rmw_ertps_static_input_buffer_t *>(memory_node->data);
static_buffer->owner = reinterpret_cast<void *>(element);
static_buffer->length = cacheChange.getDataSize();
static_buffer->writer_guid = cacheChange.writerGuid;
static_buffer->sequence_number = cacheChange.sn;
static_buffer->related_writer_guid = cacheChange.relatedWriterGuid;
static_buffer->related_sequence_number = cacheChange.relatedSequenceNumber;
if (!cacheChange.copyInto(static_buffer->buffer, RMW_ERTPS_MAX_INPUT_BUFFER_SIZE)) {
put_memory(&static_buffer_memory, memory_node);
} else {
extern sys_sem_t rmw_wait_sem;
sys_sem_signal(&rmw_wait_sem);
}
return;
}
item = item->next;
}
}
template<>
void generic_callback<rmw_ertps_service_t>(
void * callee,
const rtps::ReaderCacheChange & cacheChange)
{
inner_callback<rmw_ertps_service_t>(callee, cacheChange, &service_memory);
}
template<>
void generic_callback<rmw_ertps_subscription_t>(
void * callee,
const rtps::ReaderCacheChange & cacheChange)
{
inner_callback<rmw_ertps_subscription_t>(callee, cacheChange, &subscription_memory);
}
template<>
void generic_callback<rmw_ertps_client_t>(
void * callee,
const rtps::ReaderCacheChange & cacheChange)
{
inner_callback<rmw_ertps_client_t>(callee, cacheChange, &client_memory);
}
| 34.341772 | 90 | 0.735348 | micro-ROS |
b9e2ba432b10d9fb4efcb21452f52faca0283a94 | 238 | cpp | C++ | Online Judges/Neps Academy/A Limonada de Manolo/main.cpp | AnneLivia/URI-Online | 02ff972be172a62b8abe25030c3676f6c04efd1b | [
"MIT"
] | 64 | 2019-03-17T08:56:28.000Z | 2022-01-14T02:31:21.000Z | Online Judges/Neps Academy/A Limonada de Manolo/main.cpp | AnneLivia/URI-Online | 02ff972be172a62b8abe25030c3676f6c04efd1b | [
"MIT"
] | 1 | 2020-12-24T07:16:30.000Z | 2021-03-23T20:51:05.000Z | Online Judges/Neps Academy/A Limonada de Manolo/main.cpp | AnneLivia/URI-Online | 02ff972be172a62b8abe25030c3676f6c04efd1b | [
"MIT"
] | 19 | 2019-05-25T10:48:16.000Z | 2022-01-07T10:07:46.000Z | #include <iostream>
using namespace std;
int main()
{
int n, c, total = 0;
cin >> n >> c;
for (int i = 0; i < n; i++) {
total+=c;
if (c > 1)
c--;
}
cout << total << endl;
return 0;
}
| 13.222222 | 33 | 0.407563 | AnneLivia |