blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
86b936cd3885a178ae59e2ce5e13ba4078be99ee | 8583b5bfc594b994f51d24d012e92ae66bf2e5ea | /src/Extensions/src/extensions/treegenerators/simple_pine_generator.cpp | e3c5b2694a504128ad935b314765b52dd253c83c | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] | permissive | samdauwe/BabylonCpp | 84b8e51b59f04a847681a97fa6fe0a5c554e9e1f | 3dad13a666299cbcf2e2db5b24575c19743e1000 | refs/heads/master | 2022-01-09T02:49:55.057544 | 2022-01-02T19:27:12 | 2022-01-02T19:27:12 | 77,682,359 | 309 | 41 | Apache-2.0 | 2020-11-06T12:16:17 | 2016-12-30T11:29:05 | C++ | UTF-8 | C++ | false | false | 2,196 | cpp | #include <babylon/extensions/treegenerators/simple_pine_generator.h>
#include <babylon/core/random.h>
#include <babylon/maths/vector3.h>
#include <babylon/meshes/mesh.h>
namespace BABYLON {
namespace Extensions {
MeshPtr SimplePineGenerator::CreateTree(Scene* scene, const MaterialPtr& trunkMaterial,
const MaterialPtr& leafMaterial, unsigned int canopies,
float baseRadius, float height, unsigned int tessellation,
float twist)
{
if (twist < 0.f || twist > 1.f) {
twist = 0.f;
}
const auto curvePoints = [twist](float l, float t) {
std::vector<Vector3> path;
auto step = l / t;
for (float i = 0.f; i < l; i += step) {
if (i == 0.f) {
path.emplace_back(Vector3(0.f, i, 0.f));
path.emplace_back(Vector3(0.f, i, 0.f));
}
else {
path.emplace_back(
Vector3(Math::randomNumber(-twist, twist), i, Math::randomNumber(-twist, twist)));
path.emplace_back(
Vector3(Math::randomNumber(-twist, twist), i, Math::randomNumber(-twist, twist)));
}
}
return path;
};
auto nbL = canopies + 1.f;
auto nbS = height;
auto curve = curvePoints(nbS, nbL);
const auto radiusFunction = [nbL, baseRadius](unsigned int i, float
/*distance*/) {
float fact = baseRadius;
if (i % 2 == 0) {
fact /= 3;
}
return (nbL * 2.f - i - 1.f) * fact;
};
auto leaves
= Mesh::CreateTube("leaves", curve, 0.f, tessellation, radiusFunction, Mesh::CAP_START, scene);
// leaves->convertToFlatShadedMesh();
auto trunk = Mesh::CreateCylinder("trunk", height / nbL, nbL * 1.5f - nbL / 2.f - 1.f,
nbL * 1.5f - nbL / 2.f - 1.f, 12, 1, scene);
// trunk->convertToFlatShadedMesh();
leaves->material = leafMaterial;
trunk->material = trunkMaterial;
auto tree = Mesh::CreateBox("", 1.f, scene);
tree->isVisible = false;
leaves->setParent(tree.get());
trunk->setParent(tree.get());
return tree;
}
} // end of namespace Extensions
} // end of namespace BABYLON
| [
"sam.dauwe@gmail.com"
] | sam.dauwe@gmail.com |
eee435df7fff069c6227c1939e3ef2a6ba747bd0 | d70210e656320bacdfd82e3157c5ba15191ec419 | /Linear Data Structure/Chefs in Queue.cpp | 2d3554591df843f54eca01ebddb3ab293bf5435b | [] | no_license | Perdente/CodeChef_DSA_Math | 73d9ec2f4ccd212c44702ff55507429553b3e452 | 1b4ded5ed6609fb8e330ff2d1247c6c6b10b7e4a | refs/heads/main | 2023-01-06T00:06:45.258669 | 2020-10-27T06:13:37 | 2020-10-27T06:13:37 | 303,896,156 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,170 | cpp | //https://www.geeksforgeeks.org/find-the-nearest-smaller-numbers-on-left-side-in-an-array/
//https://www.codechef.com/LRNDSA02/problems/CHFQUEUE
/*
Question(Make the array in non decreasing order and multiply the (upper-lower+1) each time erasing.
Algorithm-
1.Use a stack pair to store the value and indices (stack-poping out the last element).
2.if new value is less then the top of stack then pop out the element and multiply the sum(upper-lower+1).
3.if stack is empty then end the process.
*/
#include<bits/stdc++.h>
using namespace std;
#define int long long int
const int N=1e5+5;
const int mod=1e9+7;
signed main()
{
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int n,k;cin>>n>>k;
vector<int>v(n);
for(int i=0;i<n;++i)
{
cin>>v[i];
}
stack<pair<int,int>>st;
int ans=1;
for(int i=0;i<n;++i)
{
if(st.empty())
{
st.push({v[i],i});
}
else
{
int cur=v[i];
if(cur<st.top().first)
{
while(cur<(st.top().first))
{
ans*=(i-(st.top().second)+1);
ans%=mod;
st.pop();
if(st.empty())break;
}
}
st.push({cur,i});
}
}
cout<<ans<<endl;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
7eca19d8d71671277619d32a40d7eb15e92f75a6 | fa96cf7954e407ce8421dc1ce9c50d8a9036cc6d | /src/checkpoints.cpp | 4b477a4632395c6b45030769094eeab5d7290fb7 | [
"MIT"
] | permissive | chealy82/litedevcoin | 6b7c933a6f6d36b1ab08bd1b2a813d25e1d15028 | 7095f4d68559bb773ec3234ff521188ace71a49d | refs/heads/master | 2020-03-30T06:37:00.143930 | 2019-02-04T09:01:59 | 2019-02-04T09:01:59 | 149,575,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,018 | cpp | // Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double fSigcheckVerificationFactor = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64 nTimeLastCheckpoint;
int64 nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x05dc0ea544a196f31e141cd268c8155a30b2972188ab7d3b6cf083550bfe5275"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1410516073, // * UNIX timestamp of last checkpoint block
0, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
1.0 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0x7d91e7b677947475955b7d84dd8ff0c0edc15feae3ceb2a1cfbf990252b23950"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1537282993,
0,
1.0
};
const CCheckpointData &Checkpoints() {
if (fTestNet)
return dataTestnet;
else
return data;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!GetBoolArg("-checkpoints", true))
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex) {
if (pindex==NULL)
return 0.0;
int64 nNow = time(NULL);
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!GetBoolArg("-checkpoints", true))
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!GetBoolArg("-checkpoints", true))
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
| [
"chealy@chealy.net"
] | chealy@chealy.net |
e98936df0ece1fb337d2b20f8a4df8cbda9d0175 | bcae155999374a2a0bbf2bb80342f104e8061389 | /c++_files/Spring_20_Files/HW/TestComplexNumber.cpp | 0bba68683b58d56180586edfd9ead504850a9208 | [] | no_license | JStevens209/consolidated_projects | bd8b97e377076406c61b19d67950efa740197221 | 6d0e4868f4d585da7258f7e6fd0329a8eab11b50 | refs/heads/main | 2023-07-11T12:50:59.348385 | 2021-08-23T15:47:34 | 2021-08-23T15:47:34 | 315,665,984 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,946 | cpp | // Author: Keith A. Shomper
// Date: Jan 07, 2020
// Purpose: A test program for HW#2.
// NOTE: To compile and link this program with the provided code, you must
// FIRST provide specifications for the three new functions as
// described in the ZyLab write up and provide at least a stub
// implementation of each of these functions in ComplexNumber.cpp.
#include <iostream>
#include "ComplexNumber.h"
using namespace std;
void testMultiply(const ComplexNumber& result, const ComplexNumber& expected);
int main() {
// test the multiplication operator
ComplexNumber a(4, 2);
testMultiply(a * 3, ComplexNumber(12, 6));
testMultiply(a * ComplexNumber(1, -1.5), ComplexNumber(7, -4));
// test string constructor (note, you may also want to test other values)
cout << "Testing string constructor:\n";
cout << " * real number only: " << ComplexNumber("2.54") << endl;
cout << " * imaginary only: " << ComplexNumber("3.2i") << endl;
cout << " * real and imaginary: " << ComplexNumber("2+4i") << endl;
// test assignment of multiple objects via input operator
ComplexNumber x, y;
cout << "Enter two complex numbers: ";
//Note: Stops at space
cin >> x >> y;
cout << "\nYou entered:\n";
cout << " * " << x << "\n * " << y << endl;
// additonal user selected test cases - try several values to ensure the
// correctness of your implementation
ComplexNumber z;
cout << "Please enter a list of complex numbers (type <CTRL-D> to exit): \n";
cin >> z;
if (!cin.eof()) cout << "You entered:\n";
/* while (!cin.eof()) {
cout << " * " << z << endl;
cin >> z;
}*/
return 0;
}
void testMultiply(const ComplexNumber& result, const ComplexNumber& expected) {
if (result == expected) {
cout << "Multiply test passed\n";
}
else {
cout << "Multiply test failed\n";
}
}
| [
"joshua.stevens@obolary.com"
] | joshua.stevens@obolary.com |
7a96b45ff4316c5a1acaf0f7f940478b24cdcf52 | acaecfdb339ba73a27cec139f9e65854aa781342 | /Projects/Engine/src/Platform/DX11/DX11VertexBuffer.cpp | 8717d2ba911d5a018ec835dde1f482db599e9719 | [] | no_license | jonathan2222/YamiEngine | d3fa0ff60c2d457959a9831e0edb3aff458fca81 | b8ed8c0031e101747937b4f0df0bd11e7b9e965b | refs/heads/master | 2020-07-26T11:32:38.599045 | 2020-01-09T23:36:57 | 2020-01-09T23:36:57 | 208,630,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,322 | cpp | #include "stdafx.h"
#include "DX11VertexBuffer.h"
#include "DX11API.h"
ym::DX11VertexBuffer::DX11VertexBuffer() : m_buffer(nullptr), m_size(0)
{
}
ym::DX11VertexBuffer::~DX11VertexBuffer()
{
YM_PROFILER_FUNCTION();
if (m_buffer)
m_buffer->Release();
}
void ym::DX11VertexBuffer::setData(const void* data, unsigned int size, Usage usage)
{
YM_PROFILER_FUNCTION();
if (m_buffer)
{
m_buffer->Release();
m_buffer = nullptr;
}
ID3D11Device* device = DX11API::get()->getDevice();
HRESULT result;
m_size = size;
// Create a description.
D3D11_BUFFER_DESC bufferDesc;
bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bufferDesc.ByteWidth = (UINT)size;
bufferDesc.Usage = (usage == Usage::STATIC ? D3D11_USAGE_DEFAULT : D3D11_USAGE_DYNAMIC);
bufferDesc.CPUAccessFlags = 0;
bufferDesc.MiscFlags = 0;
bufferDesc.StructureByteStride = 0;
// Set the data.
D3D11_SUBRESOURCE_DATA initData;
initData.pSysMem = data;
initData.SysMemPitch = 0;
initData.SysMemSlicePitch = 0;
// Create it.
result = device->CreateBuffer(&bufferDesc, &initData, &m_buffer);
YM_DX11_ASSERT_CHECK(result, "Failed to create vertex buffer!");
}
void ym::DX11VertexBuffer::bind()
{
}
void* ym::DX11VertexBuffer::getBuffer()
{
return (void*)m_buffer;
}
unsigned int ym::DX11VertexBuffer::getSize()
{
return m_size;
}
| [
"jonathan9609082000@gmail.com"
] | jonathan9609082000@gmail.com |
2df82807f7077a7297711178bf521c8c05ac5e29 | c4b112535e70e92c14e20758a440feb2f21de193 | /main/main.cpp | 2f6aa3d99949ed35e586528939eec0c35d8b2b39 | [] | no_license | FinancialEngineerLab/fft_pricing | a6e1210069e2b1bee0a46ea13bf9f8171685fbac | a419cce9f3e7de084e4e4a7ba9af26ea4170f390 | refs/heads/master | 2022-04-26T09:19:36.141862 | 2012-08-20T17:28:30 | 2012-08-20T17:28:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,965 | cpp | #include <iostream>
#include <string>
#include <utility>
#include "pricing/fteurocalc.h"
#include "pricing/eurooption.h"
#include "csutils/get_opt.h"
#include "csutils/configfile.h"
#include "csutils/utils.h"
#include "csutils/logger.h"
#include "csutils/prog_init.h"
#include "mathutils/interpolate.h"
int main (int argc, char* argv[])
{
Getopt getopt;
getopt.addOption("fft", Option::NO_ARG);
getopt.addOption("nstrikes", Option::REQ_ARG);
prog_init(getopt, argc, argv);
const bool fft = getopt.getOption('f').is_set();
unsigned int computeTill = atoi(getopt.getOption('n').arg().c_str());
const unsigned int N = get_value_from_config_file("N", 100);
const double S = get_value_from_config_file("S", 100.);
const double K = get_value_from_config_file("K", 100.);
const double R = get_value_from_config_file("r", 0.09);
const double sigma = get_value_from_config_file("sigma", 0.05);
const double time = get_value_from_config_file("time", 1.);
const double alpha = get_value_from_config_file("alpha", 1.);
const double dpsi = get_value_from_config_file("dpsi", 0.25);
if (computeTill == 0) {
computeTill = 1;
}
if (computeTill > N) {
std::cerr << "nstrikes shoule be less than " << N << std::endl;
exit(1);
}
const Pricing::Time maturity(time);
const Pricing::YieldCurve yc(R);
const Pricing::Volatility vol(sigma);
const Pricing::Time now(0);
Pricing::Pricer pricer;
FTEuroCalc fteurocalc(R, sigma, time, log(S), alpha, N, dpsi);
const double h_0 = log(K);
const std::vector<double> logStrikes = fteurocalc.createLogStrikes(h_0);
std::vector<double> ftCallPrices;
std::vector<double> bsCallPrices;
for (unsigned int j = 0; j < computeTill; ++j) {
const double h = logStrikes[j];
const double ft_price = fteurocalc.formula_6_CallPrice(h);
ftCallPrices.push_back(ft_price);
const Pricing::OptionData optionData(exp(h),
maturity,
Pricing::OptionData::CALL);
const double bS_price = pricer.eurocall(optionData, yc, vol, now, S);
bsCallPrices.push_back(bS_price);
}
std::vector<double> fftCallPrices;
if (fft)
fteurocalc.fftCallPrices(h_0, fftCallPrices, &logStrikes[0]);
for (unsigned int i = 0; i < computeTill; ++i) {
std::cout << S << ' '
<< exp(logStrikes[i]) << ' '
<< bsCallPrices[i] << ' '
<< ftCallPrices[i] << ' ';
if (fft) {
std::cout << fftCallPrices[i];
}
std::cout << std::endl;
}
if (fft) {
const double searchFor = getInput<double>("enter strike: ", true);
const std::pair<bool, double> interp
= MathUtils::interpolate(logStrikes, fftCallPrices, log(searchFor));
if (interp.first) {
std::cout << searchFor << ' ' << interp.second << std::endl;
}
else {
std::cout << "#error: "
<< searchFor << " not in range ["
<< exp(logStrikes[0]) << ", "
<< exp(logStrikes[N - 1]) << "]"
<< std::endl;
}
}
return 0;
}
| [
"strategy.chatterjee@gmail.com"
] | strategy.chatterjee@gmail.com |
ddcf588ac3fdbd9f77cd3f2a43e71973fb1a1ac4 | 075125b49e86842f08ec8f69185d728981326b1a | /cocos2d-x-3.3/Game/JumpingBunny/SourceGame/Menu/InfoMenu.cpp | 4947efa8df5fda2d2061b0a312837b11a6f08a0a | [] | no_license | flowerfx/jumping_bunny_cc2dx | 977d7986054b9224d9a73636ba57d017040a3b2f | e3e91f733b48969dadb4b29017ca5459a687c1d3 | refs/heads/master | 2020-05-23T08:05:54.732245 | 2016-10-01T09:56:57 | 2016-10-01T09:56:57 | 69,731,060 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,079 | cpp | #include "OptionsMenu.h"
#include "MainMenu.h"
#include "InfoMenu.h"
using namespace cocos2d;
InfoMenu * InfoMenu::m_Instance = NULL;
InfoMenu::InfoMenu()
{
p_MenuToSwitchTo = MENU_NONE;
p_IdxMenuData = 2;
}
InfoMenu::~InfoMenu()
{
}
void InfoMenu::Init()
{
InitEntity(p_listMenu[p_IdxMenuData]);
p_DisplayString.find("Text31")->second->SetStringName("1.0.1.1");
}
void InfoMenu::Update(float dt)
{
onUpdate(dt);
if (p_DeltaMoveTime <= 0)
{
p_DeltaMoveTime = 0;
if (p_curStatus == STATUS_MENU::M_FADEOUT)
{
MenuMgr->SwitchToMenu(p_MenuToSwitchTo);
//reset object posion to make sure the menu not stuck
ResetPositionResource();
}
else if (p_curStatus == STATUS_MENU::M_FADEIN)
{
MainMenu::GetInstance()->OnSetVisibleBtn("*", false);
}
p_curStatus = STATUS_MENU::M_IDLE;
if (IsBackKeyPress())
{
OnProcessButton("OKBtn");
SetBackkey(false);
}
}
else
{
float initDeltaTime = XMLMgr->GetUIData()->dataMenu.find(p_listMenu[p_IdxMenuData])->second->deltaTime;
UpdateFadeProcessItem(initDeltaTime, dt * 100.f);
}
}
void InfoMenu::Visit(Renderer *renderer, const Mat4& transform, uint32_t flags, SpriteBatchNode * spriteBatch )
{
onVisit(renderer, transform, flags, spriteBatch );
}
void InfoMenu::Draw(Renderer *renderer, const Mat4& transform, uint32_t flags, SpriteBatchNode * spriteBatch)
{
onDraw(renderer, transform, flags, spriteBatch);
}
void InfoMenu::OnProcessButton(std::string name)
{
if (name == "OKBtn")
{
OnHide();
p_MenuToSwitchTo = MENULAYER::MAINMENU;
MainMenu::GetInstance()->SetMenuReturnTo(MENULAYER::INFOMENU);
}
}
void InfoMenu::OnFadeIn()
{
p_DeltaMoveTime = XMLMgr->GetUIData()->dataMenu.find(p_listMenu[p_IdxMenuData])->second->deltaTime;
p_curStatus = STATUS_MENU::M_FADEIN;
}
void InfoMenu::OnFadeOut()
{
p_DeltaMoveTime = XMLMgr->GetUIData()->dataMenu.find(p_listMenu[p_IdxMenuData])->second->deltaTime;
p_curStatus = STATUS_MENU::M_FADEOUT;
}
void InfoMenu::OnShow()
{
MenuMgr->SetCurrentMenuLayer(MENULAYER::INFOMENU);
OnFadeIn();
}
void InfoMenu::OnHide()
{
OnFadeOut();
} | [
"qchien.gl@hotmail.com"
] | qchien.gl@hotmail.com |
35b7be0a845c1c0711742ff40889a9c34e70e09e | abafba20e115f6ff95f94847c668354710a8328d | /C Practice/数组最大值查找.cpp | d3f9ef8e5897820faeb6f7f4100b5a365ce4644b | [] | no_license | oldteb/Practices | b813878e52bde42a25b863aa96f0068ff3fc04a3 | 827603b80e03e83e6809b29fc49aebb8c30f4d4b | refs/heads/master | 2021-01-10T05:54:32.449453 | 2015-06-22T02:39:43 | 2015-06-22T02:39:43 | 36,441,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,467 | cpp | #include <stdio.h>
#include <stdlib.h>
int main()
{
int c,b,q,z,i,j,a[4][5];
int m,w[20];
printf("please input some integers randomly:\n");
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
scanf("%d ",&a[i][j]);
}
}
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
printf("%5d",a[i][j]);
}
printf("\n");
}
m=0;
b=0;
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
w[m]=a[i][j];
m++;
}
}
for(c=0;c<20;c++)
{
for(m=0;m<20;m++)
{
if(w[m]>w[m+1])
{
z=w[m];
w[m]=w[m+1];
w[m+1]=z;
}
}
}
printf("the biggest number is :%d\n",w[19]);
printf("the status is in ?.");
system("PAUSE");
return 0;
}
| [
"tangyunhe69@gmail.com"
] | tangyunhe69@gmail.com |
4ae83b30c796284368434d77c1ab9adc879d801a | 90e46b80788f2e77eb68825011c682500cabc59c | /Codeforces/1269C.cpp | f31421fd2444a25e9eb0af237a58b363fce5c39f | [] | no_license | yashsoni501/Competitive-Programming | 87a112e681ab0a134b345a6ceb7e817803bee483 | 3b228e8f9a64ef5f7a8df4af8c429ab17697133c | refs/heads/master | 2023-05-05T13:40:15.451558 | 2021-05-31T10:04:26 | 2021-05-31T10:04:26 | 298,651,663 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,078 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ff first
#define ss second
#define pb push_back
#define pf push_front
#define mp make_pair
#define pu push
#define pp pop_back
#define in insert
#define MOD 1000000007
#define endl "\n"
#define sz(a) (int)((a).size())
#define all(x) (x).begin(), (x).end()
#define trace(x) cerr << #x << ": " << x << " " << endl;
#define prv(a) for(auto x : a) cout << x << ' ';cout << '\n';
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define OTP(s) cout<<s<<endl;
#define FOR(i,j,k,l) for(int i=j;i<k;i+=l)
#define REP(i,j) FOR(i,0,j,1)
inline ll add(ll a, ll b){a += b; if(a >= MOD)a -= MOD; return a;}
inline ll sub(ll a, ll b){a -= b; if(a < 0)a += MOD; return a;}
inline ll mul(ll a, ll b){return (ll)((ll) a * b %MOD);}
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef pair<ll,ll> pll;
typedef vector<pll> vpll;
ll min(ll a,ll b)
{
return a>b?b:a;
}
ll max(ll a,ll b)
{
return a>b?a:b;
}
ll n,k,m;
string a="",b="";
int main()
{
IOS
cin>>n>>k;
bool a9=1;
cin>>a;
REP(i,n)
{
if(a[i]!='9')
{
a9=0;
}
}
// if(a9)
// {
// m=n+1;
// b+='1';
// ll ind=1;
// while(ind<m)
// {
// // cout<<"hjere\n";
// if(ind%k==0)
// {
// b+='1';
// }
// else
// {
// b+='0';
// }
// ind++;
// }
// cout<<b<<endl;
// return 0;
// }
string bsplit = a.substr(0,k);
REP(i,n)
{
b+=bsplit[i%k];
}
if(b<a)
{
b="";
ll ind = k-1;
while(ind>0 && bsplit[ind]=='9')
{
bsplit[ind]='0';
ind--;
}
if(ind==-1)
{
bsplit = '1'+bsplit;
}
else
{
bsplit[ind]++;
}
REP(i,n)
{
b+=bsplit[i%k];
}
}
cout<<sz(b)<<endl;
cout<<b<<endl;
} | [
"yashsoni501@gmail.com"
] | yashsoni501@gmail.com |
2e754ecaf78c345af6838551110aab758761cdaa | c7e8ead5498b30d6ade5bb80e61604327b17bb70 | /electric_network/VerticesTable.h | 0358730836e8d6e4cbd7656f616fece7968063ca | [] | no_license | KHAKhazeus/DSProject | 73fc499fd7351d122eac60bec82e9a0b6330f48a | dac44bc89137f3ef5e5ac126af038bab70fde3cd | refs/heads/master | 2020-04-02T13:43:04.359125 | 2019-01-01T05:32:42 | 2019-01-01T05:32:42 | 154,493,481 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,110 | h | //
// Created by Khazeus on 2018-12-29.
//
#ifndef DSPROJECT_NODETABLE_H
#define DSPROJECT_NODETABLE_H
#include "Vertice.h"
#include "List.h"
#include <vector>
template <typename DataType>
class VerticesTable{
public:
~VerticesTable(){ }
int getSize(){ return _vertices.getSize(); }
VerticesTable(): _vertices(List<Vertice<DataType>*>()){}
VerticesTable& operator=(const VerticesTable& right){
ListNode<Vertice<DataType>*>* temp = right.getVerticesList().gethead();
temp->upRef();
temp = temp->getNext();
while(temp){
temp->upRef();
temp->getData()->upRef();
temp = temp->getNext();
}
_vertices = right.getVerticesList();
return *this;
}
List<Vertice<DataType>*>& getVerticesList(){
return _vertices;
}
const List<Vertice<DataType>*>& getVerticesList() const{
return _vertices;
}
bool isIn(Vertice<DataType>* target){
bool result = false;
auto listNode = _vertices.gethead();
if(_vertices.getSize()){
listNode = listNode->getNext();
while(listNode){
if(listNode->getData() == target){
result = true;
break;
}
listNode = listNode->getNext();
}
}
return result;
}
void insertNewVertices(Vertice<DataType>* target){
target->upRef();
_vertices.insertBack(target);
}
Vertice<DataType>* findVerticeByValue(DataType value){
Vertice<DataType>* result = nullptr;
auto listNode = _vertices.gethead();
if(_vertices.getSize()){
listNode = listNode->getNext();
while(listNode){
if(listNode->getData()->getData() == value){
result = listNode->getData();
break;
}
listNode = listNode->getNext();
}
}
return result;
}
private:
List<Vertice<DataType>*> _vertices;
};
#endif //DSPROJECT_NODETABLE_H
| [
"khazeus@outlook.com"
] | khazeus@outlook.com |
329f53df001b221ddd0ab1bf68d5b359199d3cae | b60c4a6bd849bd1e71035e2ec15e2dcc02c83572 | /contrib/brl/bseg/boxm/tests/test_cell_iterator.cxx | 5f75b98ea901cbfd23790176316ee028fb5c59f1 | [] | no_license | mrceresa/vxl_dev | aed751aca9ca8b505b2a3b5c212414a685e121e9 | b26213c75a1a5f1b9d3ccabab89b1a68d7dffa24 | refs/heads/master | 2016-09-06T14:19:00.293440 | 2012-11-02T13:50:10 | 2012-11-02T16:28:49 | 6,161,773 | 1 | 0 | null | 2012-10-10T18:48:19 | 2012-10-10T18:09:11 | null | UTF-8 | C++ | false | false | 1,143 | cxx | //:
// \file
// \author Isabel Restrepo
// \date 13-Aug-2010
#include <testlib/testlib_test.h>
#include "test_utils.h"
void test_cell_iterator()
{
clean_up();
//create scene
boxm_scene<boct_tree<short, float> > *scene = create_scene();
//get the iterator
boxm_cell_iterator<boct_tree<short, float > > iterator = scene->cell_iterator(&boxm_scene<boct_tree<short, float> >::load_block_and_neighbors);
iterator.begin();
boct_tree_cell<short,float> *cell = *iterator;
unsigned num_cells = 0;
bool result = true;
while (!iterator.end()) {
if( (vcl_abs(cell->data() - 0.8) > 1e-7) && (vcl_abs(cell->data() - 0.5) > 1e-7) ){
result = false;
vcl_cerr << " Wrong data: " << cell->data() << vcl_endl;
}
++iterator;
cell = *iterator;
num_cells ++;
}
if(num_cells!=120){
result = false;
vcl_cerr << "Wrong number of cells: " << num_cells << vcl_endl;
}
TEST("Valid Test", result, true);
#ifdef DEBUG_LEAKS
vcl_cerr << "Leaks at test_cell_iterator " << boct_tree_cell<short, float >::nleaks() << vcl_endl;
#endif
clean_up();
}
TESTMAIN(test_cell_iterator);
| [
"isabel_restrepo@4b17d0e5-ac7a-4109-a8ed-6b3c4e86a14a"
] | isabel_restrepo@4b17d0e5-ac7a-4109-a8ed-6b3c4e86a14a |
9e8ca1fc22402a78e608f277c4f643ff652d5eae | 978b7049a0ba75fbae10d61fde783e0e6d5a9c5a | /LeetCode/854-K-Similar Strings.cpp | dc845e37c5309e4f2383fa52cdd9838dbd717eec | [] | no_license | jiahy0825/Leetcode_SecondRound | f675814b95b2687f406e110a1eb16c3c4d4679ca | e34d1fd159412f9dbc5903c4b9b37b6e57dcf635 | refs/heads/master | 2020-04-04T02:54:22.684432 | 2018-12-08T09:13:26 | 2018-12-08T09:13:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,388 | cpp | #include<iostream>
#include<string>
#include<queue>
#include<vector>
#include<unordered_set>
#include<functional>
using namespace std;
class Solution {
public:
int kSimilarity(string A, string B) {
int res = 0;
int len = A.length();
for (int i = 0; i < len; i++){
if (A[i] != B[i]){
for (int j = i + 1; j < len; j++){
if (A[j] == B[i] && A[i] == B[j]){
swap(A[i], A[j]);
res++;
break;
}
}
}
}
queue<string> q;
q.push(A);
unordered_set<string> s;
s.insert(A);
string temp;
while (!q.empty()){
int size = q.size();
while (size-- > 0){
temp = q.front();
q.pop();
if (temp == B){
return res;
}
for (int i = 0; i < len; i++){
if (temp[i] != B[i]){
for (int j = i + 1; j < len; j++){
if (temp[j] == B[i] && temp[j] != B[j]){
swap(temp[i], temp[j]);
if (s.find(temp) == s.end()){
s.insert(temp);
q.push(temp);
}
swap(temp[i], temp[j]);
}
}
}
}
}
res++;
}
return -1;
}
};
//"abc"
//"bca"
//string A = "abcdefghijklmn";
//string B = "bcdefghijklmna";
//"cdebcdeadedaaaebfbcf"
//"baaddacfedebefdabecc"
//12
//int main(){
// string A = "cdebcdeadedaaaebfbcf";
// string B = "baaddacfedebefdabecc";
// cout << (new Solution())->kSimilarity(A, B) << endl;
//
// system("Pause");
// return 0;
//}
//
| [
"632239375@qq.com"
] | 632239375@qq.com |
b807113ab4d2941b4b253ea943bb6259a2f0f62f | 34143cd84540d99cef21fd5edd468c7cd40ac335 | /POJ/2037.cc | 18c2bc6c4c105bdeb23c44a6712882691562a6d9 | [] | no_license | osak/Contest | 0094f87c674d24ebfc0d764fca284493ab90df99 | 22c9edb994b6506b1a4f65b53a6046145a6cce41 | refs/heads/master | 2023-03-06T02:23:53.795410 | 2023-02-26T11:32:11 | 2023-02-26T11:32:11 | 5,219,104 | 8 | 9 | null | 2015-02-09T06:09:14 | 2012-07-29T01:16:42 | C++ | UTF-8 | C++ | false | false | 3,818 | cc | //Name: Roll Playing Games
//Level: 4
//Category: 探索,半分全列挙
//Note: POJではTLE(-O2でジャッジデータ食わせたら一致した)
/*
* サイコロが全部で20+1個なので,可能な合計値は高々1050.
* 決定しているサイコロを順に処理することで,これらを用いて合計sを出すパターンは計算できる.
* 最後のサイコロの面は,R/2個のパターンを半分全列挙してマッチさせる.
*
* オーダーは O(50^(R/2) log 50^(R/2)) くらい.
*/
#ifndef ONLINE_JUDGE
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
using namespace std;
#define FOREACH(it,c) for(__typeof(c.begin()) it = c.begin(); it != c.end(); ++it)
typedef map<vector<long long>, vector<int> > Dict;
long long tbl[2][1051];
int M;
long long *tblptr;
pair<int,int> constraints[10];
void gendict(int depth, int lim, vector<int> &pat, Dict &dict) {
if(depth == 0) {
vector<long long> acc(M, 0);
FOREACH(it, pat) {
for(int j = 0; j < M; ++j) {
const int idx = constraints[j].first;
if(idx-*it >= 0) acc[j] += tblptr[idx-*it];
}
}
Dict::iterator it = dict.find(acc);
if(it == dict.end()) dict[acc] = pat;
} else {
for(int i = lim; i <= 50; ++i) {
pat.push_back(i);
gendict(depth-1, i, pat, dict);
pat.pop_back();
}
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
while(true) {
int N;
cin >> N;
if(!N) break;
long long *cur = tbl[0], *prev = tbl[1];
fill_n(prev, 1051, 0);
prev[0] = 1;
for(int i = 0; i < N; ++i) {
int F;
cin >> F;
fill_n(cur, 1051, 0);
while(F--) {
int val;
cin >> val;
for(int j = 0; j <= 1050-val; ++j) {
cur[j+val] += prev[j];
}
}
swap(cur, prev);
}
tblptr = prev;
int R;
cin >> R >> M;
vector<int> ans(R, 51);
Dict dicta, dictb;
for(int i = 0; i < M; ++i) {
pair<int,int> &p = constraints[i];
cin >> p.first >> p.second;
if(p.first > 1050) {
goto impossible;
}
}
if(R == 4) {
vector<int> pat;
gendict(2, 1, pat, dicta);
dictb = dicta;
} else if(R == 5) {
vector<int> pat;
gendict(2, 1, pat, dicta);
gendict(3, 1, pat, dictb);
} else if(R == 6) {
vector<int> pat;
gendict(3, 1, pat, dicta);
dictb = dicta;
}
{
vector<long long> need(M, 0);
FOREACH(it, dicta) {
const vector<long long> &acc = it->first;
const vector<int> &pat = it->second;
for(int i = 0; i < M; ++i) {
need[i] = constraints[i].second - acc[i];
}
Dict::const_iterator match = dictb.find(need);
if(match != dictb.end()) {
vector<int> cand(pat);
cand.insert(cand.end(), match->second.begin(), match->second.end());
sort(cand.begin(), cand.end());
if(ans > cand) ans = cand;
}
}
}
if(ans[0] <= 50) {
cout << "Final die face values are";
FOREACH(it, ans) {
cout << ' ' << *it;
}
cout << endl;
continue;
}
impossible:
cout << "Impossible" << endl;
}
return 0;
}
| [
"osak.63@gmail.com"
] | osak.63@gmail.com |
dbe40d740ec1249bc90fd1d1a68989329f92cc9f | db48345c7235c4b3f988dbe1765dfbb6d17776c2 | /Source/PuzzlePlatformNTWRK/MenuSystem/MenuInterface.h | 93d5e231d0bf1d3811e62462ac8448d8ee504c15 | [] | no_license | PearsonLawrence/NetworkGameTest | 7338a4d7377f03bc7e5ec7e52c9e41a2d4fe39c1 | 7ed0ffb7a879bbd4205a5a423ca0e19226ec312f | refs/heads/master | 2021-09-04T00:59:55.945875 | 2018-01-13T18:24:02 | 2018-01-13T18:24:02 | 109,328,291 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 521 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "MenuInterface.generated.h"
// This class does not need to be modified.
UINTERFACE(MinimalAPI)
class UMenuInterface : public UInterface
{
GENERATED_BODY()
};
/**
*
*/
class PUZZLEPLATFORMNTWRK_API IMenuInterface
{
GENERATED_BODY()
// Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:
virtual void Host() = 0;
};
| [
"s179130@students.aie.edu.au"
] | s179130@students.aie.edu.au |
ca6129915977333279bac1b944e2d2ef21379554 | 59abf9cf4595cc3d2663fcb38bacd328ab6618af | /MCD/Audio/AudioBuffer.cpp | 012cf91d0435f36a47a7fd5287aed14162003ad0 | [] | no_license | DrDrake/mcore3d | 2ce53148ae3b9c07a3d48b15b3f1a0eab7846de6 | 0bab2c59650a815d6a5b581a2c2551d0659c51c3 | refs/heads/master | 2021-01-10T17:08:00.014942 | 2011-03-18T09:16:28 | 2011-03-18T09:16:28 | 54,134,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,496 | cpp | #include "Pch.h"
#include "AudioBuffer.h"
#include "ALInclude.h"
#include "../Core/System/Utility.h"
namespace MCD {
const char* getALErrorString(ALenum err)
{
switch(err)
{
case AL_NO_ERROR:
return "AL_NO_ERROR";
case AL_INVALID_NAME:
return "AL_INVALID_NAME";
case AL_INVALID_ENUM:
return "AL_INVALID_ENUM";
case AL_INVALID_VALUE:
return "AL_INVALID_VALUE";
case AL_INVALID_OPERATION:
return "AL_INVALID_OPERATION";
case AL_OUT_OF_MEMORY:
return "AL_OUT_OF_MEMORY";
}
return "";
}
bool checkAndPrintError(const char* prefixMessage)
{
ALenum err = alGetError();
if(err == AL_NO_ERROR)
return true;
std::cout << prefixMessage << getALErrorString(err) << std::endl;
return false;
}
AudioBuffer::AudioBuffer(const Path& fileId, size_t bufferCount)
: Resource(fileId), mBufferCount(bufferCount)
{
if(mBufferCount > MCD_COUNTOF(handles))
mBufferCount = MCD_COUNTOF(handles);
memset(handles, 0, sizeof(handles));
alGenBuffers(mBufferCount, handles);
}
AudioBuffer::~AudioBuffer()
{
alDeleteBuffers(mBufferCount, handles);
}
size_t AudioBuffer::getPcm(uint handle)
{
if(!alIsBuffer(handle))
return 0;
static const size_t bitsPerByte = 8;
ALint bits, channels, sizeInBytes;
alGetBufferi(handle, AL_BITS, &bits);
alGetBufferi(handle, AL_CHANNELS, &channels);
alGetBufferi(handle, AL_SIZE, &sizeInBytes);
if(channels * bits == 0)
return 0;
size_t pcm = sizeInBytes / (channels * bits / bitsPerByte);
return pcm;
}
} // namespace MCD
| [
"mtlung@080b3119-2d51-0410-af92-4d39592ae298"
] | mtlung@080b3119-2d51-0410-af92-4d39592ae298 |
5cae91c2f4d8f650ed570921fe4d147f4bfe48db | a7764174fb0351ea666faa9f3b5dfe304390a011 | /drv/IFSelect/IFSelect_Modifier.ixx | 2fd3c918c03da871029923b1254e8863ada04136 | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 764 | ixx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#include <IFSelect_Modifier.jxx>
#ifndef _Standard_Type_HeaderFile
#include <Standard_Type.hxx>
#endif
IMPLEMENT_STANDARD_TYPE(IFSelect_Modifier)
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY()
STANDARD_TYPE(IFSelect_GeneralModifier),
STANDARD_TYPE(MMgt_TShared),
STANDARD_TYPE(Standard_Transient),
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY_END()
IMPLEMENT_STANDARD_TYPE_END(IFSelect_Modifier)
IMPLEMENT_DOWNCAST(IFSelect_Modifier,Standard_Transient)
IMPLEMENT_STANDARD_RTTI(IFSelect_Modifier)
| [
"shoka.sho2@excel.co.jp"
] | shoka.sho2@excel.co.jp |
3d8860d52cd8607146f0201bea9604fdfb87a894 | 8669adfe56247b9634e8cfa43a1123b30e9cbdd2 | /CardType/powerpc/codemcwi/modules/prj_bts/layer3/messages/src/L3OamC13.cpp | 33f51cdf1076052cac6333ec1c77e4f3cbbb7838 | [] | no_license | wl1244648145/xinwei | 308f1c4f64da89ba978f5bf7eb52b6ba121e01c6 | 6a2e4c85ac59eda78de5a5192de14995dee9e1fb | refs/heads/master | 2022-12-03T15:24:12.398873 | 2020-08-23T04:16:04 | 2020-08-23T04:16:04 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,744 | cpp | /*****************************************************************************
* (C) Copyright 2005: Arrowping Telecom
* Arrowping Confidential Proprietary
*****************************************************************************/
/*----------------------------------------------------------------------------
* FILENAME:
*
* DESCRIPTION:
*
*
* HISTORY:
*
* Date Author Description
* ---------- ---------- ----------------------------------------------------
* 08/03/2005 田静伟 Initial file creation.
*---------------------------------------------------------------------------*/
#ifndef _INC_L3EMSMESSAGEID
#include "L3EmsMessageId.h"
#endif
//5.4.4.1 Calibration Result Notification(BTS)
#ifndef _INC_L3OAMCFGCALRSTGENNOTIFY
#include "L3OamCfgCalRstGenNotify.h"
#endif
#include <string.h>
CCfgCalRstGenNotify :: CCfgCalRstGenNotify(CMessage &rMsg)
:CMessage(rMsg)
{ }
CCfgCalRstGenNotify :: CCfgCalRstGenNotify()
{
}
bool CCfgCalRstGenNotify :: CreateMessage(CComEntity &Entity)
{
CMessage :: CreateMessage(Entity);
SetMessageId(M_BTS_EMS_CALIBRAT_CFG_GENDATA_RSP);
return true;
}
UINT32 CCfgCalRstGenNotify :: GetDefaultDataLen() const
{
return sizeof(T_CalRstGenNotify);
}
UINT16 CCfgCalRstGenNotify :: GetTransactionId() const
{
return ((T_CalRstGenNotify *)GetDataPtr())->TransId;
}
UINT16 CCfgCalRstGenNotify :: SetTransactionId(UINT16 TransId)
{
((T_CalRstGenNotify *)GetDataPtr())->TransId = TransId;
return 0;
}
SINT8* CCfgCalRstGenNotify :: GetEle() const
{
return (SINT8*) (&(((T_CalRstGenNotify *)GetDataPtr())->Ele));
}
void CCfgCalRstGenNotify :: SetEle(SINT8 * E)
{
memcpy((SINT8*) (&(((T_CalRstGenNotify *)GetDataPtr())->Ele)),
E,
sizeof(T_CaliGenCfgEle));
}
bool CCfgCalRstGenNotify :: GetEle(SINT8* DstBuff, UINT16 Len)const
{
if(NULL == DstBuff)
{
return false;
}
else
{
memcpy(DstBuff,
&(((T_CalRstGenNotify *)GetDataPtr())->Ele),
Len);
return true;
}
}
bool CCfgCalRstGenNotify :: SetEle(SINT8* SrcBuff, UINT16 Len)
{
if(NULL == SrcBuff)
{
return false;
}
else
{
memcpy(&(((T_CalRstGenNotify*)GetDataPtr())->Ele),
SrcBuff,
Len);
return true;
}
}
#if 0
bool CCfgCalRstGenNotify :: IsAntennaErr()
{
for(UINT8 i = 0; i < ANTENNA_NUM; i++)
{
if(((T_CalRstGenNotify*)GetDataPtr())->Error.CaliAntErr[i] != 0)
return true;
}
return false;
}
bool CCfgCalRstGenNotify :: IsSynErr()
{
return (((T_CalRstGenNotify*)GetDataPtr())->Error.SYNError != 0);
}
bool CCfgCalRstGenNotify :: IsPreDistortErr()
{
return (((T_CalRstGenNotify*)GetDataPtr())->Error.PreDistortErr != 0);
}
bool CCfgCalRstGenNotify :: IsPreCalibrationErr()
{
return (((T_CalRstGenNotify*)GetDataPtr())->Error.PreCalibrationErr != 0);
}
#endif
#ifndef WBBU_CODE
bool CCfgCalRstGenNotify::IsCalibrationErr()
{
return (bool)(((T_CalRstGenNotify*)GetDataPtr())->Error.calCorrFlag);
}
#else
unsigned short CCfgCalRstGenNotify::IsCalibrationErr()
{
return (unsigned short )(((T_CalRstGenNotify*)GetDataPtr())->Error.calCorrFlag);
}
#endif
UINT16 CCfgCalRstGenNotify :: GetErrorAntenna()
{
UINT16 State = 0;//每一位标识一个天线的状态 0 - disable 1 - enable
for(UINT8 i = 0; i < ANTENNA_NUM; i++)
{
if(((T_CalRstGenNotify*)GetDataPtr())->Error.CaliAntErr[i] == 0)
{
State = State | 1;
}
State = State << 1;
}
return State;
}
CCfgCalRstGenNotify :: ~CCfgCalRstGenNotify()
{
}
| [
"hrbeu_xq@163.com"
] | hrbeu_xq@163.com |
07aeeb1f71ea5e82b5e8859f1109d466e6df2fda | 9f2436b611d90ceb9dde73968e902cc92e32d5d9 | /src/net.cpp | d2726deeb69797b6bb3732a72a828d9204535ef6 | [
"MIT"
] | permissive | asiancoin/asiacoin | 75584cc67f9abb2406021870d45f30f7a354540f | e0098120b752497491871deb1796b9a039926164 | refs/heads/master | 2021-01-19T03:27:48.264870 | 2016-04-15T10:56:18 | 2016-04-15T10:56:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 57,932 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "db.h"
#include "net.h"
#include "init.h"
#include "addrman.h"
#include "ui_interface.h"
#include "script.h"
//#include "config.h"
#ifdef WIN32
#include <string.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniwget.h>
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
// Dump addresses to peers.dat every 15 minutes (900s)
#define DUMP_ADDRESSES_INTERVAL 900
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 8;
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
struct LocalServiceInfo {
int nScore;
int nPort;
};
//
// Global state variables
//
bool fDiscover = true;
uint64 nLocalServices = NODE_NETWORK;
static CCriticalSection cs_mapLocalHost;
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
static CNode* pnodeSync = NULL;
uint64 nLocalHostNonce = 0;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
int nMaxConnections = 125;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
limitedmap<CInv, int64> mapAlreadyAskedFor(MAX_INV_SZ);
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
vector<std::string> vAddedNodes;
CCriticalSection cs_vAddedNodes;
static CSemaphore *semOutbound = NULL;
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", GetDefaultPort()));
}
void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
{
// Filter out duplicate requests
if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
return;
pindexLastGetBlocksBegin = pindexBegin;
hashLastGetBlocksEnd = hashEnd;
PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
{
if (fNoListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
{
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
{
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
{
CAddress ret(CService("0.0.0.0",0),0);
CService addr;
if (GetLocal(addr, paddrPeer))
{
ret = CAddress(addr);
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
}
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
while(true)
{
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0)
{
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
}
else if (nBytes <= 0)
{
boost::this_thread::interruption_point();
if (nBytes < 0)
{
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
{
MilliSleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0)
{
// socket closed
printf("socket closed\n");
return false;
}
else
{
// socket error
int nErr = WSAGetLastError();
printf("recv failed: %d\n", nErr);
return false;
}
}
}
}
// used when scores of local addresses may have changed
// pushes better local address to peers
void static AdvertizeLocal()
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->fSuccessfullyConnected)
{
CAddress addrLocal = GetLocalAddress(&pnode->addr);
if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
{
pnode->PushAddress(addrLocal);
pnode->addrLocal = addrLocal;
}
}
}
}
void SetReachable(enum Network net, bool fFlag)
{
LOCK(cs_mapLocalHost);
vfReachable[net] = fFlag;
if (net == NET_IPV6 && fFlag)
vfReachable[NET_IPV4] = true;
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo &info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0);
info.nPort = addr.GetPort();
}
SetReachable(addr.GetNetwork());
}
AdvertizeLocal();
return true;
}
bool AddLocal(const CNetAddr &addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr &addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
AdvertizeLocal();
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
LOCK(cs_mapLocalHost);
enum Network net = addr.GetNetwork();
return vfReachable[net] && !vfLimited[net];
}
#ifdef WIN32
extern int GetExternalIPbySTUN(uint64_t rnd, struct sockaddr_in *mapped, const char **srv);
#else
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
string strLine;
while (RecvLine(hSocket, strLine))
{
if (strLine.empty()) // HTTP response is separated from headers by blank line
{
while(true)
{
if (!RecvLine(hSocket, strLine))
{
closesocket(hSocket);
return false;
}
if (pszKeyword == NULL)
break;
if (strLine.find(pszKeyword) != string::npos)
{
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
break;
}
}
closesocket(hSocket);
if (strLine.find("<") != string::npos)
strLine = strLine.substr(0, strLine.find("<"));
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
strLine.resize(strLine.size()-1);
CService addr(strLine,0,true);
printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
if (!addr.IsValid() || !addr.IsRoutable())
return false;
ipRet.SetIP(addr);
return true;
}
}
closesocket(hSocket);
return error("GetMyExternalIP() : connection closed");
}
#endif// We now get our external IP from the IRC server first and only use this as a backup
bool GetMyExternalIP(CNetAddr& ipRet)
{
#ifdef WIN32
struct sockaddr_in mapped;
uint64_t rnd = std::numeric_limits<uint64_t>::max();
const char *srv;
int rc = GetExternalIPbySTUN(rnd, &mapped, &srv);
if(rc >= 0) {
ipRet = CNetAddr(mapped.sin_addr);
printf("GetExternalIPbySTUN(%I64u) returned %s in attempt %d; Server=%s\n", rnd, ipRet.ToStringIP().c_str(), rc, srv);
return true;
}
#else
CService addrConnect;
const char* pszGet;
const char* pszKeyword;
for (int nLookup = 0; nLookup <= 1; nLookup++)
for (int nHost = 1; nHost <= 2; nHost++)
{
// We should be phasing out our use of sites like these. If we need
// replacements, we should ask for volunteers to put this simple
// php file on their web server that prints the client IP:
// <?php echo $_SERVER["REMOTE_ADDR"]; ?>
if (nHost == 1)
{
addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org
if (nLookup == 1)
{
CService addrIP("checkip.dyndns.org", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET / HTTP/1.1\r\n"
"Host: checkip.dyndns.org\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = "Address:";
}else if (nHost == 2)
{
addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
if (nLookup == 1)
{
CService addrIP("www.showmyip.com", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET /simple/ HTTP/1.1\r\n"
"Host: www.showmyip.com\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = NULL; // Returns just IP address
}
if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
return true;
}
#endif
return false;
}
void ThreadGetMyExternalIP(void* parg)
{
// Make this thread recognisable as the external IP detection thread
RenameThread("bitcoin-ext-ip");
CNetAddr addrLocalHost;
if (GetMyExternalIP(addrLocalHost))
{
printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
AddLocal(addrLocalHost, LOCAL_HTTP);
}
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
CNode* FindNode(const CNetAddr& ip)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
return NULL;
}
CNode* FindNode(std::string addrName)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CService)pnode->addr == addr)
return (pnode);
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
{
if (pszDest == NULL) {
if (IsLocal(addrConnect))
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
pnode->AddRef();
return pnode;
}
}
/// debug print
printf("trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString().c_str(),
pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
// Connect
SOCKET hSocket;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
{
addrman.Attempt(addrConnect);
/// debug print
printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
// Set to non-blocking
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
#else
if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
#endif
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
return pnode;
}
else
{
return NULL;
}
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET)
{
printf("disconnecting node %s\n", addrName.c_str());
closesocket(hSocket);
hSocket = INVALID_SOCKET;
}
// in case this fails, we'll empty the recv buffer when the CNode is deleted
TRY_LOCK(cs_vRecvMsg, lockRecv);
if (lockRecv)
vRecvMsg.clear();
// if this was the sync node, we'll need a new one
if (this == pnodeSync)
pnodeSync = NULL;
}
void CNode::Cleanup()
{
}
void CNode::PushVersion()
{
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
}
std::map<CNetAddr, int64> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned()
{
setBanned.clear();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
if (i != setBanned.end())
{
int64 t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Misbehaving(int howmuch)
{
if (addr.IsLocal())
{
printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
return false;
}
nMisbehavior += howmuch;
if (nMisbehavior >= GetArg("-banscore", 100))
{
int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
CloseSocketDisconnect();
return true;
} else
printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
return false;
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats &stats)
{
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(cleanSubVer);
X(fInbound);
X(nStartingHeight);
X(nMisbehavior);
X(nSendBytes);
X(nRecvBytes);
X(nBlocksRequested);
stats.fSyncNode = (this == pnodeSync);
}
#undef X
// requires LOCK(cs_vRecvMsg)
bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes)
{
while (nBytes > 0) {
// get current incomplete message, or create a new one
if (vRecvMsg.empty() ||
vRecvMsg.back().complete())
vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
CNetMessage& msg = vRecvMsg.back();
// absorb network data
int handled;
if (!msg.in_data)
handled = msg.readHeader(pch, nBytes);
else
handled = msg.readData(pch, nBytes);
if (handled < 0)
return false;
pch += handled;
nBytes -= handled;
}
return true;
}
int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
{
// copy data to temporary parsing buffer
unsigned int nRemaining = 24 - nHdrPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&hdrbuf[nHdrPos], pch, nCopy);
nHdrPos += nCopy;
// if header incomplete, exit
if (nHdrPos < 24)
return nCopy;
// deserialize to CMessageHeader
try {
hdrbuf >> hdr;
}
catch (std::exception &e) {
return -1;
}
// reject messages larger than MAX_SIZE
if (hdr.nMessageSize > MAX_SIZE)
return -1;
// switch state to reading message data
in_data = true;
vRecv.resize(hdr.nMessageSize);
return nCopy;
}
int CNetMessage::readData(const char *pch, unsigned int nBytes)
{
unsigned int nRemaining = hdr.nMessageSize - nDataPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&vRecv[nDataPos], pch, nCopy);
nDataPos += nCopy;
return nCopy;
}
// requires LOCK(cs_vSend)
void SocketSendData(CNode *pnode)
{
std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
while (it != pnode->vSendMsg.end()) {
const CSerializeData &data = *it;
assert(data.size() > pnode->nSendOffset);
int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0) {
pnode->nLastSend = GetTime();
pnode->nSendBytes += nBytes;
pnode->nSendOffset += nBytes;
if (pnode->nSendOffset == data.size()) {
pnode->nSendOffset = 0;
pnode->nSendSize -= data.size();
it++;
} else {
// could not send full message; stop sending more
break;
}
} else {
if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
printf("socket send error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
// couldn't send anything at all
break;
}
}
if (it == pnode->vSendMsg.end()) {
assert(pnode->nSendOffset == 0);
assert(pnode->nSendSize == 0);
}
pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
}
static list<CNode*> vNodesDisconnected;
void ThreadSocketHandler()
{
unsigned int nPrevNodeCount = 0;
while(true)
{
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty()))
{
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
pnode->Cleanup();
// hold in disconnected pool until all refs are released
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0)
{
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
if (fDelete)
{
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if (vNodes.size() != nPrevNodeCount)
{
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(vNodes.size());
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
bool have_fds = false;
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
have_fds = true;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
have_fds = true;
// Implement the following logic:
// * If there is data to send, select() for sending data. As this only
// happens when optimistic write failed, we choose to first drain the
// write buffer in this case before receiving more. This avoids
// needlessly queueing received data, if the remote peer is not themselves
// receiving data. This means properly utilizing TCP flow control signalling.
// * Otherwise, if there is no (complete) message in the receive buffer,
// or there is space left in the buffer, select() for receiving data.
// * (if neither of the above applies, there is certainly one message
// in the receiver buffer ready to be processed).
// Together, that means that at least one of the following is always possible,
// so we don't deadlock:
// * We send some data.
// * We wait for data to be received (and disconnect after timeout).
// * We process a message in the buffer (message handler thread).
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSendMsg.empty()) {
FD_SET(pnode->hSocket, &fdsetSend);
continue;
}
}
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv && (
pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
FD_SET(pnode->hSocket, &fdsetRecv);
}
}
}
int nSelect = select(have_fds ? hSocketMax + 1 : 0,
&fdsetRecv, &fdsetSend, &fdsetError, &timeout);
boost::this_thread::interruption_point();
if (nSelect == SOCKET_ERROR)
{
if (have_fds)
{
int nErr = WSAGetLastError();
printf("socket select error %d\n", nErr);
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
MilliSleep(timeout.tv_usec/1000);
}
//
// Accept new connections
//
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
{
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
printf("Warning: Unknown socket family\n");
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET)
{
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
printf("socket error accept failed: %d\n", nErr);
}
else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS)
{
{
LOCK(cs_setservAddNodeAddresses);
if (!setservAddNodeAddresses.count(addr))
closesocket(hSocket);
}
}
else if (CNode::IsBanned(addr))
{
printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
closesocket(hSocket);
}
else
{
printf("accepted connection %s\n", addr.ToString().c_str());
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
boost::this_thread::interruption_point();
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
{
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0)
{
if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
pnode->CloseSocketDisconnect();
pnode->nLastRecv = GetTime();
pnode->nRecvBytes += nBytes;
}
else if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect)
printf("socket closed\n");
pnode->CloseSocketDisconnect();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
printf("socket recv error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend))
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SocketSendData(pnode);
}
//
// Inactivity checking
//
if (pnode->vSendMsg.empty())
pnode->nLastSendEmpty = GetTime();
if (GetTime() - pnode->nTimeConnected > 60)
{
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
{
printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
{
printf("socket not sending\n");
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastRecv > 90*60)
{
printf("socket inactivity timeout\n");
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
MilliSleep(10);
}
}
#ifdef USE_UPNP
void ThreadMapPort()
{
std::string port = strprintf("%u", GetListenPort());
const char * multicastif = 0;
const char * minissdpdpath = 0;
struct UPNPDev * devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#else
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1)
{
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if(r != UPNPCOMMAND_SUCCESS)
printf("UPnP: GetExternalIPAddress() returned %d\n", r);
else
{
if(externalIPAddress[0])
{
printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
}
else
printf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "Asiacoin " + FormatFullVersion();
try {
while(true) {
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
else
printf("UPnP Port Mapping successful.\n");;
MilliSleep(20*60*1000); // Refresh every 20 minutes
}
}
catch (boost::thread_interrupted)
{
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
printf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist); devlist = 0;
FreeUPNPUrls(&urls);
throw;
}
} else {
printf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist); devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
}
}
void MapPort(bool fUseUPnP)
{
static boost::thread* upnp_thread = NULL;
if (fUseUPnP)
{
if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
}
upnp_thread = new boost::thread(boost::bind(&TraceThread<boost::function<void()> >, "upnp", &ThreadMapPort));
}
else if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
upnp_thread = NULL;
}
}
#else
void MapPort(bool)
{
// Intentionally left blank.
}
#endif
// DNS seeds
// Each pair gives a source name and a seed name.
// The first name is used as information source for addrman.
// The second name should resolve to a list of seed addresses.
static const char *strMainNetDNSSeed[][2] = {
{"seed1", "dnsseed.zaobi.org"},
{"seed2", "dnsseed1.zaobi.org"},
{"seed3", "dnsseed2.zaobi.org"},
{"seed4", "dnsseed3.zaobi.org"},
{"seed5", "dnsseed4.zaobi.org"},
{"seed6", "dnsseed5.zaobi.org"},
{NULL, NULL}
};
static const char *strTestNetDNSSeed[][2] = {
{NULL, NULL}
};
void ThreadDNSAddressSeed()
{
static const char *(*strDNSSeed)[2] = fTestNet ? strTestNetDNSSeed : strMainNetDNSSeed;
int found = 0;
printf("Loading addresses from DNS seeds (could take a while)\n");
for (unsigned int seed_idx = 0; strDNSSeed[seed_idx][0] != NULL; seed_idx++) {
if (HaveNameProxy()) {
AddOneShot(strDNSSeed[seed_idx][1]);
} else {
vector<CNetAddr> vaddr;
vector<CAddress> vAdd;
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
{
BOOST_FOREACH(CNetAddr& ip, vaddr)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
}
}
printf("%d addresses found from DNS seeds\n", found);
}
unsigned int pnSeed[] =
{
};
void DumpAddresses()
{
int64 nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void ThreadOpenConnections()
{
// Connect to specific addresses
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
{
for (int64 nLoop = 0;; nLoop++)
{
ProcessOneShot();
BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
{
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++)
{
MilliSleep(500);
}
}
MilliSleep(500);
}
}
// Initiate network connections
int64 nStart = GetTime();
while(true)
{
ProcessOneShot();
MilliSleep(500);
CSemaphoreGrant grant(*semOutbound);
boost::this_thread::interruption_point();
// Add seed nodes if IRC isn't working
if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
{
std::vector<CAddress> vAdd;
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64 nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vAdd.push_back(addr);
}
addrman.Add(vAdd, CNetAddr("127.0.0.1"));
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64 nANow = GetAdjustedTime();
int nTries = 0;
while(true)
{
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
// If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
// stop this while(true), and let the outer while(true) run again (which sleeps, adds seed nodes, recalculates
// already-connected network ranges, ...) before trying new addrman addresses.
nTries++;
if (nTries > 100)
break;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections()
{
{
LOCK(cs_vAddedNodes);
vAddedNodes = mapMultiArgs["-addnode"];
}
if (HaveNameProxy()) {
while(true) {
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH(string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
BOOST_FOREACH(string& strAddNode, lAddresses) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
for (unsigned int i = 0; true; i++)
{
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH(string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
list<vector<CService> > lservAddressesToAdd(0);
BOOST_FOREACH(string& strAddNode, lAddresses)
{
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
{
lservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH(CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
BOOST_FOREACH(CService& addrNode, *(it))
if (pnode->addr == addrNode)
{
it = lservAddressesToAdd.erase(it);
it--;
break;
}
}
BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd)
{
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
// if successful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
boost::this_thread::interruption_point();
if (!strDest)
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort().c_str()))
return false;
if (strDest && FindNode(strDest))
return false;
CNode* pnode = ConnectNode(addrConnect, strDest);
boost::this_thread::interruption_point();
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
// for now, use a very simple selection metric: the node from which we received
// most recently
double static NodeSyncScore(const CNode *pnode) {
return -pnode->nLastRecv;
}
void static StartSync(const vector<CNode*> &vNodes) {
CNode *pnodeNewSync = NULL;
double dBestScore = 0;
// fImporting and fReindex are accessed out of cs_main here, but only
// as an optimization - they are checked again in SendMessages.
if (fImporting || fReindex)
return;
// Iterate over all nodes
BOOST_FOREACH(CNode* pnode, vNodes) {
// check preconditions for allowing a sync
if (!pnode->fClient && !pnode->fOneShot &&
!pnode->fDisconnect && pnode->fSuccessfullyConnected &&
(pnode->nStartingHeight > (nBestHeight - 144)) &&
(pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) {
// if ok, compare node's score with the best so far
double dScore = NodeSyncScore(pnode);
if (pnodeNewSync == NULL || dScore > dBestScore) {
pnodeNewSync = pnode;
dBestScore = dScore;
}
}
}
// if a new sync candidate was found, start sync!
if (pnodeNewSync) {
pnodeNewSync->fStartSync = true;
pnodeSync = pnodeNewSync;
}
}
void ThreadMessageHandler()
{
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (true)
{
bool fHaveSyncNode = false;
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy) {
pnode->AddRef();
if (pnode == pnodeSync)
fHaveSyncNode = true;
}
}
if (!fHaveSyncNode)
StartSync(vNodesCopy);
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
bool fSleep = true;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect)
continue;
// Receive messages
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv)
{
if (!ProcessMessages(pnode))
pnode->CloseSocketDisconnect();
if (pnode->nSendSize < SendBufferSize())
{
if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete()))
{
fSleep = false;
}
}
}
}
boost::this_thread::interruption_point();
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SendMessages(pnode, pnode == pnodeTrickle);
}
boost::this_thread::interruption_point();
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
if (fSleep)
MilliSleep(100);
}
}
bool BindListenPort(const CService &addrBind, string& strError)
{
strError = "";
int nOne = 1;
// Create socket for listening for incoming connections
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
printf("%s\n", strError.c_str());
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
#ifndef WIN32
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows.
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
// Set to non-blocking, incoming connections will also inherit this
if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
#else
if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef USE_IPV6
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
#ifdef WIN32
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
#else
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#endif
#ifdef WIN32
int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
// this call is allowed to fail
setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
#endif
}
#endif
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. Asiacoin is probably already running."), addrBind.ToString().c_str());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
printf("%s\n", strError.c_str());
return false;
}
printf("Bound to %s\n", addrBind.ToString().c_str());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
vhListenSocket.push_back(hListenSocket);
if (addrBind.IsRoutable() && fDiscover)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover()
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[1000] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr))
{
BOOST_FOREACH (const CNetAddr &addr, vaddr)
{
AddLocal(addr, LOCAL_IF);
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0)
{
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#ifdef USE_IPV6
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#endif
}
freeifaddrs(myaddrs);
}
#endif
// Don't use external IPv4 discovery, when -onlynet="IPv6"
if (!IsLimited(NET_IPV4))
NewThread(ThreadGetMyExternalIP, NULL);
}
void StartNode(boost::thread_group& threadGroup)
{
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover();
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
printf("DNS seeding disabled\n");
else
threadGroup.create_thread(boost::bind(&TraceThread<boost::function<void()> >, "dnsseed", &ThreadDNSAddressSeed));
#ifdef USE_UPNP
// Map ports with UPnP
MapPort(GetBoolArg("-upnp", USE_UPNP));
#endif
// Send and receive from sockets, accept connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
// Initiate outbound connections from -addnode
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
// Initiate outbound connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
// Process messages
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
// Dump network addresses
threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000));
}
bool StopNode()
{
printf("StopNode()\n");
GenerateBitcoins(false, NULL);
MapPort(false);
nTransactionsUpdated++;
if (semOutbound)
for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
MilliSleep(50);
DumpAddresses();
return true;
}
class CNetCleanup
{
public:
CNetCleanup()
{
}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
closesocket(pnode->hSocket);
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET)
if (closesocket(hListenSocket) == SOCKET_ERROR)
printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
// clean up some globals (to help leak detection)
BOOST_FOREACH(CNode *pnode, vNodes)
delete pnode;
BOOST_FOREACH(CNode *pnode, vNodesDisconnected)
delete pnode;
vNodes.clear();
vNodesDisconnected.clear();
delete semOutbound;
semOutbound = NULL;
delete pnodeLocalHost;
pnodeLocalHost = NULL;
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
}
instance_of_cnetcleanup;
void RelayTransaction(const CTransaction& tx, const uint256& hash)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(10000);
ss << tx;
RelayTransaction(tx, hash, ss);
}
void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
{
CInv inv(MSG_TX, hash);
{
LOCK(cs_mapRelay);
// Expire old relay messages
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
{
mapRelay.erase(vRelayExpiration.front().second);
vRelayExpiration.pop_front();
}
// Save original serialized message so newer versions are preserved
mapRelay.insert(std::make_pair(inv, ss));
vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
}
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if(!pnode->fRelayTxes)
continue;
LOCK(pnode->cs_filter);
if (pnode->pfilter)
{
if (pnode->pfilter->IsRelevantAndUpdate(tx, hash))
pnode->PushInventory(inv);
} else
pnode->PushInventory(inv);
}
}
| [
"1375333986@qq.com"
] | 1375333986@qq.com |
313d7def613feab46fa56815b39931763d4c2f2d | eac63dea3e05328d1e9763c28c0cb007f4be23c7 | /Classes/HelloWorldScene.cpp | f548db40ab02aa0d90a7e60a9f6b74ccef70ffb6 | [] | no_license | junhaesung/campuslife | 383edc10c09f5573d2209a1fc50584ff0c83a9e1 | a5a7bca21f53a646c2defe15ae3cd624b82a9ba0 | refs/heads/master | 2020-12-24T20:33:27.486846 | 2016-05-04T19:54:40 | 2016-05-04T19:54:47 | 58,069,460 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 5,222 | cpp | #include "HelloWorldScene.h"
#include "RoomScene.h"
#include "OptionScene.h"
#include "AchievementScene.h"
#include "OpeningScene.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
// you may modify it.
// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
origin.y + closeItem->getContentSize().height/2));
/////////////////////////////
// 3. add your codes below...
// add a label shows "Hello World"
// create and initialize a label
/*
auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);
// position the label on the center of the screen
label->setPosition(Vec2(origin.x + visibleSize.width/2,
origin.y + visibleSize.height - label->getContentSize().height));
// add the label as a child to this layer
this->addChild(label, 1);
// add "HelloWorld" splash screen"
auto sprite = Sprite::create("HelloWorld.png");
// position the sprite on the center of the screen
sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));
// add the sprite as a child to this layer
this->addChild(sprite, 0);
*/
// 배경그리기
auto spr_bg = Sprite::create("background_opening_2x.png");
spr_bg->setPosition(Point(0, 0));
spr_bg->setAnchorPoint(Point(0, 0));
this->addChild(spr_bg);
// 메뉴 라벨
auto label_01 = Label::createWithSystemFont("RoomScene", "consolas", 30.0);
label_01->setTextColor(Color4B::BLACK);
auto label_02 = Label::createWithSystemFont("OptionScene", "consolas", 30.0);
label_02->setTextColor(Color4B::BLACK);
auto label_03 = Label::createWithSystemFont("AchievementScene", "consolas", 30.0);
label_03->setTextColor(Color4B::BLACK);
auto label_04 = Label::createWithSystemFont("Exit", "consolas", 30.0);
label_04->setTextColor(Color4B::BLACK);
auto label_05 = Label::createWithSystemFont("OpeningScene", "consolas", 30.0);
label_05->setTextColor(Color4B::BLACK);
// 메뉴 아이템
auto item_01 = MenuItemLabel::create(label_01, CC_CALLBACK_1(HelloWorld::loadRoomScene, this));
auto item_02 = MenuItemLabel::create(label_02, CC_CALLBACK_1(HelloWorld::loadOptionScene, this));
auto item_03 = MenuItemLabel::create(label_03, CC_CALLBACK_1(HelloWorld::loadAchievementScene, this));
auto item_04 = MenuItemLabel::create(label_04, CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
auto item_05 = MenuItemLabel::create(label_05, CC_CALLBACK_1(HelloWorld::loadOpeningScene, this));
// 메뉴
auto menu = Menu::create(item_01,item_02, item_03, item_04, item_05, NULL);
menu->alignItemsVertically();
this->addChild(menu);
return true;
}
void HelloWorld::menuCloseCallback(Ref* pSender)
{
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}
void HelloWorld::loadRoomScene(Ref *sender)
{
this->scheduleOnce(schedule_selector(HelloWorld::scheduleCallBackRoomScene), 0);
}
void HelloWorld::scheduleCallBackRoomScene(float delta)
{
//Director::getInstance()->pushScene(OptionScene::createScene());
Director::getInstance()->replaceScene(RoomScene::createScene());
}
void HelloWorld::loadOptionScene(Ref *sender)
{
this->scheduleOnce(schedule_selector(HelloWorld::scheduleCallBackOptionScene), 0);
}
void HelloWorld::scheduleCallBackOptionScene(float delta)
{
Director::getInstance()->pushScene(OptionScene::createScene());
//Director::getInstance()->replaceScene(OptionScene::createScene());
}
void HelloWorld::loadAchievementScene(Ref *sender)
{
this->scheduleOnce(schedule_selector(HelloWorld::scheduleCallBackAchievementScene), 0);
}
void HelloWorld::scheduleCallBackAchievementScene(float delta)
{
Director::getInstance()->pushScene(AchievementScene::createScene());
}
void HelloWorld::loadOpeningScene(Ref *sender)
{
this->scheduleOnce(schedule_selector(HelloWorld::scheduleCallBackOpeningScene), 0);
}
void HelloWorld::scheduleCallBackOpeningScene(float delta)
{
//Director::getInstance()->pushScene(OptionScene::createScene());
Director::getInstance()->replaceScene(OpeningScene::createScene());
}
| [
"junhaesung0428@hanmail.net"
] | junhaesung0428@hanmail.net |
dcc5ae5338feb3de492dedb2efe709fb4dde3bef | f9823b937b589e07af236bdd111dcd95458d348f | /IdasDream/Importer.cpp | d1158f5db375cc74d13bb66b17f82e76726c1f0e | [] | no_license | jercypackson/ezg18-IdasDream | ff083bccf76e65be47d8eae253258dd28638b65f | c72f088f41cf2ad10597c90caea715b9c8b73a92 | refs/heads/master | 2022-03-29T05:08:03.997264 | 2019-01-18T19:45:25 | 2019-01-18T19:45:25 | 148,811,915 | 0 | 0 | null | 2020-01-18T09:42:40 | 2018-09-14T16:00:49 | C++ | UTF-8 | C++ | false | false | 7,621 | cpp | #include "pch.h"
#include "Importer.h"
#include <filesystem>
#include "Extensions.h"
#include "StaticMesh.h"
#include "ShaderManager.h"
#include "TextureInfo.h"
#define STB_IMAGE_IMPLEMENTATION
#include <stb\stb_image.h>
#include "Hierachy.h"
#include "ArmatureObject.h"
#include "Bones.h"
Importer::Importer(std::string path)
: _path(path)
{
}
Importer::~Importer()
{
}
SceneObject* Importer::import()
{
auto so = new SceneObject("root", glm::mat4(1.f), nullptr);
//for each file in path
for (const auto & p : std::filesystem::directory_iterator(_path)) {
auto filePath = p.path().string();
std::string ending = "_";
if (0 == filePath.compare(filePath.length() - ending.length(), ending.length(), ending)) continue;
importFile(filePath, so);
}
return so;
}
void Importer::importFile(std::string file, SceneObject* root)
{
auto f = FileImporter(file, root);
}
void FileImporter::readNode(const aiNode* node, SceneObject* parent) {
SceneObject* s;
if (strcmp(node->mName.C_Str(), "Armature") == 0) {
_armatureInverse = glm::inverse(Extensions::toGlmMat4(node->mTransformation));
ArmatureObject* a = new ArmatureObject(node->mName.C_Str(), glm::mat4(1.0f), parent);
_armature = a;
s = a;
}
else {
s = parent->createChild(node->mName.C_Str(), Extensions::toGlmMat4(node->mTransformation), parent);
if (_armature != nullptr) {
s->setGlobalInverse(_armatureInverse);
}
}
//if (node->mNumMeshes == 0) do nothing, empty SceneObject
if (node->mNumMeshes == 1) {
auto mesh = _scene->mMeshes[node->mMeshes[0]];
auto gd = GeometryData();
gd.positions.reserve(mesh->mNumVertices);
gd.normals.reserve(mesh->mNumVertices);
gd.uvs.reserve(mesh->mNumVertices);
gd.indices.reserve(mesh->mNumVertices);
gd.boundingBox.minVertex = glm::vec4(glm::vec3(std::numeric_limits<float>::max()), 1);
gd.boundingBox.maxVertex = glm::vec4(glm::vec3(std::numeric_limits<float>::min()), 1);
for (unsigned int i = 0; i < mesh->mNumVertices; i++)
{
auto position = Extensions::toGlmVec3(mesh->mVertices[i]);
gd.positions.push_back(position);
gd.normals.push_back(Extensions::toGlmVec3(mesh->mNormals[i]));
gd.uvs.push_back(mesh->mTextureCoords[0] ?
glm::vec2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y) :
glm::vec2(0.0f, 0.0f));
//bb
if (position.x < gd.boundingBox.minVertex.x) gd.boundingBox.minVertex.x = position.x;
if (position.y < gd.boundingBox.minVertex.y) gd.boundingBox.minVertex.y = position.y;
if (position.z < gd.boundingBox.minVertex.z) gd.boundingBox.minVertex.z = position.z;
if (position.x > gd.boundingBox.maxVertex.x) gd.boundingBox.maxVertex.x = position.x;
if (position.y > gd.boundingBox.maxVertex.y) gd.boundingBox.maxVertex.y = position.y;
if (position.z > gd.boundingBox.maxVertex.z) gd.boundingBox.maxVertex.z = position.z;
}
for (unsigned int i = 0; i < mesh->mNumFaces; i++)
{
auto face = mesh->mFaces[i];
for (unsigned int j = 0; j < face.mNumIndices; j++) {
gd.indices.push_back(face.mIndices[j]);
}
}
std::shared_ptr<Material> mat;
aiMaterial *aiMat = _scene->mMaterials[mesh->mMaterialIndex];
auto diffMatCount = aiMat->GetTextureCount(aiTextureType_DIFFUSE);
aiColor4D* spec = new aiColor4D(0);
aiGetMaterialColor(aiMat, AI_MATKEY_COLOR_SPECULAR, spec);
glm::vec3 matCoeffs = glm::vec3(0.2, 0.9, spec->r * 2);
delete spec;
if (diffMatCount == 0) {
aiColor4D* pOut = new aiColor4D(1, 0, 0, 1); //default
aiGetMaterialColor(aiMat, AI_MATKEY_COLOR_DIFFUSE, pOut);
mat = std::make_shared<ColorMaterial>(ShaderManager::getShader("phongPhong"), Extensions::toGlmVec4(*pOut), matCoeffs, 1.0f);
delete pOut;
}
else if (diffMatCount == 1) {
aiString str;
aiMat->GetTexture(aiTextureType_DIFFUSE, 0, &str);
auto tex = Extensions::assets + "textures/" + str.C_Str();
int width = 0, height = 0, nrComponents = 0;
unsigned char *data = stbi_load(tex.c_str(), &width, &height, &nrComponents, 4);
TextureFormat f;
if (nrComponents == 1) {
f = TextureFormat::R8;
}
else if (nrComponents == 4) {
f = TextureFormat::SRGBA8;
}
else {
std::cout << "ERROR: This texture is not supported." << std::endl;
}
mat = std::make_shared<TextureMaterial>(ShaderManager::getShader("phongPhong"), matCoeffs, 0.0f,
std::make_shared<Texture2DBL>(width, height, f, SamplerInfo({ SamplerInfo::Filtering::BILINEAR }), data));
}
else {
std::cout << "ERROR: Multiple Textures on one object not supported." << std::endl;
}
aiString* matName = new aiString();
aiGetMaterialString(aiMat, AI_MATKEY_NAME, matName);
if (strstr(matName->C_Str(), "NOSHADOW")) {
mat->setReceivesShadow(false);
}
delete matName;
s->addData(gd, mat);
if (mesh->HasBones()) {
std::vector<BoneData> boneData(_scene->mMeshes[node->mMeshes[0]]->mNumVertices);
for (unsigned int i = 0; i < mesh->mNumBones; i++)
{
auto b = mesh->mBones[i];
unsigned int boneIdx = Bones::bone(b->mName.C_Str());
auto arm = dynamic_cast<ArmatureObject*>(Hierachy::find(_armature, b->mName.C_Str()));
arm->setBoneIdx(boneIdx);
arm->setOffsetMatrix(Extensions::toGlmMat4(b->mOffsetMatrix));
for (unsigned int j = 0; j < b->mNumWeights; j++) {
auto w = b->mWeights[j];
boneData[w.mVertexId].weight[boneIdx] = w.mWeight;
}
}
s->addBoneData(boneData);
}
}
else if (node->mNumMeshes > 1) {
std::cout << "Error: More than one mesh in node!" << std::endl;
}
for (unsigned int i = 0; i < node->mNumChildren; i++)
{
readNode(node->mChildren[i], s);
}
}
FileImporter::FileImporter(std::string file, SceneObject* root)
{
auto from = std::max(file.find_last_of("\\"), file.find_last_of('/')) + 1;
auto to = file.find_last_of('.');
_scene = _importer.ReadFile(file.c_str(), aiProcess_Triangulate);
if (_scene == nullptr) {
std::cout << "Scene " << file << " was null." << std::endl;
return;
}
_scene->mRootNode->mName = aiString(file.substr(from, to - from));
readNode(_scene->mRootNode, root);
//read animations
for (unsigned int a = 0; a < _scene->mNumAnimations; a++)
{
auto anim = _scene->mAnimations[a];
auto secondsPerTick = 1 / anim->mTicksPerSecond; //todo: compare to IdasDream::_ticksPerSecond
//iterate positionkeys, rot, scale
for (unsigned int c = 0; c < anim->mNumChannels; c++)
{
auto channel = anim->mChannels[c];
unsigned int numKeys = channel->mNumPositionKeys;
if (channel->mNumRotationKeys != numKeys) {
std::cout << "Error: Invalid animaion keys." << std::endl;
}
std::vector<float> time;
std::vector<Transform> transform;
for (unsigned int p = 0; p < channel->mNumPositionKeys; p++)
{
auto pos = channel->mPositionKeys[p];
auto rot = channel->mRotationKeys[p];
if (pos.mTime != rot.mTime) {
std::cout << "Error: Position and rotation timings do not match." << std::endl;
}
time.push_back(static_cast<float>(pos.mTime * secondsPerTick));
transform.push_back(Transform(Extensions::toGlmVec3(pos.mValue), Extensions::toGlmQuat(rot.mValue)));
}
//just checking
for (unsigned int s = 0; s < channel->mNumScalingKeys; s++)
{
if (Extensions::round(Extensions::toGlmVec3(channel->mScalingKeys[s].mValue), 3)
!= glm::vec3(1)) {
std::cout << "Error: Scaling in animation not supported" << std::endl;
}
}
auto arm = dynamic_cast<ArmatureObject*>(Hierachy::find(_armature, channel->mNodeName.C_Str()));
arm->addAnimation(anim->mName.C_Str(), Animation(time, transform));
}
}
}
FileImporter::~FileImporter()
{
}
| [
"laura.luidolt@gmail.com"
] | laura.luidolt@gmail.com |
b9cc99496e40d88707c8f60f888a444e160fcaa5 | 873002d555745752657e3e25839f6653e73966a2 | /model/CoreActivityOccurrenceSettings.cpp | 426fea77054d27c4368532e5a1ca62ac069d6cfe | [] | no_license | knetikmedia/knetikcloud-cpprest-client | e7e739e382c02479b0a9aed8160d857414bd2fbf | 14afb57d62de064fb8b7a68823043cc0150465d6 | refs/heads/master | 2021-01-23T06:35:44.076177 | 2018-03-14T16:02:35 | 2018-03-14T16:02:35 | 86,382,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,340 | cpp | /**
* Knetik Platform API Documentation latest
* This is the spec for the Knetik API. Use this in conjunction with the documentation found at https://knetikcloud.com.
*
* OpenAPI spec version: latest
* Contact: support@knetik.com
*
* NOTE: This class is auto generated by the swagger code generator 2.3.0-SNAPSHOT.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "CoreActivityOccurrenceSettings.h"
namespace com {
namespace knetikcloud {
namespace client {
namespace model {
CoreActivityOccurrenceSettings::CoreActivityOccurrenceSettings()
{
m_Boot_in_play = false;
m_Boot_in_playIsSet = false;
m_Custom_launch_address = U("");
m_Custom_launch_addressIsSet = false;
m_Host_status_control = false;
m_Host_status_controlIsSet = false;
m_Join_in_play = false;
m_Join_in_playIsSet = false;
m_Leave_in_play = false;
m_Leave_in_playIsSet = false;
m_Max_players = 0;
m_Max_playersIsSet = false;
m_Min_players = 0;
m_Min_playersIsSet = false;
m_Non_host_status_control = false;
m_Non_host_status_controlIsSet = false;
m_Results_trust = U("");
m_Results_trustIsSet = false;
}
CoreActivityOccurrenceSettings::~CoreActivityOccurrenceSettings()
{
}
void CoreActivityOccurrenceSettings::validate()
{
// TODO: implement validation
}
web::json::value CoreActivityOccurrenceSettings::toJson() const
{
web::json::value val = web::json::value::object();
if(m_Boot_in_playIsSet)
{
val[U("boot_in_play")] = ModelBase::toJson(m_Boot_in_play);
}
if(m_Custom_launch_addressIsSet)
{
val[U("custom_launch_address")] = ModelBase::toJson(m_Custom_launch_address);
}
if(m_Host_status_controlIsSet)
{
val[U("host_status_control")] = ModelBase::toJson(m_Host_status_control);
}
if(m_Join_in_playIsSet)
{
val[U("join_in_play")] = ModelBase::toJson(m_Join_in_play);
}
if(m_Leave_in_playIsSet)
{
val[U("leave_in_play")] = ModelBase::toJson(m_Leave_in_play);
}
if(m_Max_playersIsSet)
{
val[U("max_players")] = ModelBase::toJson(m_Max_players);
}
if(m_Min_playersIsSet)
{
val[U("min_players")] = ModelBase::toJson(m_Min_players);
}
if(m_Non_host_status_controlIsSet)
{
val[U("non_host_status_control")] = ModelBase::toJson(m_Non_host_status_control);
}
if(m_Results_trustIsSet)
{
val[U("results_trust")] = ModelBase::toJson(m_Results_trust);
}
return val;
}
void CoreActivityOccurrenceSettings::fromJson(web::json::value& val)
{
if(val.has_field(U("boot_in_play")))
{
setBootInPlay(ModelBase::boolFromJson(val[U("boot_in_play")]));
}
if(val.has_field(U("custom_launch_address")))
{
setCustomLaunchAddress(ModelBase::stringFromJson(val[U("custom_launch_address")]));
}
if(val.has_field(U("host_status_control")))
{
setHostStatusControl(ModelBase::boolFromJson(val[U("host_status_control")]));
}
if(val.has_field(U("join_in_play")))
{
setJoinInPlay(ModelBase::boolFromJson(val[U("join_in_play")]));
}
if(val.has_field(U("leave_in_play")))
{
setLeaveInPlay(ModelBase::boolFromJson(val[U("leave_in_play")]));
}
if(val.has_field(U("max_players")))
{
setMaxPlayers(ModelBase::int32_tFromJson(val[U("max_players")]));
}
if(val.has_field(U("min_players")))
{
setMinPlayers(ModelBase::int32_tFromJson(val[U("min_players")]));
}
if(val.has_field(U("non_host_status_control")))
{
setNonHostStatusControl(ModelBase::boolFromJson(val[U("non_host_status_control")]));
}
if(val.has_field(U("results_trust")))
{
setResultsTrust(ModelBase::stringFromJson(val[U("results_trust")]));
}
}
void CoreActivityOccurrenceSettings::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.'))
{
namePrefix += U(".");
}
if(m_Boot_in_playIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("boot_in_play"), m_Boot_in_play));
}
if(m_Custom_launch_addressIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("custom_launch_address"), m_Custom_launch_address));
}
if(m_Host_status_controlIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("host_status_control"), m_Host_status_control));
}
if(m_Join_in_playIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("join_in_play"), m_Join_in_play));
}
if(m_Leave_in_playIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("leave_in_play"), m_Leave_in_play));
}
if(m_Max_playersIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("max_players"), m_Max_players));
}
if(m_Min_playersIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("min_players"), m_Min_players));
}
if(m_Non_host_status_controlIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("non_host_status_control"), m_Non_host_status_control));
}
if(m_Results_trustIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + U("results_trust"), m_Results_trust));
}
}
void CoreActivityOccurrenceSettings::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix[namePrefix.size() - 1] != U('.'))
{
namePrefix += U(".");
}
if(multipart->hasContent(U("boot_in_play")))
{
setBootInPlay(ModelBase::boolFromHttpContent(multipart->getContent(U("boot_in_play"))));
}
if(multipart->hasContent(U("custom_launch_address")))
{
setCustomLaunchAddress(ModelBase::stringFromHttpContent(multipart->getContent(U("custom_launch_address"))));
}
if(multipart->hasContent(U("host_status_control")))
{
setHostStatusControl(ModelBase::boolFromHttpContent(multipart->getContent(U("host_status_control"))));
}
if(multipart->hasContent(U("join_in_play")))
{
setJoinInPlay(ModelBase::boolFromHttpContent(multipart->getContent(U("join_in_play"))));
}
if(multipart->hasContent(U("leave_in_play")))
{
setLeaveInPlay(ModelBase::boolFromHttpContent(multipart->getContent(U("leave_in_play"))));
}
if(multipart->hasContent(U("max_players")))
{
setMaxPlayers(ModelBase::int32_tFromHttpContent(multipart->getContent(U("max_players"))));
}
if(multipart->hasContent(U("min_players")))
{
setMinPlayers(ModelBase::int32_tFromHttpContent(multipart->getContent(U("min_players"))));
}
if(multipart->hasContent(U("non_host_status_control")))
{
setNonHostStatusControl(ModelBase::boolFromHttpContent(multipart->getContent(U("non_host_status_control"))));
}
if(multipart->hasContent(U("results_trust")))
{
setResultsTrust(ModelBase::stringFromHttpContent(multipart->getContent(U("results_trust"))));
}
}
bool CoreActivityOccurrenceSettings::getBootInPlay() const
{
return m_Boot_in_play;
}
void CoreActivityOccurrenceSettings::setBootInPlay(bool value)
{
m_Boot_in_play = value;
m_Boot_in_playIsSet = true;
}
bool CoreActivityOccurrenceSettings::bootInPlayIsSet() const
{
return m_Boot_in_playIsSet;
}
void CoreActivityOccurrenceSettings::unsetBoot_in_play()
{
m_Boot_in_playIsSet = false;
}
utility::string_t CoreActivityOccurrenceSettings::getCustomLaunchAddress() const
{
return m_Custom_launch_address;
}
void CoreActivityOccurrenceSettings::setCustomLaunchAddress(utility::string_t value)
{
m_Custom_launch_address = value;
m_Custom_launch_addressIsSet = true;
}
bool CoreActivityOccurrenceSettings::customLaunchAddressIsSet() const
{
return m_Custom_launch_addressIsSet;
}
void CoreActivityOccurrenceSettings::unsetCustom_launch_address()
{
m_Custom_launch_addressIsSet = false;
}
bool CoreActivityOccurrenceSettings::getHostStatusControl() const
{
return m_Host_status_control;
}
void CoreActivityOccurrenceSettings::setHostStatusControl(bool value)
{
m_Host_status_control = value;
m_Host_status_controlIsSet = true;
}
bool CoreActivityOccurrenceSettings::hostStatusControlIsSet() const
{
return m_Host_status_controlIsSet;
}
void CoreActivityOccurrenceSettings::unsetHost_status_control()
{
m_Host_status_controlIsSet = false;
}
bool CoreActivityOccurrenceSettings::getJoinInPlay() const
{
return m_Join_in_play;
}
void CoreActivityOccurrenceSettings::setJoinInPlay(bool value)
{
m_Join_in_play = value;
m_Join_in_playIsSet = true;
}
bool CoreActivityOccurrenceSettings::joinInPlayIsSet() const
{
return m_Join_in_playIsSet;
}
void CoreActivityOccurrenceSettings::unsetJoin_in_play()
{
m_Join_in_playIsSet = false;
}
bool CoreActivityOccurrenceSettings::getLeaveInPlay() const
{
return m_Leave_in_play;
}
void CoreActivityOccurrenceSettings::setLeaveInPlay(bool value)
{
m_Leave_in_play = value;
m_Leave_in_playIsSet = true;
}
bool CoreActivityOccurrenceSettings::leaveInPlayIsSet() const
{
return m_Leave_in_playIsSet;
}
void CoreActivityOccurrenceSettings::unsetLeave_in_play()
{
m_Leave_in_playIsSet = false;
}
int32_t CoreActivityOccurrenceSettings::getMaxPlayers() const
{
return m_Max_players;
}
void CoreActivityOccurrenceSettings::setMaxPlayers(int32_t value)
{
m_Max_players = value;
m_Max_playersIsSet = true;
}
bool CoreActivityOccurrenceSettings::maxPlayersIsSet() const
{
return m_Max_playersIsSet;
}
void CoreActivityOccurrenceSettings::unsetMax_players()
{
m_Max_playersIsSet = false;
}
int32_t CoreActivityOccurrenceSettings::getMinPlayers() const
{
return m_Min_players;
}
void CoreActivityOccurrenceSettings::setMinPlayers(int32_t value)
{
m_Min_players = value;
m_Min_playersIsSet = true;
}
bool CoreActivityOccurrenceSettings::minPlayersIsSet() const
{
return m_Min_playersIsSet;
}
void CoreActivityOccurrenceSettings::unsetMin_players()
{
m_Min_playersIsSet = false;
}
bool CoreActivityOccurrenceSettings::getNonHostStatusControl() const
{
return m_Non_host_status_control;
}
void CoreActivityOccurrenceSettings::setNonHostStatusControl(bool value)
{
m_Non_host_status_control = value;
m_Non_host_status_controlIsSet = true;
}
bool CoreActivityOccurrenceSettings::nonHostStatusControlIsSet() const
{
return m_Non_host_status_controlIsSet;
}
void CoreActivityOccurrenceSettings::unsetNon_host_status_control()
{
m_Non_host_status_controlIsSet = false;
}
utility::string_t CoreActivityOccurrenceSettings::getResultsTrust() const
{
return m_Results_trust;
}
void CoreActivityOccurrenceSettings::setResultsTrust(utility::string_t value)
{
m_Results_trust = value;
m_Results_trustIsSet = true;
}
bool CoreActivityOccurrenceSettings::resultsTrustIsSet() const
{
return m_Results_trustIsSet;
}
void CoreActivityOccurrenceSettings::unsetResults_trust()
{
m_Results_trustIsSet = false;
}
}
}
}
}
| [
"shawn.stout@knetik.com"
] | shawn.stout@knetik.com |
6de0e2426d71289cb70f442ab7a231a26eed4c38 | 3de5a328c9372fc996d265cf005a33f70a76f9de | /playstate/playstate/game/game_runner.cpp | f97f86066829840156e81cfd145331a4132142fa | [] | no_license | perandersson/playstate | 6c22942f295ee85482332776e6b94041e765247d | 7e6a426e834e43663846c3c1a5ae4f3a9fa94619 | refs/heads/master | 2020-04-28T00:49:30.853108 | 2013-10-14T17:24:35 | 2013-10-14T17:24:35 | 10,280,928 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,004 | cpp | #include "../memory/memory.h"
#include "../kernel.h"
#include "game_runner.h"
#include "scripted_configuration.h"
#include "../model/wavefront/wavefront_resource_loader.h"
#include "../rendering/graphics_driver.h"
#include "../input/input_system.h"
#include "../font/truetype/truetype_font_resource_loader.h"
#include "../model/md5/md5_mesh_resource_loader.h"
#include "../timer/timer_factory.h"
#include "../image/image_resource_loader.h"
#include "../sound/sound_engine.h"
#include "../processor/processors/linked_list_update_processor.h"
using namespace playstate;
namespace playstate
{
float32 GameDeltaTime = 0.0f;
float64 GameTotalTime = 0.0f;
}
template<> playstate::GameRunner* playstate::Singleton<playstate::GameRunner>::gSingleton = NULL;
GameRunner::GameRunner(IGame* game, IConfiguration* configuration)
: mGame(game), mConfiguration(configuration), mRenderPipeline(NULL), mRunning(true),
mCanvas(IWindow::Get(), IInputSystem::Get(), std::auto_ptr<IUpdateProcessor>(new LinkedListUpdateProcessor())), mTimer(NULL)
{
assert_not_null(game);
assert_not_null(configuration);
mTimer = ITimerFactory::Get().CreateTimer();
}
GameRunner::~GameRunner()
{
if(mTimer != NULL) {
delete mTimer;
mTimer = NULL;
}
if(mRenderPipeline != NULL) {
delete mRenderPipeline;
mRenderPipeline = NULL;
}
}
void GameRunner::Start()
{
if(!Initialize()) {
Release();
return;
}
if(!mGame->Initialize()) {
mGame->Release();
Release();
return;
}
mGame->LoadContent();
Run();
mGame->UnloadContent();
mGame->Release();
Release();
}
void GameRunner::Shutdown()
{
mRunning = false;
}
void GameRunner::Run()
{
ScriptSystem& scriptSystem = ScriptSystem::Get();
IKernel& kernel = IKernel::Get();
IWindow& window = IWindow::Get();
IRenderContext* screenRenderContext = IGraphicsDriver::Get().GetScreenRenderContext();
while(mRunning) {
GameDeltaTime = mTimer->GetElapsedAndRestart();
GameTotalTime += (float64)GameDeltaTime;
scriptSystem.SetGlobalVar("GameDeltaTime", GameDeltaTime);
scriptSystem.SetGlobalVar("GameTotalTime", GameTotalTime);
scriptSystem.SetGlobalVar("SecondsPerTick", SecondsPerTick);
mScene.Update();
mCanvas.Update();
mGame->Update();
if(mRenderPipeline != NULL)
mRenderPipeline->Render(mScene, mCanvas, mScene.GetActiveCamera());
screenRenderContext->SwapBuffers();
kernel.Process();
}
}
void GameRunner::SetRenderPipeline(IRenderPipeline* renderPipeline)
{
if(mRenderPipeline != NULL)
delete mRenderPipeline;
mRenderPipeline = renderPipeline;
}
bool GameRunner::Initialize()
{
IResourceManager& resourceManager = IResourceManager::Get();
IFileSystem& fileSystem = IFileSystem::Get();
IRenderSystem& renderSystem = IRenderSystem::Get();
IWindow& window = IWindow::Get();
ISoundEngine& soundEngine = ISoundEngine::Get();
// Register resource types
resourceManager.RegisterResourceType(new ImageResourceLoader(renderSystem, fileSystem), ".png");
resourceManager.RegisterResourceType(new WavefrontResourceLoader(resourceManager, fileSystem, renderSystem), ".obj");
resourceManager.RegisterResourceType(new TrueTypeFontResourceLoader(fileSystem, renderSystem), ".ttf");
//resourceManager.RegisterResourceType(new MD5MeshResourceLoader(fileSystem, resourceManager, renderSystem), ".md5mesh");
int32 width = mConfiguration->FindInt("window.width");
int32 height = mConfiguration->FindInt("window.height");
playstate::string title = mConfiguration->FindString("window.title");
window.SetSize(Point(width, height));
window.SetTitle(title);
window.AddWindowClosedListener(this);
// Set the sound volume
soundEngine.SetMasterVolume(mConfiguration->FindFloat("sound.mastervolume", 0.5f));
soundEngine.SetMusicVolume(mConfiguration->FindFloat("sound.musicvolume", 0.5f));
soundEngine.SetSoundEffectVolume(mConfiguration->FindFloat("sound.soundeffectvolume", 0.5f));
return true;
}
void GameRunner::Release()
{
IWindow::Get().RemoveWindowClosedListener(this);
}
bool GameRunner::OnWindowClosing()
{
mRunning = false;
return true;
}
const Scene& GameRunner::GetScene() const
{
return mScene;
}
Scene& GameRunner::GetScene()
{
return mScene;
}
Canvas& GameRunner::GetCanvas()
{
return mCanvas;
}
const Canvas& GameRunner::GetCanvas() const
{
return mCanvas;
}
//
// Script integration
//
namespace playstate
{
int Game_Start(lua_State* L)
{
ScriptedConfiguration* configuration = new ScriptedConfiguration(luaM_popcollection(L));
ScriptableGame* game = luaM_getobject<ScriptableGame>(L);
if(game != NULL) {
GameRunner runner(game, configuration);
runner.Start();
delete game;
delete configuration;
}
return 0;
}
int Game_SetRenderPipeline(lua_State* L)
{
int top1 = lua_gettop(L);
IRenderPipeline* pipeline = luaM_popobject<IRenderPipeline>(L);
int top2 = lua_gettop(L);
if(pipeline != NULL) {
GameRunner::Get().SetRenderPipeline(pipeline);
}
return 0;
}
int Game_Shutdown(lua_State* L)
{
GameRunner::Get().Shutdown();
return 0;
}
} | [
"dim.raven@gmail.com"
] | dim.raven@gmail.com |
363b572849295fda4397bd350dfb3a233bd44ba6 | dee4f176db476b621a208e1e9c8562740228c84c | /Cracking the Coding Interview/Linked List/Q1-2.cpp | 0c82441c177d14278029bdab94ed7983b6dc2e5d | [] | no_license | Mumbaikar007/Code | 7a62f2bcb9e01c06d3d83370f78298a76f94ee87 | b55ee260f3e4e33fb59ba6ed35c2ee29443bbc11 | refs/heads/master | 2021-09-27T05:31:00.973615 | 2018-11-06T10:42:31 | 2018-11-06T10:42:31 | 104,623,021 | 6 | 8 | null | 2018-10-31T15:55:05 | 2017-09-24T06:10:27 | Makefile | UTF-8 | C++ | false | false | 987 | cpp | //
// Created by optimus on 14/11/17.
//
# include <iostream>
using namespace std;
typedef struct Node {
int data;
Node *next;
};
Node *InsertTail ( Node *head, int data){
Node *newNode = (Node *) malloc(sizeof (Node));
newNode->data = data;
newNode->next = nullptr;
if ( head == nullptr)
return newNode;
else {
Node *traverse = head;
while ( traverse -> next != nullptr )
traverse = traverse->next;
traverse->next = newNode;
}
return head;
}
int main(){
Node *head = nullptr;
cout << "Enter 10 elements... \n";
int number;
for ( int i = 0 ; i < 10 ; i ++){
cin >> number;
head = InsertTail( head, number);
}
int last = 4;
Node *p1, *p2;
p1 = p2 = head;
for ( int i = 0 ; i < last ; i ++)
p1 = p1->next;
while (p1 != nullptr){
p1 = p1->next;
p2 = p2->next;
}
cout << p2->data << endl;
return 0;
} | [
"brainteaser97@gmail.com"
] | brainteaser97@gmail.com |
adfc7e4266fe4da6d19fe3e0ba0716e4b3474232 | c1626152963432aa221a4a9b0e4767a4608a51f7 | /src/boost/concept/usage.hpp | 9012c672ccf9716462cd8a6d44e42101c92f4ee2 | [
"MIT"
] | permissive | 107-systems/107-Arduino-BoostUnits | d2bffefc2787e99173797c9a89d47961718f9b03 | f1a4dfa7bf2af78c422bf10ba0c30e2a703cb69b | refs/heads/main | 2023-09-06T03:46:02.903776 | 2023-09-05T09:32:35 | 2023-09-05T09:32:35 | 401,328,494 | 0 | 0 | MIT | 2023-09-05T09:32:37 | 2021-08-30T12:03:20 | C++ | UTF-8 | C++ | false | false | 1,337 | hpp | // Copyright David Abrahams 2006. 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 BOOST_CONCEPT_USAGE_DWA2006919_HPP
# define BOOST_CONCEPT_USAGE_DWA2006919_HPP
# include "boost/concept/assert.hpp"
# include "boost/config/workaround.hpp"
# include "boost/concept/detail/backward_compatibility.hpp"
namespace boost { namespace concepts {
template <class Model>
struct usage_requirements
{
# if defined(BOOST_GCC) && (BOOST_GCC >= 110000)
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wnonnull"
# endif
~usage_requirements() { ((Model*)0)->~Model(); }
# if defined(BOOST_GCC) && (BOOST_GCC >= 110000)
# pragma GCC diagnostic pop
# endif
};
# if BOOST_WORKAROUND(__GNUC__, <= 3)
# define BOOST_CONCEPT_USAGE(model) \
model(); /* at least 2.96 and 3.4.3 both need this :( */ \
BOOST_CONCEPT_ASSERT((boost::concepts::usage_requirements<model>)); \
~model()
# else
# define BOOST_CONCEPT_USAGE(model) \
BOOST_CONCEPT_ASSERT((boost::concepts::usage_requirements<model>)); \
~model()
# endif
}} // namespace boost::concepts
#endif // BOOST_CONCEPT_USAGE_DWA2006919_HPP
| [
"cto@lxrobotics.com"
] | cto@lxrobotics.com |
edd7ade2de469b2590587363d6a16e536701d760 | 15ad8e2580fcbaf7470a0e47d5c9dab4f07aeb2e | /modules/mono/glue/runtime_interop.h | 9725ced593e32f76f7d3548991814d0232e638aa | [
"OFL-1.1",
"Bison-exception-2.2",
"FTL",
"GPL-3.0-or-later",
"BSD-3-Clause",
"Zlib",
"CC0-1.0",
"GPL-3.0-only",
"MIT",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-nvidia-2002",
"BSD-2-Clause",
"LicenseRef-scancode-other-permissive",
"LicenseRef-sc... | permissive | ConnectionMaster/godot | 1d6e1d9a9af69bc7bb4795a99c5cdc557b5c57e2 | c7c561ffd5d0e46cd1db3dbb583c6ca3841ab894 | refs/heads/master | 2023-08-17T03:29:47.558209 | 2022-12-13T13:36:30 | 2022-12-13T13:38:58 | 183,078,437 | 1 | 0 | MIT | 2023-01-10T02:27:10 | 2019-04-23T18:59:34 | C++ | UTF-8 | C++ | false | false | 2,397 | h | /*************************************************************************/
/* runtime_interop.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#ifndef RUNTIME_INTEROP_H
#define RUNTIME_INTEROP_H
#include "core/typedefs.h"
namespace godotsharp {
const void **get_runtime_interop_funcs(int32_t &r_size);
}
#endif // RUNTIME_INTEROP_H
| [
"ignalfonsore@gmail.com"
] | ignalfonsore@gmail.com |
732715a6de70e4fe19bb8dff60010319e7864645 | 451da728b7dc3cce884543e961a086fbb9fc0076 | /2018/11/zamka/zamka.cc | 9618c2d959c710d854bbeefb313d8b9f94f46164 | [] | no_license | chyld/captains-log | 628834c34c7ea76d7f7e82ebdc8546e018d6b937 | 6eb60ebc8b3f6fa2df20085802adbdafa815c115 | refs/heads/master | 2021-12-09T13:04:48.473496 | 2021-12-04T22:31:20 | 2021-12-04T22:31:20 | 113,895,598 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 703 | cc | // make clean; make zamka; cat samples/zamka.1.in | ./zamka
#include <iostream>
#include <string>
#include <math.h>
int getValue(int, int, int, int);
int main()
{
int L, D, X;
std::cin >> L >> D >> X;
const int N = getValue(L, D + 1, +1, X);
const int M = getValue(D, L - 1, -1, X);
std::cout << N << std::endl
<< M << std::endl;
}
int getValue(int start, int stop, int step, int value)
{
for (int i = start; i != stop; i += step)
{
auto s = std::to_string(i);
int sum = 0;
for (auto c : s)
{
sum += (c - 48);
}
if (sum == value)
{
return i;
}
}
return 0;
}
| [
"chyld.medford@gmail.com"
] | chyld.medford@gmail.com |
0a5cdc1fc1260a0e4e9833cd79ddf7fe52ffcb91 | 97ea3d4f34edb84ba79e3860ef54e6cefd61c9e9 | /fluid_simulation_for_dummies_impl/Application.h | 951d40fdfacf1102bb650b731f1a4ac086cd1774 | [] | no_license | Weikang01/fluid_simulation_for_dummies_impl | 01a710740b82e0840eddef43258f67b7e2f1468c | 594116a5ac6e3f67843d9a9ff64d5e4df1a70f32 | refs/heads/master | 2023-06-25T18:43:57.853067 | 2021-07-31T03:22:37 | 2021-07-31T03:22:37 | 389,456,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 406 | h | #pragma once
class GLFWwindow;
class FluidSquare;
class Application
{
public:
void run();
private:
void initSystem();
void initSquare();
void mainLoop();
void terminateSystem();
static void framebuffer_size_callback(GLFWwindow* window, int width, int height);
const int SCREEN_WIDTH = 128;
const int SCREEN_HEIGHT = 128;
GLFWwindow* window = nullptr;
private:
FluidSquare* square = nullptr;
};
| [
"lwkdota@qq.com"
] | lwkdota@qq.com |
7e8519ef93bf9e79e75e9496a3361d1320c7dfcf | 2666facc0e254b66a63e6007f1e7412b09dc8ab3 | /Vivado_HLS/cifar10_cnv_src/layer3_core.cpp | aa9a74350868fa5b85f6572205de8b1d61f9f2fc | [] | no_license | AILearnerLi/Winograd_CNN_accelerator | ced6f4115cffc3765952f1f7abdea268db52d4e9 | cb2dd447aeb4c002eca3445404b6882306c658d7 | refs/heads/main | 2023-08-17T14:52:50.964820 | 2021-10-09T18:53:30 | 2021-10-09T18:53:30 | 448,947,120 | 1 | 0 | null | 2022-01-17T15:25:11 | 2022-01-17T15:25:10 | null | UTF-8 | C++ | false | false | 11,018 | cpp | #include <iostream>
using namespace std;
#include "core.h"
//static ap_uint<simd_C0*bitw> weights_C0[OFM_CH_C0/out_parallel_C0][IMG_CH/simd_C0][pe_num_C0] = {
//#include "../data/vgg_11_pack/conv0_packed_out1.txt"
//};
static B_C0 bias_C0[OFM_CH_C0/out_parallel_C0][out_parallel_C0] = {
#include "../data/cifar10_cnv/qconv0_b.txt"
};
//static ap_uint<simd_C1*bitw> weights_C1[OFM_CH_C1/out_parallel_C1][OFM_CH_C0/simd_C1][pe_num_C1] = {
//#include "../data/vgg_11_pack/conv1_packed_out1.txt"
//};
static B_C1 bias_C1[OFM_CH_C1/out_parallel_C1][out_parallel_C1] = {
#include "../data/cifar10_cnv/qconv1_b.txt"
};
//static ap_uint<simd_C2*bitw> weights_C2[OFM_CH_C2/out_parallel_C2][OFM_CH_C1/simd_C2][pe_num_C2] = {
//#include "../data/vgg_11_pack/conv2_packed_out1.txt"
//};
static B_C2 bias_C2[OFM_CH_C2/out_parallel_C2][out_parallel_C2] = {
#include "../data/cifar10_cnv/qconv2_b.txt"
};
#if !__SYNTHESIS__
#include "mem.hpp"
ap_uint<simd_C0*bitw> ***weights_C0;
ap_uint<simd_C1*bitw> ***weights_C1;
ap_uint<simd_C2*bitw> ***weights_C2;
#else
static ap_uint<simd_C0*bitw> weights_C0[OFM_CH_C0/out_parallel_C0][IMG_CH/simd_C0][pe_num_C0] = {
#include "../data/cifar10_cnv/conv0_packed_out1.txt"
};
static ap_uint<simd_C1*bitw> weights_C1[OFM_CH_C1/out_parallel_C1][OFM_CH_C0/simd_C1][pe_num_C1] = {
#include "../data/cifar10_cnv/conv1_packed_out2.txt"
};
static ap_uint<simd_C2*bitw> weights_C2[OFM_CH_C2/out_parallel_C2][OFM_CH_C1/simd_C2][pe_num_C2] = {
#include "../data/cifar10_cnv/conv2_packed_out2.txt"
};
#endif
//static ap_uint<simd_C2*bitw> weights_C2[OFM_CH_C2/out_parallel_C2][OFM_CH_C1/simd_C2][pe_num_C2];
//static B_C2 bias_C2[OFM_CH_C2/out_parallel_C2][out_parallel_C2];
//static Fixed_Weights<simd*bitw, OFM_CH_C1/out_parallel, ifmChannels/simd, pe_num> weights_C1;
//static Fixed_Weights<simd_C2*bitw, OFM_CH_C2/out_parallel_C2, OFM_CH_C1/simd_C2, pe_num_C2> weights_C2;
//void nn_top(ap_uint<128> *in, hls::stream<TO> &out, unsigned int reps){
void doCompute( TI *in, TO_32 *out,int const reps){
#pragma HLS DATAFLOW
hls::stream<TI> inStream_0;
// #pragma HLS STREAM variable=inStream_0 depth=30
hls::stream<ap_uint<bitw*1>> inStream_1("unit_str_docomp"); //After adjusting width of stream
// #pragma HLS STREAM variable=inStream_1 depth=30
hls::stream<ap_uint<bitw*IMG_CH>> c0_in_padded;
// #pragma HLS STREAM variable=c1_in_padded depth=450
hls::stream<ap_uint<bitw*out_parallel_C0>> c0_outstream;
//Conv1
hls::stream<ap_uint<bitw*OFM_CH_C0>> c1_in_padded;
hls::stream<ap_uint<bitw*out_parallel_C1>> c1_outstream;
//Conv2
hls::stream<ap_uint<bitw*OFM_CH_C1>> c2_in_padded;
hls::stream<ap_uint<out_size_C2>> c2_outstream; //*4 due to no maxpool
hls::stream<TO_32> outstream("outstream");
//static ap_uint<simd*bitw> weights_C1[OFM_CH_C1/out_parallel][ifmChannels/simd][pe_num] ={
//#include "../data/weights_bn_v1_pack/conv1_packed_out4.txt"
//};
//
//static B_C1 bias_C1[OFM_CH_C1/out_parallel][out_parallel] = {
//#include "../data/weights_bn_v1_pack/qconv1_b.txt"
//};
//
//static ap_uint<simd_C2*bitw> weights_C2[OFM_CH_C2/out_parallel_C2][OFM_CH_C1/simd_C2][pe_num_C2] ={
//#if out_parallel_C2 == 2
// #include "../data/weights_bn_v1_pack/conv2_packed_out2.txt"
////#elif out_parallel_C2 == 1
//// #include "../data/qconv2_packed_simd2_out1.txt"
////#elif out_parallel_C2 ==4
//// #include "../data/qconv2_packed_simd2_out4.txt"
//#elif
// assert(1)
//#endif
//};
//
//static B_C2 bias_C2[OFM_CH_C2/out_parallel_C2][out_parallel_C2] = {
//#include "../data/weights_bn_v1_pack/qconv2_b.txt"
//};
Mem2Stream<MEM_BANDWIDTH, INPUT_depth>(in, inStream_0);
//stream width=MEM_BANDWIDTH
StreamingDataWidthConverter_Batch<TI::width, bitw*1, INPUT_depth>
(inStream_0, inStream_1, reps);
//----------------------------------------//
#if !__SYNTHESIS__
layer_features l = {OFM_CH_C0/out_parallel_C0, IMG_CH/simd_C0, pe_num_C0};
weights_C0 = new ap_uint<simd_C0*bitw> **[l.ch];
for(int r=0; r< l.ch;r++){
weights_C0[r] = new ap_uint<simd_C0*bitw> *[l.row];
for(int col=0; col<l.row; col++)
weights_C0[r][col] = new ap_uint<simd_C0*bitw> [l.col];
}
load<ap_uint<simd_C0*bitw>>("/home/ab/projects/hls_projects/cifar10_cnv/data/cifar10_cnv/conv0_packed_out1.txt", l, weights_C0);
#endif
//----------------------------------------//
//stream width=bitw*IMG_CH
Streaming_pad<IMG_DIM, 3, 1, IMG_CH, 1, IMG_CH,
ap_uint<bitw>>(inStream_1, c0_in_padded);
convlayer<
4,
2,
bitw,
IFM_DIM_C0,
OFM_DIM_C0,
IMG_CH,
trans_bit_C0, OFM_CH_C0, simd_C0, pe_num_C0,IMG_CH,
out_shift_C0, out_size_C0,
ap_int<8>, ap_int<8>, ap_int<8>,has_bias_C0,
ap_int<32>
>(c0_in_padded, c0_outstream, weights_C0, bias_C0, reps);
//---------------- Conv1 -----------------//
#if !__SYNTHESIS__
// deallocate memory for conv0
for (int i = 0; i < l.ch; i++)
{
for (int j = 0; j < l.row; j++)
delete[] weights_C0[i][j];
delete[] weights_C0[i];
}
delete[] weights_C0;
//Allocating Weights for conv1
l = {OFM_CH_C1/out_parallel_C1, OFM_CH_C0/simd_C1, pe_num_C1};
weights_C1 = new ap_uint<simd_C1*bitw> **[l.ch];
for(int r=0; r< l.ch;r++){
weights_C1[r] = new ap_uint<simd_C1*bitw> *[l.row];
for(int col=0; col<l.row; col++)
weights_C1[r][col] = new ap_uint<simd_C1*bitw> [l.col];
}
load<ap_uint<simd_C1*bitw>>("/home/ab/projects/hls_projects/cifar10_cnv/data/cifar10_cnv/conv1_packed_out2.txt", l, weights_C1);
#endif
//----------------------------------------//
Streaming_pad<OFM_DIM_C0, 3, 1, OFM_CH_C0, out_parallel_C0,
OFM_CH_C0, ap_uint<bitw>>(c0_outstream, c1_in_padded);
convlayer<
4,
2,
bitw,
IFM_DIM_C1,
OFM_DIM_C1,
OFM_CH_C0,
trans_bit_C1, OFM_CH_C1, simd_C1,pe_num_C1,OFM_CH_C0,
out_shift_C1, out_size_C1,
ap_int<8>, ap_int<8>, ap_int<8>, has_bias_C1,
ap_int<32>
>(c1_in_padded, c1_outstream, weights_C1, bias_C1, reps);
//---------------- Conv2 -----------------//
#if !__SYNTHESIS__
// deallocate memory for conv1
for (int i = 0; i < l.ch; i++)
{
for (int j = 0; j < l.row; j++)
delete[] weights_C1[i][j];
delete[] weights_C1[i];
}
delete[] weights_C1;
//Allocating Weights for conv2
l = {OFM_CH_C2/out_parallel_C2, OFM_CH_C1/simd_C2, pe_num_C2};
weights_C2 = new ap_uint<simd_C2*bitw> **[l.ch];
for(int r=0; r< l.ch;r++){
weights_C2[r] = new ap_uint<simd_C2*bitw> *[l.row];
for(int col=0; col<l.row; col++)
weights_C2[r][col] = new ap_uint<simd_C2*bitw> [l.col];
}
load<ap_uint<simd_C1*bitw>>("/home/ab/projects/hls_projects/cifar10_cnv/data/cifar10_cnv/conv2_packed_out2.txt", l, weights_C2);
#endif
//----------------------------------------//
Streaming_pad<OFM_DIM_C1, 3, 1, OFM_CH_C1, out_parallel_C1,
OFM_CH_C1, ap_uint<bitw>>(c1_outstream, c2_in_padded);
convlayer<
4,
2,
bitw,
IFM_DIM_C2,
OFM_DIM_C2,
OFM_CH_C1,
trans_bit_C2, OFM_CH_C2, simd_C2,pe_num_C2,OFM_CH_C1,
out_shift_C2, out_size_C2,
ap_int<8>, ap_int<8>, ap_int<8>, has_bias_C2,
ap_int<32>
>(c2_in_padded, c2_outstream, weights_C2, bias_C2, reps);
//----------------------------------------//
#if !__SYNTHESIS__
// deallocate memory for conv1
for (int i = 0; i < l.ch; i++)
{
for (int j = 0; j < l.row; j++)
delete[] weights_C2[i][j];
delete[] weights_C2[i];
}
delete[] weights_C2;
#endif
//----------------------------------------//
StreamingDataWidthConverter_Batch<TO::width, TO_32::width, (OFM_DIM_C2*OFM_DIM_C2*OFM_CH_C2)/(out_parallel_C2)>(c2_outstream, outstream, reps);
Stream2Mem<TO_32::width,(OFM_DIM_C2*OFM_DIM_C2*OFM_CH_C2)/(out_parallel_C2*2) >(outstream, out);
}
void DoMemInit(unsigned int targetmem,unsigned int target_ch,
unsigned int target_row, unsigned int target_col,ap_uint<64> val){
switch(targetmem){
case 1:
weights_C0[target_ch][target_row][target_col] = val;
break;
case 2:
bias_C0[target_row][target_col] = val(B_C0::width-1,0);
break;
case 3:
weights_C1[target_ch][target_row][target_col] = val;
break;
case 4:
bias_C1[target_row][target_col] = val(B_C1::width-1,0);
break;
case 5:
weights_C2[target_ch][target_row][target_col] = val;
break;
case 6:
bias_C2[target_row][target_col] = val(B_C2::width-1,0);
break;
}
}
//
//void Read_Vals(unsigned int targetmem,unsigned int target_ch,
// unsigned int target_row, unsigned int target_col,ap_uint<64> val){
//
// switch(targetmem){
// case 1:
// val = weights_C1[target_ch][target_row][target_col];
// break;
// case 2:
// val(B_C1::width-1,0) = bias_C1[target_row][target_col];
// break;
// case 3:
// val = weights_C2[target_ch][target_row][target_col];
// break;
// case 4:
// val(B_C2::width-1,0) = bias_C2[target_row][target_col];
// break;
// }
//
//}
void nn_top( TI *in, TO_32 *out,
bool doInit,
unsigned int targetmem,
unsigned int target_ch, unsigned int target_row, unsigned int target_col,
ap_uint<64> val, unsigned int numReps){
//void nn_top(hls::stream<TI> &in, hls::stream<TO> &out){
//#pragma HLS INTERFACE axis port=in
//#pragma HLS INTERFACE axis port=out
//#pragma HLS INTERFACE s_axilite port=reps bundle=ctrl_bus
//#pragma HLS INTERFACE s_axilite port=return bundle=ctrl_bus
// signals to be mapped to the AXI master ports
#pragma HLS INTERFACE m_axi offset=slave port=in bundle=inmem depth=384
#pragma HLS INTERFACE s_axilite port=in bundle=ctrl_bus
//depth = (OFM_DIM_C2*OFM_DIM_C2*OFM_CH_C2)/(MEM_BANDWIDTH/8)+1
#pragma HLS INTERFACE m_axi offset=slave port=out bundle=outmem depth=4096 //*****change when changing out_parallel***//
#pragma HLS INTERFACE s_axilite port=out bundle=ctrl_bus
//#pragma HLS INTERFACE m_axi offset=slave port=val bundle=valmem
// signals to be mapped to the AXI Lite slave port
#pragma HLS INTERFACE s_axilite port=return bundle=ctrl_bus
#pragma HLS INTERFACE s_axilite port=doInit bundle=ctrl_bus
#pragma HLS INTERFACE s_axilite port=targetmem bundle=ctrl_bus
#pragma HLS INTERFACE s_axilite port=target_ch bundle=ctrl_bus
#pragma HLS INTERFACE s_axilite port=target_row bundle=ctrl_bus
#pragma HLS INTERFACE s_axilite port=target_col bundle=ctrl_bus
#pragma HLS INTERFACE s_axilite port=val bundle=ctrl_bus
#pragma HLS INTERFACE s_axilite port=numReps bundle=ctrl_bus
//Partitioning arrays
#pragma HLS ARRAY_PARTITION variable=weights_C0 complete dim=3
#pragma HLS ARRAY_PARTITION variable=weights_C1 complete dim=3
#pragma HLS ARRAY_PARTITION variable=weights_C2 complete dim=3
#pragma HLS ARRAY_PARTITION variable=bias_C0 complete dim=2
#pragma HLS ARRAY_PARTITION variable=bias_C1 complete dim=2
#pragma HLS ARRAY_PARTITION variable=bias_C2 complete dim=2
//Array Resources
#pragma HLS RESOURCE variable=weights_C0 core=RAM_2P
#pragma HLS RESOURCE variable=weights_C1 core=RAM_2P
#pragma HLS RESOURCE variable=weights_C2 core=RAM_2P
#pragma HLS RESOURCE variable=bias_C0 core=RAM_2P_LUTRAM
#pragma HLS RESOURCE variable=bias_C1 core=RAM_2P_LUTRAM
#pragma HLS RESOURCE variable=bias_C2 core=RAM_2P_LUTRAM
if (doInit) {
DoMemInit(targetmem, target_ch, target_row, target_col, val);
}
else {
doCompute(in, out, numReps);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
7e5b8d8ba32993c92729392c9ae3d22b48cf789e | a01851ad710157c72e2a122a1f7735639f6db225 | /L687. Longest Univalue Path.cpp | c545c5f4ad9c274803721fff0d1c7afcc9af82b5 | [] | no_license | we-are-kicking-lhx/xinxinalgorithm | 9089629b210a5a0e199f374c74afc24742644f03 | e988e3bca6438af6933378f374afb2627a5708fe | refs/heads/master | 2021-06-27T10:50:22.979162 | 2020-11-23T07:01:23 | 2020-11-23T07:01:23 | 173,912,054 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 715 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
if(!root) return 0;
int ans=0;
func(root,ans);
return ans;
}
int func(TreeNode* root,int& ans){
if(!root) return 0;
int l=func(root->left,ans);
int r=func(root->right,ans);
int pl=0,pr=0;
if(root->left && root->val==root->left->val) pl=l+1;
if(root->right && root->val==root->right->val) pr=r+1;
ans=max(ans,pl+pr);
return max(pr,pl);
}
}; | [
"haoxin18@foxmail.com"
] | haoxin18@foxmail.com |
aae8f731cdd4c597c0ae34739861333a1ee23b6c | 13611380423651017f2ff6d52ec080108344367d | /Project2/studentrecord.h | 5a4cfaf0a43f699274ee91ad2a305d0cef445ca0 | [] | no_license | nregmee19/eclipse-workspace1 | 2712affad3fd1eb3166a8e44ed8dee4ecf0a194d | 643428217c5b15b9ef83e8ebf84cd8d840a5b349 | refs/heads/master | 2020-03-30T06:20:12.423445 | 2018-09-29T10:54:35 | 2018-09-29T10:54:35 | 150,853,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 487 | h | /*
* studentrecord.h
*
* Created on: Sep 21, 2017
* Author: Niraj Regmee
*/
#ifndef STUDENTRECORD_H_
#define STUDENTRECORD_H_
#include <iostream>
#include <string>
using namespace std;
class studentrecord {
private:
string studentName;
string studentID;
string studentAddress;
double studentGPA;
public:
studentrecord();
studentrecord(string, string, string, double);
virtual ~studentrecord();
void display();
};
#endif /* STUDENTRECORD_H_ */
| [
"43698879+nregmee19@users.noreply.github.com"
] | 43698879+nregmee19@users.noreply.github.com |
a789fe2fdad4e2bd0f105b5c88e8f2e456173b4f | dab17edba4d031ef4892bd373892b3ea39eac992 | /KleptoEngine/AnimationSequence.h | d199e135a346ffec94863aaab08bc7e5b6a20bc5 | [] | no_license | McMasterGameDesignAssociation/current-version | fc13f74693d5ef3e2da76a27d4ee99d972e496c4 | df89d6d7a3abafd3333d9115d1cbc370d88f34b7 | refs/heads/master | 2020-12-24T14:02:00.284263 | 2015-02-25T16:53:39 | 2015-02-25T16:53:39 | 26,332,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,053 | h | /*
COPYRIGHT BENJAMIN ISHERWOOD 11/02/2015
THIS SOFTWARE IS INTENDED FOR OPEN SOURCE USE, REDISTRIBUTION
IS ENCOURAGE
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef ANIMATION_SEQUENCE_H
#define ANIMATION_SEQUENCE_H
#include "engineStdafx.h"
#include "BaseEntity.h"
class AnimationSequence : public BasicEntity
{
private:
vector<SquareFV> frames;
protected:
friend AnimationSequence;
AnimationSequence();
AnimationSequence(string desc, string name, ULong objectID);
void addFrame(SquareFV nextFrame);
void addFrame(FV2 * nextFrame);
void resetSequence(void);
Uint getNumberOfFrames(void) const;
};
#endif | [
"isherwb@mcmaster.ca"
] | isherwb@mcmaster.ca |
c6dd67429d75e81484c665e7f27cba50aa2f0fb9 | 6e8453fa6d67d864e0fca2206fac05447ebaf37f | /coordinates.h | 763342496b0d6e36500b49a16ab60ac64e95e53f | [] | no_license | gunjinudv/pfe | 19e3420877ed1adbdfcb38f758e09e1dc44828aa | ef53bb71bf800779a2e850013b7af613507b2a00 | refs/heads/master | 2021-09-05T23:21:20.663848 | 2018-01-30T11:45:42 | 2018-01-30T11:45:42 | 118,746,665 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 858 | h | #ifndef COORDINATESHEADER
#define COORDINATESHEADER
#include<stdio.h>
#include "voxel.h"
class COORDINATES
{
public:
int vol;
double max_vp, max_dir[3];
double x, y, z;
COORDINATES *prec;
COORDINATES *suiv;
COORDINATES(double i,double j,double k, double vp, double *vectp, int v);
~COORDINATES();
};
void incoordinates(COORDINATES *p,COORDINATES * &first,COORDINATES * &last);
void delcoordinates(COORDINATES* &p,COORDINATES * &first,COORDINATES * &last);//ne pas l'appeler avec first(last) a la place de p; il faut: q=first; delcoordinates(q,first,last);
void freelistcoordinates(COORDINATES * &first,COORDINATES* &last);
void extractcoordinates(COORDINATES* &p,COORDINATES * &first,COORDINATES * &last);//ne pas l'appeler avec first(last) a la place de p; il faut: q=first; extractcoordinates(q,first,last);
#endif | [
"gunjin.udval@telecom-sudparis.eu"
] | gunjin.udval@telecom-sudparis.eu |
8fb013aba7f33776828fa14cc4587e52e8352c47 | 937d4cbee661cc6a044dd119704e1ed8f1b4c6a5 | /src/TicTacToeUnlimited.cpp | 954cd3fb2ca048a6912c6ae3006be6eea4a3ef8d | [] | no_license | fo2rist/tictactoeunlimited | 5cd6a40b1758bbd8e094704416be245fb6a11191 | 6944ee3816790fc7fcca25c0eac69147723ba3d7 | refs/heads/master | 2021-05-04T16:37:52.055666 | 2018-02-05T04:32:12 | 2018-02-05T04:32:12 | 120,254,716 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 974 | cpp | // Drilldown navigation project template
#include "TicTacToeUnlimited.hpp"
#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/AbstractPane>
#include "GameLogic.hpp"
#include "GameViewController.hpp"
using namespace bb::cascades;
TicTacToeUnlimited::TicTacToeUnlimited(bb::cascades::Application *app)
: QObject(app)
{
// create scene document from main.qml asset
// set parent to created document to ensure it exists for the whole application lifetime
QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
GameLogic *game = new GameLogic(this);
qml->setContextProperty("game", game);
qml->setContextProperty("gameController", new GameViewController(game, this));
// create root object for the UI
AbstractPane *root = qml->createRootObject<AbstractPane>();
// set created root object as a scene
app->setScene(root);
//Disable menu
app->setMenuEnabled(false);
}
| [
"fo2@inbox.ru"
] | fo2@inbox.ru |
dba69a9afb3cf454874dad2c8647dcb4d9ab6f5b | 6b9383fe4c720561947c3fc00dcad55fcf1b5522 | /Meteor/source/meteor/renderer/camera.cpp | 0db04c11966d380cd0908d62622b1c0c0cfb30d8 | [
"Apache-2.0"
] | permissive | NikiNatov/Meteor_Engine_DX11 | 4c350670ae0a6d95c6cde50ba4526eede619ca64 | fe6206ddefe15682a37c2df9c1b293b8ea0e3956 | refs/heads/main | 2023-05-14T16:48:05.611397 | 2021-06-07T16:55:57 | 2021-06-07T16:55:57 | 374,739,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,691 | cpp | #include "pch.h"
#include "camera.h"
#include <glm\gtc\matrix_transform.hpp>
namespace meteor
{
// --------------------------------------------------------------------------------------------------------------------------------------
Camera::Camera()
{
RecalculateProjection();
}
// --------------------------------------------------------------------------------------------------------------------------------------
Camera::Camera(mtrFloat fov, mtrFloat aspectRatio, mtrFloat nearPlane /*= 0.1f*/, mtrFloat farPlane /*= 1000.0f*/)
: m_FOV(fov), m_AspectRatio(aspectRatio), m_Near(nearPlane), m_Far(farPlane)
{
RecalculateProjection();
}
// --------------------------------------------------------------------------------------------------------------------------------------
void Camera::SetPerspective(mtrFloat fov, mtrFloat nearPlane, mtrFloat farPlane)
{
m_FOV = fov;
m_Near = nearPlane;
m_Far = farPlane;
RecalculateProjection();
}
// --------------------------------------------------------------------------------------------------------------------------------------
void Camera::SetViewport(mtrUInt width, mtrUInt height)
{
if (height == 0)
return;
m_AspectRatio = (mtrFloat)width / (mtrFloat)height;
RecalculateProjection();
}
// --------------------------------------------------------------------------------------------------------------------------------------
void Camera::RecalculateProjection()
{
m_ProjMatrix = glm::perspective(glm::radians(m_FOV), m_AspectRatio, m_Near, m_Far);
}
}
| [
"nikinatov0046@gmail.com"
] | nikinatov0046@gmail.com |
283c3d3a673dd85a03476007e5f42972de256364 | 51df1f271c4a46321a18ddc3e816f443bdaaa606 | /src/videoplayer/videoplayer.h | 23e1dfa0dd0788258c9a3d5598407da6032f9e09 | [] | no_license | nakadasanda/VideoPlayer | 1b2811337f6259e63ab9b7a39d2ad1391c6c2043 | 45f4d3aa61646e2433e09d92e1c547a21b1a5276 | refs/heads/master | 2022-12-06T00:01:28.257280 | 2020-07-30T12:44:55 | 2020-07-30T12:44:55 | 276,336,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | h | #ifndef VIDEOPLAYER_H
#define VIDEOPLAYER_H
#include <QThread>
#include <QImage>
class VideoPlayer : public QThread
{
Q_OBJECT
public:
explicit VideoPlayer();
~VideoPlayer();
void setFileName(QString path){mFileName = path;}
void startPlay();
signals:
void sig_GetOneFrame(QImage img );
protected:
void run();
private:
QString mFileName;
};
#endif // VIDEOPLAYER_H
| [
"you@example.com"
] | you@example.com |
81ca6053506977fbcd2fc4304b74fc183cd2b757 | 3aaccbef6d4c3b10717e2e4389e66b9fbbcfa10a | /prj.labs/lab05/lab05.cpp | 043385117765071ea231373e839883acde4b6633 | [] | no_license | Lada-Rom/image-processing | 8759ef40408c44d413775f17f5826588177a484d | 53b3db861a066dd22dcdcefb4201f4f912da89db | refs/heads/master | 2023-04-16T17:06:10.548602 | 2021-04-27T20:07:20 | 2021-04-27T20:07:20 | 362,207,780 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,719 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <opencv2/opencv.hpp>
std::vector<cv::Mat> getImages(int n) {
std::vector<cv::Mat> images;
for (size_t i{ 1 }; i <= n; ++i)
images.push_back(cv::imread(
"../../../data/lab05.src" + std::to_string(i) + ".png",
cv::IMREAD_GRAYSCALE));
return images;
}
std::vector<std::vector<cv::Point2f>> getSourcePoints() {
std::vector<std::vector<cv::Point2f>> points;
points.push_back({
{ 2428, 3370 }, { 250, 3465 },
{ 192, 758 }, { 2357, 702 } });
points.push_back({
{ 410, 575 }, { 1903, 557 },
{ 1908, 2436 }, { 410, 2426 } });
points.push_back({
{ 546, 1962 }, { 590, 479 },
{ 2484, 389 }, { 2481, 2042 } });
points.push_back({
{ 674, 1932 }, { 734, 578 },
{ 2457, 398 }, { 2495, 2042 } });
points.push_back({
{ 584, 1764 }, { 671, 383 },
{ 2453, 380 }, { 2382, 1918 } });
return points;
}
void drawPoints(std::vector<cv::Mat>& src_imgs, cv::Mat& dst_img,
const std::vector<std::vector<cv::Point2f>>& src_keypoints,
const std::vector<cv::Point2f>& dst_keypoints, bool write = false) {
for (size_t i{}; i < src_imgs.size(); ++i)
for (size_t j{}; j < src_keypoints[i].size(); ++j)
cv::line(src_imgs[i], src_keypoints[i][j],
src_keypoints[i][(j + 1) % src_keypoints[i].size()], 0);
for (size_t j{}; j < dst_keypoints.size(); ++j)
cv::line(dst_img, dst_keypoints[j],
dst_keypoints[(j + 1) % dst_keypoints.size()], 0);
if (write) {
for (size_t i{ 1 }; i <= src_imgs.size(); ++i)
cv::imwrite("../../../data/lab05.pnt" + std::to_string(i)
+ ".png", src_imgs[i - 1]);
cv::imwrite("../../../data/lab05.pnt0.png", dst_img);
}
}
std::vector<cv::Mat> findMultipleHomography(
const std::vector<std::vector<cv::Point2f>>& srcs,
const std::vector<cv::Point2f>& dst) {
std::vector<cv::Mat> Hs;
for (size_t i{}; i < srcs.size(); ++i)
Hs.push_back(cv::findHomography(srcs[i], dst));
return Hs;
}
void warpMultiplePerspective(
const std::vector<cv::Mat>& srcs, std::vector<cv::Mat>& dsts,
const std::vector<cv::Mat>& Hs, const cv::Size& size, bool write = false) {
for (size_t i{}; i < srcs.size(); ++i)
cv::warpPerspective(srcs[i], dsts[i], Hs[i], size);
if (write)
for (size_t i{1}; i <= dsts.size(); ++i)
cv::imwrite("../../../data/lab05.dst" + std::to_string(i)
+ ".png", dsts[i - 1]);
}
void MIPTBinarization(
const cv::Mat& source_image, cv::Mat& bin_image,
size_t radius, double sigma, int d0, int thres) {
cv::Rect rect;
cv::Mat G = cv::Mat::zeros(source_image.size(), CV_8UC1);
std::cout << "Matrix G" << std::endl;
cv::GaussianBlur(
source_image, G, cv::Size(2 * radius + 1, 2 * radius + 1), sigma);
std::cout << "Matrix M" << std::endl;
cv::Mat M = cv::Mat::zeros(source_image.size(), CV_8UC1);
double source_pixel, gauss_pixel;
for (size_t i{}; i < M.cols; ++i) {
for (size_t j{}; j < M.rows; ++j) {
source_pixel = static_cast<double>(
source_image.at<uchar>(cv::Point(i, j)));
gauss_pixel = static_cast<double>(
G.at<uchar>(cv::Point(i, j)));
M.at<uchar>(cv::Point(i, j)) = std::abs(gauss_pixel - source_pixel);
}
}
std::cout << "Matrix D" << std::endl;
cv::Mat D = cv::Mat::zeros(source_image.size(), CV_8UC1);
cv::GaussianBlur(M, D, cv::Size(2 * radius + 1, 2 * radius + 1), sigma);
std::cout << "Matrix B" << std::endl;
cv::Mat B = cv::Mat::zeros(source_image.size(), CV_8UC1);
double pixelI, pixelG, pixelD;
double condition;
for (size_t i{}; i < B.cols; ++i) {
for (size_t j{}; j < B.rows; ++j) {
pixelG = static_cast<double>(
G.at<uchar>(cv::Point(i, j)));
pixelI = static_cast<double>(
source_image.at<uchar>(cv::Point(i, j)));
pixelD = static_cast<double>(
D.at<uchar>(cv::Point(i, j)));
condition = (pixelG - pixelI) / (pixelD + d0);
B.at<uchar>(cv::Point(i, j)) = (255 * condition < thres) ? 255 : 0;
}
}
bin_image = B;
}
void writeBinarized(const std::vector<cv::Mat>& srcs, const cv::Mat& src,
std::vector<cv::Mat>& dsts, cv::Mat& dst, bool write = false) {
std::cout << "image 1" << std::endl;
MIPTBinarization(srcs[0], dsts[0], 20, 15, 20, 200);
std::cout << "image 2" << std::endl;
MIPTBinarization(srcs[1], dsts[1], 20, 40, 20, 180);
std::cout << "image 3" << std::endl;
MIPTBinarization(srcs[2], dsts[2], 20, 15, 20, 150);
std::cout << "image 4" << std::endl;
MIPTBinarization(srcs[3], dsts[3], 20, 50, 20, 150);
std::cout << "image 5" << std::endl;
MIPTBinarization(srcs[4], dsts[4], 20, 60, 20, 150);
cv::threshold(src, dst, 127, 255, cv::THRESH_BINARY);
if (write) {
for (size_t i{}; i < srcs.size(); ++i)
cv::imwrite("../../../data/lab05.bin" + std::to_string(i + 1)
+ ".png", dsts[i]);
cv::imwrite("../../../data/lab05.bin0.png", dst);
}
}
cv::Mat deviation(const cv::Mat& lhs, const cv::Mat& rhs) {
cv::Mat deviation(lhs.size(), CV_8UC3);
double MSE{};
double PSNR{};
double lhs_pixel, rhs_pixel, error;
for (size_t i{}; i < lhs.cols; ++i) {
for (size_t j{}; j < lhs.rows; ++j) {
lhs_pixel = static_cast<double>(lhs.at<uchar>(cv::Point(i, j)));
rhs_pixel = static_cast<double>(rhs.at<uchar>(cv::Point(i, j)));
error = lhs_pixel - rhs_pixel;
MSE += error * error;
if (error < 0) {
deviation.at<cv::Vec3b>(j, i) = cv::Vec3b{ 0, 255, 0 };
continue;
}
if (error == 0) {
deviation.at<cv::Vec3b>(j, i) = cv::Vec3b{ 0, 0, 0 };
continue;
}
if (error > 0) {
deviation.at<cv::Vec3b>(j, i) = cv::Vec3b{ 0, 0, 255 };
continue;
}
}
}
MSE /= lhs.cols * lhs.rows;
PSNR = 10 * std::log(255 * 255 / MSE);
std::cout << "MSE: " << MSE << "\nPSNR: " << PSNR << std::endl;
return deviation;
}
void writeDeviation(const std::vector<cv::Mat>& bins,
std::vector<cv::Mat>& devs, const cv::Mat& ideal, bool write = false) {
for (size_t i{}; i < bins.size(); ++i) {
std::cout << "image " << i + 1 << std::endl;
devs[i] = deviation(bins[i], ideal);
if (write)
cv::imwrite("../../../data/lab05.dev" + std::to_string(i + 1)
+ ".png", devs[i]);
}
}
size_t connectedComponentsWithStatsColored( const cv::Mat& source) {
cv::Mat labels;
cv::Mat stats;
cv::Mat centroids;
int num_labels = cv::connectedComponentsWithStats(
source, labels, stats, centroids);
return num_labels;
}
void multiConnectedComponents(const std::vector<cv::Mat>& srcs) {
std::vector<cv::Mat> source_inverted{srcs.size()};
for (size_t i{}; i < srcs.size(); ++i)
cv::threshold(srcs[i], source_inverted[i],
127, 255, cv::THRESH_BINARY_INV);
for (size_t i{}; i < srcs.size(); ++i) {
std::cout << "image" << i + 1 << std::endl;
std::cout << "components: "
<< connectedComponentsWithStatsColored(srcs[i]) << std::endl;
}
}
int main() {
//images[0] is ideal image
std::cout << "Reading..." << std::endl;
size_t num_images = 5;
std::vector<cv::Mat> source_images = getImages(num_images);
cv::Mat target_image = cv::imread(
"../../../data/lab05.src0.png", cv::IMREAD_GRAYSCALE);
//adding keypoints for homography
std::cout << "\nAdding keypoints..." << std::endl;
std::vector<std::vector<cv::Point2f>> source_points = getSourcePoints();
std::vector<cv::Point2f> target_points = {
{93, 106}, {2264, 106}, {2264, 2785}, {93, 2785} };
//showing keypoints
std::cout << "\nShowing keypoints..." << std::endl;
std::vector<cv::Mat> src_visual_keypoints(source_images.size());
for (size_t i{}; i < source_images.size(); ++i)
source_images[i].copyTo(src_visual_keypoints[i]);
cv::Mat dst_visual_keypoints;
target_image.copyTo(dst_visual_keypoints);
drawPoints(
src_visual_keypoints, dst_visual_keypoints,
source_points, target_points, true);
//finding homography
std::cout << "\nFinding homography..." << std::endl;
std::vector<cv::Mat> Hs =
findMultipleHomography(source_points, target_points);
//warping
std::cout << "\nWarping..." << std::endl;
std::vector<cv::Mat> warped_images{num_images};
warpMultiplePerspective(
source_images, warped_images, Hs,
target_image.size(), true);
//binarization
std::cout << "\nBinarizing..." << std::endl;
std::vector<cv::Mat> source_bin_images{num_images};
cv::Mat target_bin_image;
writeBinarized(
warped_images, target_image, source_bin_images,
target_bin_image, true);
//deviation
std::cout << "\nCalculating deviation..." << std::endl;
std::vector<cv::Mat> source_deviation_images{num_images};
writeDeviation(
source_bin_images, source_deviation_images,
target_bin_image, true);
//components
std::cout << "\nCalculating components..." << std::endl;
multiConnectedComponents(source_bin_images);
std::cout << "ideal: " <<
connectedComponentsWithStatsColored(target_bin_image) << std::endl;
cv::waitKey(0);
}
| [
"doodleztoon@gmail.com"
] | doodleztoon@gmail.com |
5b43c7e0213dd36c9f6176d1ef105c52cb78a127 | c575692b1ad08065dccb9a59bf2e9ba039762125 | /lib/src/Objects/StaticObject.cpp | 18c7a5410e1b5138629f652545306a20a3624abf | [] | no_license | Mzartek/VulkanTraining | c7b4207f465146a27f4f5c993cda6d735e266003 | 8a56e1c5e1e6626a89c71bb4f86b9d95c31a2e91 | refs/heads/master | 2021-06-28T18:23:46.287637 | 2018-06-03T14:50:21 | 2018-06-03T14:50:21 | 96,036,279 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 49 | cpp | #include <VulkanTraining/Objects/StaticObject.h>
| [
"havranekkevin@gmail.com"
] | havranekkevin@gmail.com |
ad71a7989ec700ae51997558c0295779e15a63db | 7f0fecfcdadd67036443a90034d34a0b0318a857 | /sparta/sparta/argos/Reader.hpp | 94848cdda2f342882b91cfadc983fa4a56a4cf06 | [
"MIT"
] | permissive | timsnyder/map | e01b855288fc204d12e32198b2c8bd0f13c4cdf7 | aa4b0d7a1260a8051228707fd047431e1e52e01e | refs/heads/master | 2020-12-21T19:34:48.716857 | 2020-02-17T17:29:29 | 2020-02-17T17:29:29 | 236,536,756 | 0 | 0 | MIT | 2020-01-27T16:31:24 | 2020-01-27T16:31:23 | null | UTF-8 | C++ | false | false | 58,869 | hpp | // <Reader.hpp> -*- C++ -*-
/**
* \file Reader.hpp
*
* \brief Reads transctions using the record and index file
*
*/
#ifndef __READER_H__
#define __READER_H__
#include <functional>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
#include <sys/stat.h>
#include "PipelineDataCallback.h"
#include "sparta/utils/SpartaException.hpp"
#include "sparta/utils/SpartaAssert.hpp"
#include "sparta/utils/LexicalCast.hpp"
#include "sparta/argos/Outputter.hpp"
// #define READER_DBG 1
// #define READER_LOG 1
#if READER_DBG==1
#define READER_LOG 1
#endif
namespace sparta{
namespace argos{
/*!
* \brief Sanity checker for records. Used when doing a dump of the index
* file to check that all transactions in the heartbeat actually belong
* there
*/
class RecordChecker : public PipelineDataCallback
{
uint64_t start;
uint64_t end;
public:
RecordChecker(uint64_t _start, uint64_t _end) :
start(_start),
end(_end)
{;}
virtual void foundTransactionRecord(transaction_t* r) override {
if(r->time_Start < start){
std::cout << "Bounds on transactions were outside of heartbeat range " << start
<< "," << end << ". transaction: idx: " << r->transaction_ID << " loc: "
<< r->location_ID << " start: "
<< r->time_Start << " end: " << r->time_End
<< " parent: " << r->parent_ID << std::endl;
}
if(r->time_End > end){
std::cout << "Bounds on transactions were outside of heartbeat range " << start
<< "," << end << ". transaction: idx: " << r->transaction_ID << " loc: "
<< r->location_ID << " start: "
<< r->time_Start << " end: " << r->time_End
<< " parent: " << r->parent_ID << std::endl;
}
}
virtual void foundInstRecord(instruction_t* r) override {
foundTransactionRecord(r);
}
virtual void foundMemRecord(memoryoperation_t* r) override {
foundTransactionRecord(r);
}
virtual void foundAnnotationRecord(annotation_t* r) override {
foundTransactionRecord(r);
}
virtual void foundPairRecord(pair_t* r) override {
foundTransactionRecord(r);
}
};
// Memory Layout of pair_struct. We build a vector of such structs before we start reading record back from the database.
// This structs help us by telling us exactly how may pair values
// there are in the current pair type, what their names are and how much bytes each of the values occupy.
// We inquire such a vector of structs by giving it a unique id and this vector gives
// us such a struct where the unique id matches.
struct pair_struct{
uint16_t UniqueID;
uint16_t length;
std::vector<uint16_t> types;
std::vector<uint16_t> sizes;
std::string formatGuide;
std::vector<std::string> names;
};
/*!
* \class Reader
* @ brief A class that facilitates reading transactions from disk that
* end in a given interval measured in cycles.
*
* The Reader will return the records found on disk by calling
* methods in PipelineDataCallback, passing pointers to the read
* transactions.
*/
class Reader
{
private:
/**
* \brief return the correct position in the record file that corresponds
* to the start cycle.
* \param start The cycle number to start reading records from.
*/
uint64_t findRecordReadPos_(uint64_t start)
{
//Figure out how far we need to seek into our index file.
uint64_t step = first_index_ + (start/heartbeat_ * sizeof(uint64_t));
//Now read the pointer from this location.
if(!index_file_.seekg(step)) {
sparta_assert(!"Could not seekg in for the given position. Please report bug");
}
uint64_t pos = 0;
//It might be the case that our index file is too small
//to represent an end time that the user is requesting.
//in the above algorythm either reached the end of the index file.
//notice we look too see if the index file seeker has passed
//size_of_index_file_ - 8 bytes b/c a special last index is written to the index file
//to point to only the start of the last transaction.
int64_t filepos = index_file_.tellg();
if(filepos >= size_of_index_file_ - 8 || filepos == -1)
{
//We need to reset end of file reach flags for the index file.
index_file_.clear();
pos = size_of_record_file_;
}
else
{
index_file_.read((char*)&pos, sizeof(uint64_t));
}
return pos;
}
/**
* \brief A helper method to round values up to the
* interval values.
* example 4600 rounds to 5000 when the interval is "1000"
*/
uint64_t roundUp_(uint64_t num)
{
int remainder = num % heartbeat_;
if(remainder == 0)
return num;
return num + heartbeat_ - remainder;
}
/**
* \brief Return the start time in the file.
*/
uint64_t findCycleFirst_()
{
//Make sure the user is not abusing our NON thread safe method.
sparta_assert(!lock, "This reader class is not thread safe, and this method cannot be called"" from multiple threads.");
lock = true;
record_file_.seekg(0, std::ios::beg);
transaction_t transaction;
record_file_.read(reinterpret_cast<char*>(&transaction), sizeof(transaction_t));
lock = false;
return transaction.time_Start;
}
/**
* \brief Return the last end time in the file.
* Our output saved the last index to point to
* the start of last record.
*/
uint64_t findCycleLast_()
{
//Make sure the user is not abusing our NON thread safe method.
sparta_assert(!lock, "This reader class is not thread safe, and this method cannot be called"" from multiple threads.");
lock = true;
//Notice that we reset the index file, b/c if
//we had already read to the end of the file, we need to reset
//end of file flags.
index_file_.clear();
//seek one entry back from the end of the index file
index_file_.seekg(size_of_index_file_-sizeof(uint64_t));
uint64_t pos = 0;
index_file_.read((char*)&pos, sizeof(uint64_t));
//read the transaction at the appropriate location.
record_file_.seekg(pos, std::ios::beg);
transaction_t transaction;
record_file_.read(reinterpret_cast<char*>(&transaction), sizeof(transaction_t));
lock = false;
if(record_file_.gcount() != sizeof(transaction_t))
{
return highest_cycle_;
}
return transaction.time_End - 1;
}
/*!
* \brief Read a record of any format. Older formats are upconverted to new format.
*/
void readRecord_(int64_t& pos, uint64_t start, uint64_t end) {
if(version_ == 1){
readRecord_v1_(pos, start, end);
}else if(version_ == 2){
readRecord_v2_(pos, start, end);
}else{
throw SpartaException("This argos reader library does not know how to read a record "
" for version ") << version_ << " file " << filepath_;
}
}
/*!
* \brief Implementation of readRecord_ function which accepts the version 1 format)
*/
void readRecord_v1_(int64_t& pos, uint64_t start, uint64_t end) {
const uint32_t MAX_ANNT_LEN = 16384;
const uint32_t ANNT_BUF_SIZE = MAX_ANNT_LEN + 1;
char annt_buf[ANNT_BUF_SIZE];
annt_buf[0] = '\0';
version1::transaction_t transaction;
record_file_.read(reinterpret_cast<char*>(&transaction), sizeof(version1::transaction_t));
pos += sizeof(version1::transaction_t);
if((transaction.flags & TYPE_MASK) == is_Annotation){
version1::annotation_t annot;
memcpy(&annot, &transaction, sizeof(version1::transaction_t));
record_file_.read(reinterpret_cast<char*>(&annot.length), sizeof(uint16_t));
pos += sizeof(uint16_t);
annot.annt = annt_buf;
if(annot.length > MAX_ANNT_LEN){
// Truncate because this giant annotation exceeds buffer.
// An alternative would be replace annt_buf with a heap variable and
// enlarge it each time a larger annotation was encountered.
record_file_.read(annt_buf, MAX_ANNT_LEN); // Read max portion of annotaiton
pos += MAX_ANNT_LEN;
std::cerr << "Had to truncate annotation " << annot.transaction_ID
<< " starting at " << annot.time_Start << " of length " << annot.length
<< " to " << MAX_ANNT_LEN << " because it exceeded buffer size." << std::endl
<< " ANNOTATION:\n" << std::string(annt_buf) << std::endl;
record_file_.seekg(annot.length - MAX_ANNT_LEN, std::ios::cur); // Skip rest
pos += annot.length - MAX_ANNT_LEN;
annot.length = MAX_ANNT_LEN;
}else{
record_file_.read(annt_buf, annot.length);
pos += annot.length;
}
// Only send along transaction in the query range
if(transaction.time_End < start || transaction.time_Start > end){
#if READER_DBG
// Skip transactions by not sending them along to the callback.
// read is faster than seekg aparently. This DOES help performance
std::cerr << "READER: skipped transaction outside of window [" << start << ", "
<< end << "). start: " << transaction.time_Start << " end: "
<< transaction.time_End
<< " parent: " << transaction.parent_ID << std::endl;
#endif
}else{
#ifdef READER_DBG
std::cout << "READER: found annt. " << "loc: " << annot.location_ID << " start: "
<< annot.time_Start << " end: " << annot.time_End
<< " parent: " << annot.parent_ID << std::endl;
#endif
annotation_t new_anno(std::move(annot));
data_callback_->foundAnnotationRecord(&new_anno);
}
return;
}else if((transaction.flags & TYPE_MASK) == is_Instruction){
record_file_.seekg(-sizeof(version1::transaction_t), std::ios::cur);
pos -= sizeof(version1::transaction_t);
version1::instruction_t inst;
record_file_.read(reinterpret_cast<char*>(&inst), sizeof(version1::instruction_t));
pos += sizeof(version1::instruction_t);
#ifdef READER_DBG
std::cout << "READER: found inst. start: " << inst.time_Start << " end: " << inst.time_End << std::endl;
#endif
instruction_t new_inst(std::move(inst));
data_callback_->foundInstRecord(&new_inst);
return;
}else if((transaction.flags & TYPE_MASK) == is_MemoryOperation){
record_file_.seekg(-sizeof(version1::transaction_t), std::ios::cur);
pos -= sizeof(version1::transaction_t);
version1::memoryoperation_t memop;
record_file_.read(reinterpret_cast<char*>(&memop), sizeof(version1::memoryoperation_t));
pos += sizeof(version1::memoryoperation_t);
#ifdef READER_DBG
std::cout << "READER: found inst. start: " << memop.time_Start << " end: " << memop.time_End << std::endl;
#endif
memoryoperation_t new_memop(std::move(memop));
data_callback_->foundMemRecord(&new_memop);
return;
}else{
throw sparta::SpartaException("An unidentifiable transaction type found in this record."
" It is possible the data may be corrupt.");
}
}
/**
* \brief Read a single record at \a pos and increment pos
*/
void readRecord_v2_(int64_t& pos, uint64_t start, uint64_t end) {
const uint32_t MAX_ANNT_LEN = 16384;
const uint32_t ANNT_BUF_SIZE = MAX_ANNT_LEN + 1;
char annt_buf[ANNT_BUF_SIZE];
annt_buf[0] = '\0';
transaction_t transaction;
record_file_.read(reinterpret_cast<char*>(&transaction), sizeof(transaction_t));
pos += sizeof(transaction_t);
// some struct to populate the record too.
annotation_t annot;
instruction_t inst;
memoryoperation_t memop;
pair_t pairt;
switch (transaction.flags & TYPE_MASK)
{
case is_Annotation :
{
memcpy(&annot, &transaction, sizeof(transaction_t));
record_file_.read(reinterpret_cast<char*>(&annot.length), sizeof(uint16_t));
pos += sizeof(uint16_t);
annot.annt = annt_buf;
if(annot.length > MAX_ANNT_LEN){
// Truncate because this giant annotation exceeds buffer.
// An alternative would be replace annt_buf with a heap variable and
// enlarge it each time a larger annotation was encountered.
record_file_.read(annt_buf, MAX_ANNT_LEN); // Read max portion of annotaiton
pos += MAX_ANNT_LEN;
std::cerr << "Had to truncate annotation " << annot.transaction_ID
<< " starting at " << annot.time_Start << " of length " << annot.length
<< " to " << MAX_ANNT_LEN << " because it exceeded buffer size." << std::endl
<< " ANNOTATION:\n" << std::string(annt_buf) << std::endl;
record_file_.seekg(annot.length - MAX_ANNT_LEN, std::ios::cur); // Skip rest
pos += annot.length - MAX_ANNT_LEN;
annot.length = MAX_ANNT_LEN;
}else{
record_file_.read(annt_buf, annot.length);
pos += annot.length;
}
(void) start;
//// Sanity check the transactions coming out
//if(start % heartbeat_ == 0 // Only try this sanity checking if start is a multiple of heartbeat_
// && transaction.time_Start < start // Got a transaction starting before the first heartbeat containing this query
// && transaction.time_End > transaction.time_Start){ // ignore 0-length transactions
// std::cout << "Found a transaction where start < query-start && end <= query-start: ("
// << transaction.time_Start << " < " << start << ")"
// << " && " << transaction.time_End << "<= " << start << ") : \""
// << annot.annt << "\""
// << std::endl;
//}
(void) end;
// Only send along transaction in the query range
if(transaction.time_End < start || transaction.time_Start > end){
#if READER_DBG
// Skip transactions by not sending them along to the callback.
// read is faster than seekg aparently. This DOES help performance
std::cerr << "READER: skipped transaction outside of window [" << start << ", "
<< end << "). start: " << transaction.time_Start << " end: "
<< transaction.time_End
<< " parent: " << transaction.parent_ID << std::endl;
#endif
}else{
#ifdef READER_DBG
std::cout << "READER: found annt. " << "loc: " << annot.location_ID << " start: "
<< annot.time_Start << " end: " << annot.time_End
<< " parent: " << annot.parent_ID << std::endl;
#endif
data_callback_->foundAnnotationRecord(&annot);
}
} break;
case is_Instruction:
{
record_file_.seekg(-sizeof(transaction_t), std::ios::cur);
pos -= sizeof(transaction_t);
record_file_.read(reinterpret_cast<char*>(&inst), sizeof(instruction_t));
pos += sizeof(instruction_t);
#ifdef READER_DBG
std::cout << "READER: found inst. start: " << inst.time_Start << " end: " << inst.time_End << std::endl;
#endif
data_callback_->foundInstRecord(&inst);
} break;
case is_MemoryOperation:
{
record_file_.seekg(-sizeof(transaction_t), std::ios::cur);
pos -= sizeof(transaction_t);
record_file_.read(reinterpret_cast<char*>(&memop), sizeof(memoryoperation_t));
pos += sizeof(memoryoperation_t);
#ifdef READER_DBG
std::cout << "READER: found inst. start: " << memop.time_Start << " end: " << memop.time_End << std::endl;
#endif
data_callback_->foundMemRecord(&memop);
} break;
// If we have found a record which is of Pair Type,
// then we enter into this switch case
// which contains the logic to read back records of
// pair type using record file, map file
// and In-memory data structures and rebuild the pair
// record one by one.
case is_Pair : {
// First, we do a simple memcpy of the generic transaction structure
// we read into our pair structure
memcpy(&pairt, &transaction, sizeof(transaction_t));
// We grab the location Id of this record we are about to read from
// the generic transaction structure
unsigned long long location_ID = transaction.location_ID;
std::string delim = ":";
// The loc_map is an In-memory Map which contains a mapping
// of Location ID to Pair ID.
// We are going to use this map to lookup the Location ID we
// just read from this current record
// and find out the pair id of such a record
std::string token = loc_map_[std::to_string(location_ID)];
// We are now going to use the In-memory data structure we built
//during the Reader construction.
// This Data Structure contains information about the name strings
// and their sizeof data
// for every different type of pair we have collected.
// So, we retrieve records from this structure one by one,
// till we find that the pair id of the record we just read
// from the record file
// matches the pair id of the current record we retrieved from
// the In-memory data Structure.
for(auto & st : map_){
if(st.UniqueID == std::stoull(token)){
// We lookup the length, the name strings and the sizeofs of
// every anme string from the retrieved
// record of the Data Struture and copy the values into out
// live Pair Transaction record
pairt.length = st.length;
std::string token = "#";
std::string guideString = st.formatGuide;
while(guideString.size()){
if(guideString.find(token) != std::string::npos){
uint16_t index = guideString.find(token);
pairt.delimVector.emplace_back(guideString.substr(0, index));
guideString = guideString.substr(index + token.size());
if(guideString.empty()){
pairt.delimVector.emplace_back(guideString);
}
}
else{
pairt.delimVector.emplace_back(guideString);
guideString = "";
}
}
pairt.nameVector.reserve(pairt.length);
pairt.valueVector.reserve(pairt.length);
pairt.sizeOfVector.reserve(pairt.length);
pairt.stringVector.reserve(pairt.length);
pairt.nameVector.emplace_back("pairid");
pairt.valueVector.emplace_back(std::make_pair(st.UniqueID, false));
pairt.sizeOfVector.emplace_back(sizeof(uint16_t));
pairt.stringVector.emplace_back(" ");
for(std::size_t i = 1; i != st.length; ++i){
pairt.nameVector.emplace_back(st.names[i]);
pairt.sizeOfVector.emplace_back(st.sizes[i]);
if(st.types[i] == 0){
switch(pairt.sizeOfVector[i]){
case sizeof(uint8_t) : {
uint8_t tmp;
// We read exactly the number of bytes
// this value occupies from the database.
// This is a crucial step else if we read
// wrong number of bytes, our read procedure
// will crash in near future.
record_file_.read(reinterpret_cast<char*>(&tmp), sizeof(uint8_t));
pos += sizeof(uint8_t);
pairt.valueVector.emplace_back(std::make_pair(tmp, true));
}break;
case sizeof(uint16_t) : {
uint16_t tmp;
// We read exactly the number of bytes this
// value occupies from the database.
// This is a crucial step else if we read wrong
// number of bytes, our read procedure will crash in near future.
record_file_.read(reinterpret_cast<char*>(&tmp), sizeof(uint16_t));
pos += sizeof(uint16_t);
pairt.valueVector.emplace_back(std::make_pair(tmp, true));
}break;
case sizeof(uint32_t) : {
uint32_t tmp;
// We read exactly the number of bytes
// this value occupies from the database.
// This is a crucial step else if we read
// wrong number of bytes, our read procedure
// will crash in near future.
record_file_.read(reinterpret_cast<char*>(&tmp), sizeof(uint32_t));
pos += sizeof(uint32_t);
pairt.valueVector.emplace_back(std::make_pair(tmp, true));
}break;
case sizeof(uint64_t) : {
uint64_t tmp;
// We read exactly the number of bytes
// this value occupies from the database.
// This is a crucial step else if we read
// wrong number of bytes, our read procedure
// will crash in near future.
record_file_.read(reinterpret_cast<char*>(&tmp), sizeof(uint64_t));
pos += sizeof(uint64_t);
pairt.valueVector.emplace_back(std::make_pair(tmp, true));
}break;
default : {
throw sparta::SpartaException(
"Data Type not supported for reading/writing.");
}
}
// Finally for a certain field "i", we check if there is a string
// representation for the integral value, by checking,
// if a key with current pair id, current field id, current integral value
// exists in the In-memory String Map. If yes, we grab the value
// and place it in the enum vector.
if(stringMap_.find(std::make_tuple(pairt.valueVector[0].first,
i - 1,
pairt.valueVector[i].first)) !=
stringMap_.end()){
pairt.stringVector.emplace_back(stringMap_[std::make_tuple(
pairt.valueVector[0].first,
i - 1,
pairt.valueVector[i].first)]);
pairt.valueVector[i].second = false;
}
// Else, we push empty string in the enum vector at this index.
else{
pairt.stringVector.emplace_back(std::to_string(pairt.valueVector[i].first));
}
}
else if(st.types[i] == 1){
uint16_t annotationLength;
record_file_.read(reinterpret_cast<char*>(&annotationLength), sizeof(uint16_t));
pos += sizeof(uint16_t);
std::unique_ptr<char[] , std::function<void(char * ptr)>>
annot_ptr(new char[annotationLength + 1],
[&](char * ptr) { delete [] ptr; });
record_file_.read(annot_ptr.get(), annotationLength);
pos += annotationLength;
std::string annot_str(annot_ptr.get(), annotationLength);
pairt.stringVector.emplace_back(annot_str);
pairt.valueVector.emplace_back(std::make_pair(std::numeric_limits<uint64_t>::max(), false));
// This bool value describes if this field has a string-only value.
// String only values are those values which are stored in database as
// strings and has no integral representation of itself.
const bool string_only_field = true;
pairt.valueVector.emplace_back(std::make_pair(
std::numeric_limits<
typename decltype(pairt.valueVector)::value_type::first_type>::max(),
string_only_field));
}
}
break;
}
}
#ifdef READER_DBG
std::cout << "READER: found pair. start: " << pairt.time_Start << " end: " << pairt.time_End << std::endl;
#endif
data_callback_->foundPairRecord(&pairt);
}
break;
default:
{
throw sparta::SpartaException("Unknown Transaction Found. Data might be corrupt.");
}
}
}
void reopenFileStream_(std::fstream & fs, const std::string & filename, std::ios::openmode mode = std::ios::in)
{
size_t cur_pos = fs.tellg();
fs.close();
fs.clear();
fs.open(filename, mode);
fs.seekg(cur_pos);
}
void checkIndexUpdates_()
{
struct stat index_stat_result, record_stat_result;
stat(index_file_path_.c_str(), &index_stat_result);
stat(record_file_path_.c_str(), &record_stat_result);
if(index_stat_result.st_size != size_of_index_file_ && record_stat_result.st_size != size_of_record_file_)
{
int64_t record_remainder = record_stat_result.st_size % heartbeat_;
if(record_stat_result.st_size - record_remainder == size_of_record_file_)
{
return;
}
reopenFileStream_(record_file_, record_file_path_, std::ios::in | std::ios::binary);
reopenFileStream_(index_file_, index_file_path_, std::ios::in | std::ios::binary);
reopenFileStream_(map_file_, map_file_path_, std::ios::in);
reopenFileStream_(data_file_, data_file_path_, std::ios::in);
size_of_index_file_ = index_stat_result.st_size;
if(record_remainder != 0)
{
size_of_record_file_ = record_stat_result.st_size - record_remainder;
}
else
{
size_of_record_file_ = record_stat_result.st_size;
}
highest_cycle_ = findCycleLast_();
file_updated_ = true;
}
}
public:
/**
* \brief Construct a Reader
* \param filename the name of the record file
* \param cd a pointer to for the PipelineDataCallback to use.
*/
Reader(std::string filepath, PipelineDataCallback* cb) :
filepath_(filepath),
record_file_path_(std::string(filepath + "record.bin")),
index_file_path_(std::string(filepath + "index.bin")),
map_file_path_(std::string(filepath + "map.dat")),
data_file_path_(std::string(filepath + "data.dat")),
string_file_path_(std::string(filepath + "string_map.dat")),
display_file_path_(std::string(filepath + "display_format.dat")),
record_file_(record_file_path_, std::fstream::in | std::fstream::binary ),
index_file_(index_file_path_, std::fstream::in | std::fstream::binary),
map_file_(map_file_path_, std::fstream::in),
data_file_(data_file_path_, std::fstream::in),
string_file_(string_file_path_, std::fstream::in),
display_file_(display_file_path_, std::fstream::in),
data_callback_(cb),
size_of_index_file_(0),
size_of_record_file_(0),
lowest_cycle_(0),
highest_cycle_(0),
lock(false),
file_updated_(false),
loc_map_(),
map_(),
stringMap_()
{
sparta_assert(data_callback_);
//Make sure the file opened correctly!
if(!record_file_.is_open())
{
throw sparta::SpartaException("Failed to open file, "+filepath+"record.bin");
}
if(!index_file_.is_open())
{
throw sparta::SpartaException("Failed to open file, "+filepath+"index.bin");
}
#ifdef READER_LOG
std::cout << "READER: Argos reader opened: " << filepath << "record.bin" << std::endl;
#endif
// Read header from index file
char header_buf[64];
// Note that this is not shared with argos::Outputter since it must
// remain even if the Outputter is changed
const std::string EXPECTED_HEADER_PREFIX = "sparta_pipeout_version:";
const std::size_t HEADER_SIZE = EXPECTED_HEADER_PREFIX.size() + 4 + 1; // prefix + number + newline
index_file_.read(header_buf, HEADER_SIZE);
// Assuming older version until header proves otherwise
version_ = 1;
if(index_file_.gcount() != (int)HEADER_SIZE){
// Assume old version because the file is too small to have a header
index_file_.clear(); // Clear error flags after failing to read enough data
index_file_.seekg(0, std::ios::beg); // Restore
}if(strncmp(header_buf, EXPECTED_HEADER_PREFIX.c_str(), EXPECTED_HEADER_PREFIX.size())){
// Header prefix did not match. Assume old version
index_file_.seekg(0, std::ios::beg); // Restore
}else{
// Header prefix matched. Read version
*(header_buf + HEADER_SIZE - 1) = '\0'; // Insert null
version_ = sparta::lexicalCast<decltype(version_)>(header_buf+EXPECTED_HEADER_PREFIX.size());
}
sparta_assert(version_ > 0 && version_ <= Outputter::FILE_VERSION,
"pipeout file " << filepath << " determined to be format "
<< version_ << " which is not known by this version of SPARTA. Version "
"expected to be in range [1, " << Outputter::FILE_VERSION << "]");
sparta_assert(index_file_.good(),
"Finished reading index file header for " << filepath << " but "
"ended up with non-good file handle somehow. This is a bug in the "
"header-reading logic");
// Read the heartbeat size from our index file.
// This will be the first integer in the file except for the header if there is one
// Warning: this must be called while the index_file_ is already seeked to the
// start of file, which it is after opening.
index_file_.read((char*)&heartbeat_, sizeof(uint64_t));
// Save the first index entry position
first_index_ = index_file_.tellg();
#ifdef READER_LOG
std::cout << "READER: Heartbeat is: " << heartbeat_ << std::endl;
#endif
sparta_assert(heartbeat_ != 0,
"Pipeout database \"" << filepath << "\" had a heartbeat of 0. This "
"would be too slow to actually load");
//Determine the size of our index file
index_file_.seekg(0, std::fstream::end);
size_of_index_file_ = index_file_.tellg();
//Determine the size of our record file.
record_file_.seekg(0, std::ios::end);
size_of_record_file_ = record_file_.tellg();
//cache the earliest start and stop of the record file
lowest_cycle_ = findCycleFirst_();
highest_cycle_ = findCycleLast_();
std::string delim = ":";
// Building the In-Memory LocationID -> PairID Lookup structure
// from the map_file_ which contains the same.
// We read this map_file_ just once during the construction
// of the Reader Class and store all the relationships
// in an unordered_map called loc_map. When we read each Pair Record,
// we quickly do a lookup with the Location ID
// of the record in this map, and retrieve the Pair ID of that record,
// so that we can go ahead and get all the information
// about its name strings and sizeof and pair length from other data structures.
//The fields in the file are separated by ":"
// Read throught the whole map File
while(map_file_){
std::string Data_String;
// Read a line from the file, and if we cannot find a line,
// that means we have read the whole file
if(!getline(map_file_, Data_String)){
break;
}
//Parse the string, one delimiter at a time.
size_t last = 0;
size_t next = 0;
next = Data_String.find(delim, last);
// We know the format of the map file is always like,
// A:B: so we know we can iterate twice over the
// delimiters in every single line and retrieve the individual values as strings
std::string key_ = Data_String.substr(last, next - last);
last = next + 1;
next = Data_String.find(delim, last);
std::string val_ = Data_String.substr(last, next - last);
// Once we have got the kep string and value string,
// we immediately put the pair in the Map.
// We don't even have to check for duplicate pairs as
// there never will be a duplicate strings,
// because, in the Outputter.h we build the Map file
// with only unique Location IDs.
loc_map_.insert(std::make_pair(key_, val_));
last = next + 1;
}
// Building the In-memory Pair Lookup structure, such that,
// in future when reading back record from transaction file,
// we can use this structure to know about the length, name strings
// and sizeof the values
// for that paritcular pair, instead of using a file on disk for this.
// We read through the Data file just once, and populate this structure.
//The fields in the file are separated by ":"
//Read through the whole Data File
while(data_file_){
pair_struct pStruct;
std::string Data_String;
// Read a line from the file, and if we cannot find a line,
// that means we have read the whole file
if(!getline(data_file_, Data_String)){
break;
}
//Parse the string, one delimiter at a time.
size_t last = 0;
size_t next = 0;
next = Data_String.find(delim, last);
//We know the first value in such a string is always the Pair ID
pStruct.UniqueID = std::stoull(Data_String.substr(last, next - last));
last = next + 1;
next = Data_String.find(delim, last);
// We know the second value in such a string
// is always the Length of this particular Pair.
pStruct.length = std::stoull(Data_String.substr(last, next - last)) + 1;
last = next + 1;
// The first pair value is the pair-id. We can make up any name
// for the name string for this pair.
pStruct.names.push_back("pairid");
pStruct.sizes.push_back(sizeof(uint16_t));
pStruct.types.emplace_back(0);
// Iterate through the rest of the delimiters in the stringline
// and build up the Name Strings and the Sizeof values for every field.
while((next = Data_String.find(delim, last)) != std::string::npos){
pStruct.names.emplace_back(Data_String.substr(last, next - last));
last = next + 1;
next = Data_String.find(delim, last);
pStruct.sizes.emplace_back(std::stoull(Data_String.substr(last, next - last)));
last = next + 1;
next = Data_String.find(delim, last);
pStruct.types.emplace_back(std::stoull(Data_String.substr(last, next - last)));
last = next + 1;
}
//Finally, when we have completely parsed one line of this file,
// it means we have complete knowledge of one pair type.
// We then insert this pair into out Lookup structure.
map_.emplace_back(pStruct);
}
while(display_file_){
std::string dataString;
if(!getline(display_file_, dataString)){
break;
}
size_t last = 0, next = 0;
next = dataString.find(delim, last);
uint16_t pairId = std::stoull(dataString.substr(last, next - last));
last = next + 1;
next = dataString.find("\n", last);
for(auto& st : map_){
if(st.UniqueID == pairId){
st.formatGuide = dataString.substr(last, next - last);
}
}
}
// Now, we are the In-memory Structure that will help us perform
// a lookup to find out the Actual String Representation from an integer.
// When a modeler has methods which actually return strings like
// instruction opcodes like "and", "str", "adddl" or mmu state like "ready", "not ready" etc.,
// we need to display exactly this kind of string back in the Argos Viewer.
// But storing such strings in Database
// takes up a lot of space and also, writing strings to a binary file is time intensive.
// So, during writing records to the Database,
// we created and used a Map which stores as Key a Tuple of 3 integers where the
// first integer represented the Pair Id of the record, for example,
// which pair does this record belong to?
// Is it ExampleInst or MemoryAccessInfo or LoadStoreInstInfo.
// The second integer represented which field of that
// pair record this value belonged to, for example, the third field or
// the fourth field and finally, the third and the last field,
// was the actual unique value for that string. For example, a tuple key of 1,2,3
// -> "not ready" in the map means that the value 3 in the 2nd field of the
// 1st type of Pair actually is represented by the string "not ready".
// By using this structure, we will populate the enum vector of our pair
// records and send the record back to the Argos side, so that we can
// represent such strings in the Argos Viewer.
// Read every line of the String Map file
while(string_file_){
std::string Data_String;
// If we do not find a string line, that means we have read all
// the lines and have reached the end of the file
if(!getline(string_file_, Data_String)){
break;
}
// We do not need to iterate throuogh this because we know exactly
// how many delimiters there would be in every line of this file
size_t last = 0;
size_t next = 0;
next = Data_String.find(delim, last);
//The first value before the delimiter would be our pair ID
uint64_t pid = std::stoull(Data_String.substr(last, next - last));
last = next + 1;
next = Data_String.find(delim, last);
// The first value before the second delimiter would be our Field ID
uint64_t fid = std::stoull(Data_String.substr(last, next - last));
last = next + 1;
next = Data_String.find(delim, last);
// The first value before the third delimiter would be our actual mapped value
uint64_t fval = std::stoull(Data_String.substr(last, next - last));
last = next + 1;
next = Data_String.find(delim, last);
// the value before the final delimiter would be a string value and we parse this string value,
// create a tuple key with the previous index values and put this string as the value for key.
std::string strval = Data_String.substr(last, next - last);
stringMap_[std::make_tuple(pid, fid, fval)] = strval;
}
}
//!Destructor.
virtual ~Reader()
{
index_file_.close();
record_file_.close();
map_file_.close();
data_file_.close();
string_file_.close();
display_file_.close();
}
/**
* \brief Clears the internal lock. This should be used ONLY when an
* exception occurs during loading
*/
void clearLock(){
lock = false;
}
/*!
* \brief Set the data callback, returning the previous callback
*/
PipelineDataCallback* setDataCallback(PipelineDataCallback* cb)
{
auto prev = data_callback_;
data_callback_ = cb;
sparta_assert(data_callback_, "Data callback must not be nullptr");
return prev;
}
/**
* \brief using our PipelineDataCallback pointer
* pass all of the transactions found in a given interval of cycles.
* \param start the intervals start cycle. Transactions with
* TMEN of "start" WILL be included in this window.
* "start" will also round down to the lower index closest to "start"
* \param end the intervals stop cycle. transactions
* with TMEN of "end" will NOT be included in the window.
*
* [start, end) where start rounded down and end rounded up
*
* so if our interval = 1000
* getWindowls(3500, 4700) will essentially return all transactions
* ending between
* [3000, 5000)
*
* \warning start must be GREATER than end.
* \warning This method IS NOT thread safe.
*/
void getWindow(uint64_t start, uint64_t end)
{
#ifdef READER_LOG
std::cout << "\nREADER: returning window. START: " << start << " END: " << end << std::endl;
#endif
// sparta_assert(//start < end, "Cannot return a window where the start value is greater than the end value");
//Make sure the user is not abusing our NON thread safe method.
sparta_assert(!lock, "This reader class is not thread safe, and this method cannot be called"" from multiple threads.");
lock = true;
//round the end up to the nearest interval.
uint64_t chunk_end = roundUp_(end);
#ifdef READER_LOG
std::cout << "READER: end rounded to: " << chunk_end << std::endl;
#endif
//First we will want to make sure we are ready to read at the correct
//position in the record file.
int64_t pos = findRecordReadPos_(start);
record_file_.seekg(pos);
//what space does this interval span in the record file.
uint64_t full_data_size = findRecordReadPos_(chunk_end) - record_file_.tellg();
//Now start processing the chunk.
int64_t end_pos = pos + full_data_size;
#ifdef READER_LOG
std::cout << "READER: start_pos: " << pos << " end_pos: " << end_pos << std::endl;
#endif
//Make sure we have not passed the end position, also make sure we
//are not at -1 bc that means we reached the end of the file!
//As we read records. Read each as a transaction.
//check the flags, seek back and then read it as the proper type,
//then pass the a pointer to the struct to the appropriate callback.
uint32_t recsread = 0;
if(version_ == 1){
while(pos < end_pos && pos != -1)
{
// Read, checking for chunk_end
readRecord_v1_(pos, start, chunk_end);
recsread++;
}
}else if(version_ == 2){
while(pos < end_pos && pos != -1)
{
// Read, checking for chunk_end
readRecord_v2_(pos, start, chunk_end);
recsread++;
}
}else{
throw SpartaException("This argos reader library does not know how to read a window "
" for version ") << version_ << " file: " << filepath_;
}
#ifdef READER_LOG
std::cout << "READER: read " << std::dec << recsread << " records" << std::endl;
#endif
//unlock our assertion test.
sparta_assert(lock);
lock = false;
}
/**
* \brief Reads transactions afer each index in the entire file
*/
void dumpIndexTransactions() {
auto prev_cb = data_callback_;
try{
uint64_t tick = 0;
index_file_.seekg(0, std::ios::beg);
while(tick <= getCycleLast() + (heartbeat_-1)){
int64_t pos;
//index_file_.read((char*)&pos, sizeof(uint64_t));
//if(index_file_.eof()){
// break;
//}
// Set up a record checker to ensure all transactions fall
// within the range being queried
RecordChecker rec(tick, tick + heartbeat_);
data_callback_ = &rec;
pos = findRecordReadPos_(tick);
std::cout << "Heartbeat at t=" << std::setw(10) << tick << " @ filepos " << std::setw(9)
<< pos << " first transaction:" << std::endl;
uint64_t chunk_end = roundUp_(tick + heartbeat_);
std::cout << "chunk end rounded to: " << chunk_end << std::endl;
std::cout << "record file pos before: " << record_file_.tellg() << std::endl;
record_file_.seekg(pos, std::ios::beg);
std::cout << "record file pos after: " << record_file_.tellg() << std::endl;
if(record_file_.tellg() == EOF) {
std::cerr << "TellG says EOF!" << std::endl;
}
else {
//what space does this interval span in the record file.
uint64_t full_data_size = findRecordReadPos_(chunk_end) - record_file_.tellg();
//Now start processing the chunk.
int64_t end_pos = pos + full_data_size;
std::cout << "pos = " << pos << ", end_pos = " << end_pos << std::endl;
uint32_t recsread = 0;
while(pos < end_pos && pos != -1)
{
// Read, checking for chunk_end
readRecord_(pos, tick, chunk_end);
recsread++;
}
//readRecord_(pos, tick, tick + heartbeat_);
std::cout << "Records: " << recsread << std::endl;
}
std::cout << "record file pos after read: " << record_file_.tellg() << std::endl;
std::cout << "pos variable after read: " << pos << std::endl;
tick += heartbeat_;
std::cout << "\n";
}
}catch(...){
// Restore data callback before propogating exception
data_callback_ = prev_cb;
throw;
}
uint64_t tmp;
if(index_file_.read((char*)&tmp, sizeof(uint64_t))){
std::cout << "Read junk at the end of the index file:\n " << tmp;
while(index_file_.read((char*)&tmp, sizeof(uint64_t))){
std::cout << " " << tmp;
}
}
}
/**
* \brief Gets the size of a data chunk. This is a minimum granularity
* of file reads when looking for any range. Chunks are in terms of
* ticks and chunks always begin at ticks which are chunk-size-aligned
*/
uint64_t getChunkSize() const
{
return heartbeat_;
}
/**
* \brief Return the start time in the file.
*/
uint64_t getCycleFirst() const
{
#ifdef READER_DBG
std::cout << "READER: Returning first cycle: " << lowest_cycle_ << std::endl;
#endif
//This needs to be changed.
//BUG When this returns 0, we miss many transactions in the viewer.
return lowest_cycle_;
}
/**
* \brief Return the last end time in the file.
* Our output saved the last index to point to
* the start of last record.
*/
uint64_t getCycleLast() const
{
#ifdef READER_DBG
std::cout << "READER: Returning last cycle: " << highest_cycle_ << std::endl;
#endif
return highest_cycle_;
}
/**
* \brief Gets the version of the pipeout files loaded
*/
uint32_t getVersion() const
{
return version_;
}
bool isUpdated()
{
checkIndexUpdates_();
return file_updated_;
}
void ackUpdated()
{
file_updated_ = false;
}
private:
const std::string filepath_; /*!< Path to this file */
const std::string record_file_path_; /*!< Path to the record file */
const std::string index_file_path_; /*!< Path to the index file */
const std::string map_file_path_; /*!< Path to the map file which maps LocationID to Pair number */
// Path to the data file which contains information about the name strings and the size in Bytes
// their values hold for every different pair
const std::string data_file_path_;
// Path to the string_map file which contains String Representations of the actual values,
// mapped from the intermediate Tuple used to write in Database
const std::string string_file_path_;
const std::string display_file_path_;
std::fstream record_file_; /*!< The record file stream */
std::fstream index_file_; /*!< The index file stream */
std::fstream map_file_; /*!< The map file stream */
std::fstream data_file_; /*!< The data file stream */
std::fstream string_file_; /*!< The string map file stream */
std::fstream display_file_;
PipelineDataCallback* data_callback_; /*<! A pointer to a callback to pass records too */
uint64_t heartbeat_; /*!< The heartbeast-size in cycles of our indexes in the index file */
uint64_t first_index_; /*!< Position in file of first index entry */
uint32_t version_; /*!< Version of the file being read */
int64_t size_of_index_file_; /*!< The total byte size of the index file */
int64_t size_of_record_file_; /*!< The total byte size of the record file */
uint64_t lowest_cycle_; /*!< The lowest cycle in the file. */
uint64_t highest_cycle_; /*!< The highest cycle in the file. */
bool lock; /*!< A tool used too assert that this file Reader is not thread safe.*/
bool file_updated_; /*!< Set to true when the open database has changed */
// In-memory data structure to hold the mapping of Location ID
// of generic transaction structures
// and map them to Pair IDs of pair transaction structs.
std::unordered_map<std::string, std::string> loc_map_;
// In-memory data structure to hold the unique pairId and
// subsequent information about its name strings and
// sizeofs for every different pair type
std::vector<pair_struct> map_;
// In-memory data structure to hold the string map structure
// which maps a tuple of integers reflecting the pair type,
// field number and field value to the actual String
// we want to display in Argos
std::unordered_map<std::tuple<
uint64_t, uint64_t, uint64_t>,
std::string, hashtuple::hash<
std::tuple<uint64_t, uint64_t, uint64_t>>>
stringMap_;
};
}//NAMESPACE:argos
}//NAMESPACE:sparta
// __READER_H__
#endif
| [
"klingaard@gmail.com"
] | klingaard@gmail.com |
a24dae43f1a0030dddb458a6a1143213d381e379 | 6882960fe1a5a3a82c73a9f5aa0599cd40d573fc | /9-3..cpp | 56c4e83b440750d3cee27c9496ea3991c7212932 | [] | no_license | EveBell/githubb | 3a79d8044adaf87393d03a01bd71052f2c30e0ba | d747130fad5c1c3250703127391aa4c577ae635c | refs/heads/master | 2021-09-02T15:43:30.757504 | 2018-01-03T13:00:36 | 2018-01-03T13:00:36 | 114,891,479 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 314 | cpp | #include<stdio.h>
#include<string.h>
#define N 5
int main(void){
int i;
char s[N][128];
char a[]="$$$$$";
for(i=0;i<N;i++){
printf("s[%d]:",i);
scanf("%s",s[i]);
}
for(int j=0;j<N;j++)
{int b=strcmp(a,s[j]);
if(b==0) break;
printf("s[%d]=\"%s\"\n",j,s[j]);
}
return 0;
}
| [
"1600691512@qq.com"
] | 1600691512@qq.com |
be79efeaa916fe3781ff51bb2733a69efb28d755 | 70addd8f28e04bbb2c76289d540b5c36e431a09d | /Merge2SortedList.h | 73506546cf8d541beda40142eb00799f75349563 | [] | no_license | zhang-yanan/leetcode | 1286326e908743e65cd2d767aa83c95ce486c372 | b2ec0b2e38734dcec78fdd2ab8abc03529026279 | refs/heads/master | 2020-12-24T13:17:36.238493 | 2015-08-13T07:11:34 | 2015-08-13T07:11:34 | 40,642,012 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | h | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL)return l2;
if(l2 == NULL)return l1;
ListNode *q, *p, *r,*m, *result;
if(l1->val < l2->val)
{
p = l1;
q = l2;
}else {
p = l2;
q = l1;
}
result = r = p;
m=q;
while(p!=NULL &&q !=NULL)
{
while( p != NULL &&p->val <= q->val)
{
r = p;
p = p->next;
}
r->next = q;
if(p == NULL)break;
while(q !=NULL && q->val <= p->val)
{
m = q;
q = q->next;
}
m->next = p;
}
return result;
}
}; | [
"zhangyanan.gucas@gmail.com"
] | zhangyanan.gucas@gmail.com |
75c9b01f658ca161e5b540900610fb0aa5874c0e | 771a5f9d99fdd2431b8883cee39cf82d5e2c9b59 | /SDK/BP_PromptActor_EmissarySoldLoot_OOS_functions.cpp | 03bceaed189431be2c028c8af36f36902db67acb | [
"MIT"
] | permissive | zanzo420/Sea-Of-Thieves-SDK | 6305accd032cc95478ede67d28981e041c154dce | f56a0340eb33726c98fc53eb0678fa2d59aa8294 | refs/heads/master | 2023-03-25T22:25:21.800004 | 2021-03-20T00:51:04 | 2021-03-20T00:51:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,549 | cpp | // Name: SeaOfThieves, Version: 2.0.23
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
// Function BP_PromptActor_EmissarySoldLoot_OOS.BP_PromptActor_EmissarySoldLoot_OOS_C.UserConstructionScript
// (Event, Public, BlueprintCallable, BlueprintEvent)
void ABP_PromptActor_EmissarySoldLoot_OOS_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_PromptActor_EmissarySoldLoot_OOS.BP_PromptActor_EmissarySoldLoot_OOS_C.UserConstructionScript");
ABP_PromptActor_EmissarySoldLoot_OOS_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_PromptActor_EmissarySoldLoot_OOS.BP_PromptActor_EmissarySoldLoot_OOS_C.ReceiveEndPlay
// (Event, Public, BlueprintEvent)
// Parameters:
// TEnumAsByte<Engine_EEndPlayReason> EndPlayReason (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_PromptActor_EmissarySoldLoot_OOS_C::ReceiveEndPlay(TEnumAsByte<Engine_EEndPlayReason> EndPlayReason)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_PromptActor_EmissarySoldLoot_OOS.BP_PromptActor_EmissarySoldLoot_OOS_C.ReceiveEndPlay");
ABP_PromptActor_EmissarySoldLoot_OOS_C_ReceiveEndPlay_Params params;
params.EndPlayReason = EndPlayReason;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_PromptActor_EmissarySoldLoot_OOS.BP_PromptActor_EmissarySoldLoot_OOS_C.ReceiveBeginPlay
// (Event, Public, BlueprintEvent)
void ABP_PromptActor_EmissarySoldLoot_OOS_C::ReceiveBeginPlay()
{
static auto fn = UObject::FindObject<UFunction>("Function BP_PromptActor_EmissarySoldLoot_OOS.BP_PromptActor_EmissarySoldLoot_OOS_C.ReceiveBeginPlay");
ABP_PromptActor_EmissarySoldLoot_OOS_C_ReceiveBeginPlay_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function BP_PromptActor_EmissarySoldLoot_OOS.BP_PromptActor_EmissarySoldLoot_OOS_C.ExecuteUbergraph_BP_PromptActor_EmissarySoldLoot_OOS
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
void ABP_PromptActor_EmissarySoldLoot_OOS_C::ExecuteUbergraph_BP_PromptActor_EmissarySoldLoot_OOS(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function BP_PromptActor_EmissarySoldLoot_OOS.BP_PromptActor_EmissarySoldLoot_OOS_C.ExecuteUbergraph_BP_PromptActor_EmissarySoldLoot_OOS");
ABP_PromptActor_EmissarySoldLoot_OOS_C_ExecuteUbergraph_BP_PromptActor_EmissarySoldLoot_OOS_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void ABP_PromptActor_EmissarySoldLoot_OOS_C::AfterRead()
{
ABP_PromptActorBase_C::AfterRead();
READ_PTR_FULL(PromptCounterAccessKey, UClass);
READ_PTR_FULL(Company, UClass);
READ_PTR_FULL(PromptCoordinator, UBP_Prompt_EmissarySoldLoot_C);
}
void ABP_PromptActor_EmissarySoldLoot_OOS_C::BeforeDelete()
{
ABP_PromptActorBase_C::BeforeDelete();
DELE_PTR_FULL(PromptCounterAccessKey);
DELE_PTR_FULL(Company);
DELE_PTR_FULL(PromptCoordinator);
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"40242723+alxalx14@users.noreply.github.com"
] | 40242723+alxalx14@users.noreply.github.com |
c0ebe2844504b3f12511162a06efb6e20fb0f337 | c37126fbdbf55155c0fd73b16fcea60bf3887627 | /acmicpc.net/20170623_55_12015/original source.cpp | 2201399cb2c109d1e6d15ad16dd012f56347dbf9 | [] | no_license | Jyunpp/Algorithm | b95dfc1328be931a97def8e6f17058aece99fe5e | a26d9c4e305b0d80bce99302886ce8411e5470e5 | refs/heads/master | 2021-07-02T03:59:50.085470 | 2019-05-29T00:43:10 | 2019-05-29T00:43:10 | 83,957,639 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 335 | cpp | //20170623
#include <iostream>
#include <algorithm>
using namespace std;
int dp[1000001], len, N, temp;
int main() {
cin >> N;
for (int i = 1; i <= N; ++i) {
cin >> temp;
int *pos = lower_bound(dp + 1, dp + len + 1, temp);
*pos = temp;
if (pos == dp + len + 1)
len++;
}
cout << len << endl;
/*cin >> n;*/
return 0;
} | [
"kcjohnnykim@gmail.com"
] | kcjohnnykim@gmail.com |
823e15999c722575c3edbcb9ec3e1b70421b6475 | 73bd731e6e755378264edc7a7b5d16132d023b6a | /CodeForces/268B.cpp | 0632b4f10be25e0ed88077a0576b93ee6b96c83f | [] | no_license | IHR57/Competitive-Programming | 375e8112f7959ebeb2a1ed6a0613beec32ce84a5 | 5bc80359da3c0e5ada614a901abecbb6c8ce21a4 | refs/heads/master | 2023-01-24T01:33:02.672131 | 2023-01-22T14:34:31 | 2023-01-22T14:34:31 | 163,381,483 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 380 | cpp | #include <bits/stdc++.h>
#define MAX 100005
using namespace std;
typedef long long ll;
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
ll n, sum;
cin>>n;
if(n == 1){
cout<<1<<endl;
return 0;
}
sum = 0;
for(int i = n; i >= 1; i--){
sum += (i + (i - 1) * (n - i));
}
cout<<sum<<endl;
return 0;
}
| [
"iqbalhrasel95@gmail.com"
] | iqbalhrasel95@gmail.com |
4bcc089c6014a2a9c120113067c0bb4966bccfd8 | 770fe4667faa077389333ba619bff64491c6a77b | /First loops/Multiplication table/Multiplication table.cpp | a7e10a8d997965a6fd091d1d706fe0f86590e493 | [] | no_license | tagiramdark/JutgeEjercicios | 59332a79e58c612c90546f40a5f5c10a548c2f3a | d13444afe28607a5a17a38b60d71b16553c2a207 | refs/heads/master | 2022-03-04T19:25:03.793032 | 2019-11-04T22:06:38 | 2019-11-04T22:06:38 | 219,391,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | cpp | #include <iostream>
using namespace std;
int main()
{
int n=0;
cin >> n ;
int value=0;
for (int i = 0; i <= n; i++)
{
if (i != n)
cout << i * i * i << ",";
else
cout << i * i * i << endl;
}
}
| [
"garciaangel1510@hotmail.com"
] | garciaangel1510@hotmail.com |
58e52188302b58351205d4b3e826a862e6e63cce | 00da032d00cfafa03ed8e983475005c4e17beda4 | /src/wallet/wallet2.h | 8ae21cd42582171ae7287baf6bd3b111b3a725f1 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | wrkzdev/lethean | 92126bb7e250316bd44443bea2be7118fd737b1f | 0b117ff380ea6ee64a552e65a5d3ffd775b4af89 | refs/heads/main | 2023-06-14T15:21:01.510495 | 2021-06-28T13:02:54 | 2021-06-28T13:02:54 | 387,052,447 | 1 | 0 | NOASSERTION | 2021-07-17T23:12:16 | 2021-07-17T23:12:16 | null | UTF-8 | C++ | false | false | 57,302 | h | // Copyright (c) 2014-2017, The Monero 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.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#pragma once
#include <memory>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/serialization/list.hpp>
#include <boost/serialization/vector.hpp>
#include <atomic>
#include "include_base_utils.h"
#include "cryptonote_basic/account.h"
#include "cryptonote_basic/account_boost_serialization.h"
#include "cryptonote_basic/cryptonote_basic_impl.h"
#include "net/http_client.h"
#include "storages/http_abstract_invoke.h"
#include "rpc/core_rpc_server_commands_defs.h"
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "cryptonote_core/cryptonote_tx_utils.h"
#include "common/unordered_containers_boost_serialization.h"
#include "crypto/chacha8.h"
#include "crypto/hash.h"
#include "ringct/rctTypes.h"
#include "ringct/rctOps.h"
#include "wallet_errors.h"
#include "common/password.h"
#include "node_rpc_proxy.h"
#include <iostream>
#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "wallet.wallet2"
class Serialization_portability_wallet_Test;
namespace tools
{
class i_wallet2_callback
{
public:
virtual void on_new_block(uint64_t height, const cryptonote::block& block) {}
virtual void on_money_received(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t amount) {}
virtual void on_unconfirmed_money_received(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t amount) {}
virtual void on_money_spent(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& in_tx, uint64_t amount, const cryptonote::transaction& spend_tx) {}
virtual void on_skip_transaction(uint64_t height, const crypto::hash &txid, const cryptonote::transaction& tx) {}
virtual ~i_wallet2_callback() {}
};
struct tx_dust_policy
{
uint64_t dust_threshold;
bool add_to_fee;
cryptonote::account_public_address addr_for_dust;
tx_dust_policy(uint64_t a_dust_threshold = 0, bool an_add_to_fee = true, cryptonote::account_public_address an_addr_for_dust = cryptonote::account_public_address())
: dust_threshold(a_dust_threshold)
, add_to_fee(an_add_to_fee)
, addr_for_dust(an_addr_for_dust)
{
}
};
class wallet2
{
friend class ::Serialization_portability_wallet_Test;
public:
static constexpr const std::chrono::seconds rpc_timeout = std::chrono::minutes(3) + std::chrono::seconds(30);
enum RefreshType {
RefreshFull,
RefreshOptimizeCoinbase,
RefreshNoCoinbase,
RefreshDefault = RefreshOptimizeCoinbase,
};
private:
wallet2(const wallet2&) : m_run(true), m_callback(0), m_testnet(false), m_always_confirm_transfers(true), m_print_ring_members(false), m_store_tx_info(true), m_default_mixin(0), m_default_priority(0), m_refresh_type(RefreshOptimizeCoinbase), m_auto_refresh(true), m_refresh_from_block_height(0), m_confirm_missing_payment_id(true), m_ask_password(true), m_min_output_count(0), m_min_output_value(0), m_merge_destinations(false), m_confirm_backlog(true), m_is_initialized(false),m_node_rpc_proxy(m_http_client, m_daemon_rpc_mutex) {}
public:
static const char* tr(const char* str);
static bool has_testnet_option(const boost::program_options::variables_map& vm);
static void init_options(boost::program_options::options_description& desc_params);
//! \return Password retrieved from prompt. Logs error on failure.
static boost::optional<password_container> password_prompt(const bool new_password);
//! Uses stdin and stdout. Returns a wallet2 if no errors.
static std::unique_ptr<wallet2> make_from_json(const boost::program_options::variables_map& vm, const std::string& json_file);
//! Uses stdin and stdout. Returns a wallet2 and password for `wallet_file` if no errors.
static std::pair<std::unique_ptr<wallet2>, password_container>
make_from_file(const boost::program_options::variables_map& vm, const std::string& wallet_file);
//! Uses stdin and stdout. Upgrades legacy .wallet file to .keys. Returns true if keys file successfully generated.
static bool make_from_legacy(
const boost::program_options::variables_map& vm, const std::string& wallet_file);
//! Uses stdin and stdout. Returns a wallet2 and password for wallet with no file if no errors.
static std::pair<std::unique_ptr<wallet2>, password_container> make_new(const boost::program_options::variables_map& vm);
//! Just parses variables.
static std::unique_ptr<wallet2> make_dummy(const boost::program_options::variables_map& vm);
static bool verify_password(const std::string& keys_file_name, const std::string& password, bool watch_only);
wallet2(bool testnet = false, bool restricted = false) : m_run(true), m_callback(0), m_testnet(testnet), m_always_confirm_transfers(true), m_print_ring_members(false), m_store_tx_info(true), m_default_mixin(0), m_default_priority(0), m_refresh_type(RefreshOptimizeCoinbase), m_auto_refresh(true), m_refresh_from_block_height(0), m_confirm_missing_payment_id(true), m_ask_password(true), m_min_output_count(0), m_min_output_value(0), m_merge_destinations(false), m_confirm_backlog(true), m_is_initialized(false), m_restricted(restricted), is_old_file_format(false), m_node_rpc_proxy(m_http_client, m_daemon_rpc_mutex) {}
struct CryptoContext {
crypto::chacha8_key key;
crypto::chacha8_iv iv;
};
struct transfer_details
{
uint64_t m_block_height;
cryptonote::transaction_prefix m_tx;
crypto::hash m_txid;
size_t m_internal_output_index;
uint64_t m_global_output_index;
bool m_spent;
uint64_t m_spent_height;
crypto::key_image m_key_image; //TODO: key_image stored twice :(
rct::key m_mask;
uint64_t m_amount;
bool m_rct;
bool m_key_image_known;
size_t m_pk_index;
bool is_rct() const { return m_rct; }
uint64_t amount() const { return m_amount; }
const crypto::public_key &get_public_key() const { return boost::get<const cryptonote::txout_to_key>(m_tx.vout[m_internal_output_index].target).key; }
BEGIN_SERIALIZE_OBJECT()
FIELD(m_block_height)
FIELD(m_tx)
FIELD(m_txid)
FIELD(m_internal_output_index)
FIELD(m_global_output_index)
FIELD(m_spent)
FIELD(m_spent_height)
FIELD(m_key_image)
FIELD(m_mask)
FIELD(m_amount)
FIELD(m_rct)
FIELD(m_key_image_known)
FIELD(m_pk_index)
END_SERIALIZE()
};
struct payment_details
{
crypto::hash m_tx_hash;
uint64_t m_amount;
uint64_t m_block_height;
uint64_t m_unlock_time;
uint64_t m_timestamp;
};
struct unconfirmed_transfer_details
{
cryptonote::transaction_prefix m_tx;
uint64_t m_amount_in;
uint64_t m_amount_out;
uint64_t m_change;
time_t m_sent_time;
std::vector<cryptonote::tx_destination_entry> m_dests;
crypto::hash m_payment_id;
enum { pending, pending_not_in_pool, failed } m_state;
uint64_t m_timestamp;
};
struct confirmed_transfer_details
{
uint64_t m_amount_in;
uint64_t m_amount_out;
uint64_t m_change;
uint64_t m_block_height;
std::vector<cryptonote::tx_destination_entry> m_dests;
crypto::hash m_payment_id;
uint64_t m_timestamp;
uint64_t m_unlock_time;
confirmed_transfer_details(): m_amount_in(0), m_amount_out(0), m_change((uint64_t)-1), m_block_height(0), m_payment_id(cryptonote::null_hash), m_timestamp(0), m_unlock_time(0) {}
confirmed_transfer_details(const unconfirmed_transfer_details &utd, uint64_t height):
m_amount_in(utd.m_amount_in), m_amount_out(utd.m_amount_out), m_change(utd.m_change), m_block_height(height), m_dests(utd.m_dests), m_payment_id(utd.m_payment_id), m_timestamp(utd.m_timestamp), m_unlock_time(utd.m_tx.unlock_time) {}
};
struct tx_construction_data
{
std::vector<cryptonote::tx_source_entry> sources;
cryptonote::tx_destination_entry change_dts;
std::vector<cryptonote::tx_destination_entry> splitted_dsts; // split, includes change
std::list<size_t> selected_transfers;
std::vector<uint8_t> extra;
uint64_t unlock_time;
bool use_rct;
std::vector<cryptonote::tx_destination_entry> dests; // original setup, does not include change
};
typedef std::vector<transfer_details> transfer_container;
typedef std::unordered_multimap<crypto::hash, payment_details> payment_container;
// The convention for destinations is:
// dests does not include change
// splitted_dsts (in construction_data) does
struct pending_tx
{
cryptonote::transaction tx;
uint64_t dust, fee;
bool dust_added_to_fee;
cryptonote::tx_destination_entry change_dts;
std::list<size_t> selected_transfers;
std::string key_images;
crypto::secret_key tx_key;
std::vector<cryptonote::tx_destination_entry> dests;
tx_construction_data construction_data;
};
// The term "Unsigned tx" is not really a tx since it's not signed yet.
// It doesnt have tx hash, key and the integrated address is not separated into addr + payment id.
struct unsigned_tx_set
{
std::vector<tx_construction_data> txes;
wallet2::transfer_container transfers;
};
struct signed_tx_set
{
std::vector<pending_tx> ptx;
std::vector<crypto::key_image> key_images;
};
struct keys_file_data
{
crypto::chacha8_iv iv;
std::string account_data;
BEGIN_SERIALIZE_OBJECT()
FIELD(iv)
FIELD(account_data)
END_SERIALIZE()
};
struct cache_file_data
{
crypto::chacha8_iv iv;
std::string cache_data;
BEGIN_SERIALIZE_OBJECT()
FIELD(iv)
FIELD(cache_data)
END_SERIALIZE()
};
// GUI Address book
struct address_book_row
{
cryptonote::account_public_address m_address;
crypto::hash m_payment_id;
std::string m_description;
};
typedef std::tuple<uint64_t, crypto::public_key, rct::key> get_outs_entry;
/*!
* \brief Generates a wallet or restores one.
* \param wallet_ Name of wallet file
* \param password Password of wallet file
* \param recovery_param If it is a restore, the recovery key
* \param recover Whether it is a restore
* \param two_random Whether it is a non-deterministic wallet
* \return The secret key of the generated wallet
*/
crypto::secret_key generate(const std::string& wallet, const std::string& password,
const crypto::secret_key& recovery_param = crypto::secret_key(), bool recover = false,
bool two_random = false);
/*!
* \brief Creates a wallet from a public address and a spend/view secret key pair.
* \param wallet_ Name of wallet file
* \param password Password of wallet file
* \param viewkey view secret key
* \param spendkey spend secret key
*/
void generate(const std::string& wallet, const std::string& password,
const cryptonote::account_public_address &account_public_address,
const crypto::secret_key& spendkey, const crypto::secret_key& viewkey);
/*!
* \brief Creates a watch only wallet from a public address and a view secret key.
* \param wallet_ Name of wallet file
* \param password Password of wallet file
* \param viewkey view secret key
*/
void generate(const std::string& wallet, const std::string& password,
const cryptonote::account_public_address &account_public_address,
const crypto::secret_key& viewkey = crypto::secret_key());
/*!
* \brief Rewrites to the wallet file for wallet upgrade (doesn't generate key, assumes it's already there)
* \param wallet_name Name of wallet file (should exist)
* \param password Password for wallet file
*/
void rewrite(const std::string& wallet_name, const std::string& password);
void write_watch_only_wallet(const std::string& wallet_name, const std::string& password);
void load(const std::string& wallet, const std::string& password);
void store();
/*!
* \brief store_to - stores wallet to another file(s), deleting old ones
* \param path - path to the wallet file (keys and address filenames will be generated based on this filename)
* \param password - password to protect new wallet (TODO: probably better save the password in the wallet object?)
*/
void store_to(const std::string &path, const std::string &password);
std::string path() const;
/*!
* \brief verifies given password is correct for default wallet keys file
*/
bool verify_password(const std::string& password) const;
cryptonote::account_base& get_account(){return m_account;}
const cryptonote::account_base& get_account()const{return m_account;}
void set_refresh_from_block_height(uint64_t height) {m_refresh_from_block_height = height;}
uint64_t get_refresh_from_block_height() const {return m_refresh_from_block_height;}
// upper_transaction_size_limit as defined below is set to
// approximately 125% of the fixed minimum allowable penalty
// free block size. TODO: fix this so that it actually takes
// into account the current median block size rather than
// the minimum block size.
bool deinit();
bool init(std::string daemon_address = "http://localhost:8080",
boost::optional<epee::net_utils::http::login> daemon_login = boost::none, uint64_t upper_transaction_size_limit = 0);
void stop() { m_run.store(false, std::memory_order_relaxed); }
i_wallet2_callback* callback() const { return m_callback; }
void callback(i_wallet2_callback* callback) { m_callback = callback; }
/*!
* \brief Checks if deterministic wallet
*/
bool is_deterministic() const;
bool get_seed(std::string& electrum_words) const;
/*!
* \brief Gets the seed language
*/
const std::string &get_seed_language() const;
/*!
* \brief Sets the seed language
*/
void set_seed_language(const std::string &language);
/*!
* \brief Tells if the wallet file is deprecated.
*/
bool is_deprecated() const;
void refresh();
void refresh(uint64_t start_height, uint64_t & blocks_fetched);
void refresh(uint64_t start_height, uint64_t & blocks_fetched, bool& received_money);
bool refresh(uint64_t & blocks_fetched, bool& received_money, bool& ok);
void set_refresh_type(RefreshType refresh_type) { m_refresh_type = refresh_type; }
RefreshType get_refresh_type() const { return m_refresh_type; }
bool testnet() const { return m_testnet; }
bool restricted() const { return m_restricted; }
bool watch_only() const { return m_watch_only; }
uint64_t balance() const;
uint64_t unlocked_balance() const;
uint64_t unlocked_dust_balance(const tx_dust_policy &dust_policy) const;
template<typename T>
void transfer(const std::vector<cryptonote::tx_destination_entry>& dsts, const size_t fake_outputs_count, const std::vector<size_t> &unused_transfers_indices, uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, T destination_split_strategy, const tx_dust_policy& dust_policy, bool trusted_daemon);
template<typename T>
void transfer(const std::vector<cryptonote::tx_destination_entry>& dsts, const size_t fake_outputs_count, const std::vector<size_t> &unused_transfers_indices, uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, T destination_split_strategy, const tx_dust_policy& dust_policy, cryptonote::transaction& tx, pending_tx& ptx, bool trusted_daemon);
void transfer(const std::vector<cryptonote::tx_destination_entry>& dsts, const size_t fake_outputs_count, const std::vector<size_t> &unused_transfers_indices, uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, bool trusted_daemon);
void transfer(const std::vector<cryptonote::tx_destination_entry>& dsts, const size_t fake_outputs_count, const std::vector<size_t> &unused_transfers_indices, uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, cryptonote::transaction& tx, pending_tx& ptx, bool trusted_daemon);
template<typename T>
void transfer_selected(const std::vector<cryptonote::tx_destination_entry>& dsts, const std::list<size_t> selected_transfers, size_t fake_outputs_count,
std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs,
uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, T destination_split_strategy, const tx_dust_policy& dust_policy, cryptonote::transaction& tx, pending_tx &ptx);
void transfer_selected_rct(std::vector<cryptonote::tx_destination_entry> dsts, const std::list<size_t> selected_transfers, size_t fake_outputs_count,
std::vector<std::vector<tools::wallet2::get_outs_entry>> &outs,
uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, cryptonote::transaction& tx, pending_tx &ptx);
void commit_tx(pending_tx& ptx_vector);
void commit_tx(std::vector<pending_tx>& ptx_vector);
bool save_tx(const std::vector<pending_tx>& ptx_vector, const std::string &filename);
// load unsigned tx from file and sign it. Takes confirmation callback as argument. Used by the cli wallet
bool sign_tx(const std::string &unsigned_filename, const std::string &signed_filename, std::vector<wallet2::pending_tx> &ptx, std::function<bool(const unsigned_tx_set&)> accept_func = NULL);
// sign unsigned tx. Takes unsigned_tx_set as argument. Used by GUI
bool sign_tx(unsigned_tx_set &exported_txs, const std::string &signed_filename, std::vector<wallet2::pending_tx> &ptx);
// load unsigned_tx_set from file.
bool load_unsigned_tx(const std::string &unsigned_filename, unsigned_tx_set &exported_txs);
bool load_tx(const std::string &signed_filename, std::vector<tools::wallet2::pending_tx> &ptx, std::function<bool(const signed_tx_set&)> accept_func = NULL);
std::vector<pending_tx> create_transactions(std::vector<cryptonote::tx_destination_entry> dsts, const size_t fake_outs_count, const uint64_t unlock_time, uint32_t priority, const std::vector<uint8_t> extra, bool trusted_daemon);
std::vector<wallet2::pending_tx> create_transactions_2(std::vector<cryptonote::tx_destination_entry> dsts, const size_t fake_outs_count, const uint64_t unlock_time, uint32_t priority, const std::vector<uint8_t> extra, bool trusted_daemon);
std::vector<wallet2::pending_tx> create_transactions_all(uint64_t below, const cryptonote::account_public_address &address, const size_t fake_outs_count, const uint64_t unlock_time, uint32_t priority, const std::vector<uint8_t> extra, bool trusted_daemon);
std::vector<wallet2::pending_tx> create_transactions_from(const cryptonote::account_public_address &address, std::vector<size_t> unused_transfers_indices, std::vector<size_t> unused_dust_indices, const size_t fake_outs_count, const uint64_t unlock_time, uint32_t priority, const std::vector<uint8_t> extra, bool trusted_daemon);
std::vector<pending_tx> create_unmixable_sweep_transactions(bool trusted_daemon);
bool check_connection(uint32_t *version = NULL, uint32_t timeout = 200000);
void get_transfers(wallet2::transfer_container& incoming_transfers) const;
void get_payments(const crypto::hash& payment_id, std::list<wallet2::payment_details>& payments, uint64_t min_height = 0) const;
void get_payments(std::list<std::pair<crypto::hash,wallet2::payment_details>>& payments, uint64_t min_height, uint64_t max_height = (uint64_t)-1) const;
void get_payments_out(std::list<std::pair<crypto::hash,wallet2::confirmed_transfer_details>>& confirmed_payments,
uint64_t min_height, uint64_t max_height = (uint64_t)-1) const;
void get_unconfirmed_payments_out(std::list<std::pair<crypto::hash,wallet2::unconfirmed_transfer_details>>& unconfirmed_payments) const;
void get_unconfirmed_payments(std::list<std::pair<crypto::hash,wallet2::payment_details>>& unconfirmed_payments) const;
uint64_t get_blockchain_current_height() const { return m_local_bc_height; }
void rescan_spent();
void rescan_blockchain(bool refresh = true);
bool is_transfer_unlocked(const transfer_details& td) const;
template <class t_archive>
inline void serialize(t_archive &a, const unsigned int ver)
{
uint64_t dummy_refresh_height = 0; // moved to keys file
if(ver < 5)
return;
a & m_blockchain;
a & m_transfers;
a & m_account_public_address;
a & m_key_images;
if(ver < 6)
return;
a & m_unconfirmed_txs;
if(ver < 7)
return;
a & m_payments;
if(ver < 8)
return;
a & m_tx_keys;
if(ver < 9)
return;
a & m_confirmed_txs;
if(ver < 11)
return;
a & dummy_refresh_height;
if(ver < 12)
return;
a & m_tx_notes;
if(ver < 13)
return;
if (ver < 17)
{
// we're loading an old version, where m_unconfirmed_payments was a std::map
std::unordered_map<crypto::hash, payment_details> m;
a & m;
for (std::unordered_map<crypto::hash, payment_details>::const_iterator i = m.begin(); i != m.end(); ++i)
m_unconfirmed_payments.insert(*i);
}
if(ver < 14)
return;
if(ver < 15)
{
// we're loading an older wallet without a pubkey map, rebuild it
for (size_t i = 0; i < m_transfers.size(); ++i)
{
const transfer_details &td = m_transfers[i];
const cryptonote::tx_out &out = td.m_tx.vout[td.m_internal_output_index];
const cryptonote::txout_to_key &o = boost::get<const cryptonote::txout_to_key>(out.target);
m_pub_keys.emplace(o.key, i);
}
return;
}
a & m_pub_keys;
if(ver < 16)
return;
a & m_address_book;
if(ver < 17)
return;
a & m_unconfirmed_payments;
if(ver < 18)
return;
a & m_scanned_pool_txs[0];
a & m_scanned_pool_txs[1];
}
/*!
* \brief Check if wallet keys and bin files exist
* \param file_path Wallet file path
* \param keys_file_exists Whether keys file exists
* \param wallet_file_exists Whether bin file exists
*/
static void wallet_exists(const std::string& file_path, bool& keys_file_exists, bool& wallet_file_exists);
/*!
* \brief Check if wallet file path is valid format
* \param file_path Wallet file path
* \return Whether path is valid format
*/
static bool wallet_valid_path_format(const std::string& file_path);
static bool parse_long_payment_id(const std::string& payment_id_str, crypto::hash& payment_id);
static bool parse_short_payment_id(const std::string& payment_id_str, crypto::hash8& payment_id);
static bool parse_payment_id(const std::string& payment_id_str, crypto::hash& payment_id);
bool always_confirm_transfers() const { return m_always_confirm_transfers; }
void always_confirm_transfers(bool always) { m_always_confirm_transfers = always; }
bool print_ring_members() const { return m_print_ring_members; }
void print_ring_members(bool value) { m_print_ring_members = value; }
bool store_tx_info() const { return m_store_tx_info; }
void store_tx_info(bool store) { m_store_tx_info = store; }
uint32_t default_mixin() const { return m_default_mixin; }
void default_mixin(uint32_t m) { m_default_mixin = m; }
uint32_t get_default_priority() const { return m_default_priority; }
void set_default_priority(uint32_t p) { m_default_priority = p; }
bool auto_refresh() const { return m_auto_refresh; }
void auto_refresh(bool r) { m_auto_refresh = r; }
bool confirm_missing_payment_id() const { return m_confirm_missing_payment_id; }
void confirm_missing_payment_id(bool always) { m_confirm_missing_payment_id = always; }
bool ask_password() const { return m_ask_password; }
void ask_password(bool always) { m_ask_password = always; }
void set_default_decimal_point(unsigned int decimal_point);
unsigned int get_default_decimal_point() const;
void set_min_output_count(uint32_t count) { m_min_output_count = count; }
uint32_t get_min_output_count() const { return m_min_output_count; }
void set_min_output_value(uint64_t value) { m_min_output_value = value; }
uint64_t get_min_output_value() const { return m_min_output_value; }
void merge_destinations(bool merge) { m_merge_destinations = merge; }
bool merge_destinations() const { return m_merge_destinations; }
bool confirm_backlog() const { return m_confirm_backlog; }
void confirm_backlog(bool always) { m_confirm_backlog = always; }
bool get_tx_key(const crypto::hash &txid, crypto::secret_key &tx_key) const;
/*!
* \brief GUI Address book get/store
*/
std::vector<address_book_row> get_address_book() const { return m_address_book; }
bool add_address_book_row(const cryptonote::account_public_address &address, const crypto::hash &payment_id, const std::string &description);
bool delete_address_book_row(std::size_t row_id);
uint64_t get_num_rct_outputs();
const transfer_details &get_transfer_details(size_t idx) const;
void get_hard_fork_info(uint8_t version, uint64_t &earliest_height);
bool use_fork_rules(uint8_t version, int64_t early_blocks = 0);
int get_fee_algorithm();
std::string get_wallet_file() const;
std::string get_keys_file() const;
std::string get_daemon_address() const;
const boost::optional<epee::net_utils::http::login>& get_daemon_login() const { return m_daemon_login; }
uint64_t get_daemon_blockchain_height(std::string& err);
uint64_t get_daemon_blockchain_target_height(std::string& err);
/*!
* \brief Calculates the approximate blockchain height from current date/time.
*/
uint64_t get_approximate_blockchain_height() const;
std::vector<size_t> select_available_outputs_from_histogram(uint64_t count, bool atleast, bool unlocked, bool allow_rct, bool trusted_daemon);
std::vector<size_t> select_available_outputs(const std::function<bool(const transfer_details &td)> &f);
std::vector<size_t> select_available_unmixable_outputs(bool trusted_daemon);
std::vector<size_t> select_available_mixable_outputs(bool trusted_daemon);
size_t pop_best_value_from(const transfer_container &transfers, std::vector<size_t> &unused_dust_indices, const std::list<size_t>& selected_transfers, bool smallest = false) const;
size_t pop_best_value(std::vector<size_t> &unused_dust_indices, const std::list<size_t>& selected_transfers, bool smallest = false) const;
void set_tx_note(const crypto::hash &txid, const std::string ¬e);
std::string get_tx_note(const crypto::hash &txid) const;
std::string sign(const std::string &data) const;
bool verify(const std::string &data, const cryptonote::account_public_address &address, const std::string &signature) const;
std::vector<tools::wallet2::transfer_details> export_outputs() const;
size_t import_outputs(const std::vector<tools::wallet2::transfer_details> &outputs);
bool export_key_images(const std::string filename);
std::vector<std::pair<crypto::key_image, crypto::signature>> export_key_images() const;
uint64_t import_key_images(const std::vector<std::pair<crypto::key_image, crypto::signature>> &signed_key_images, uint64_t &spent, uint64_t &unspent);
uint64_t import_key_images(const std::string &filename, uint64_t &spent, uint64_t &unspent);
void update_pool_state(bool refreshed = false);
std::string encrypt(const std::string &plaintext, const crypto::secret_key &skey, bool authenticated = true) const;
std::string encrypt_with_view_secret_key(const std::string &plaintext, bool authenticated = true) const;
std::string decrypt(const std::string &ciphertext, const crypto::secret_key &skey, bool authenticated = true) const;
std::string decrypt_with_view_secret_key(const std::string &ciphertext, bool authenticated = true) const;
std::string make_uri(const std::string &address, const std::string &payment_id, uint64_t amount, const std::string &tx_description, const std::string &recipient_name, std::string &error);
bool parse_uri(const std::string &uri, std::string &address, std::string &payment_id, uint64_t &amount, std::string &tx_description, std::string &recipient_name, std::vector<std::string> &unknown_parameters, std::string &error);
uint64_t get_blockchain_height_by_date(uint16_t year, uint8_t month, uint8_t day); // 1<=month<=12, 1<=day<=31
bool is_synced() const;
std::vector<std::pair<uint64_t, uint64_t>> estimate_backlog(uint64_t min_blob_size, uint64_t max_blob_size, const std::vector<uint64_t> &fees);
uint64_t get_fee_multiplier(uint32_t priority, int fee_algorithm = -1);
uint64_t get_per_kb_fee();
private:
/*!
* \brief Stores wallet information to wallet file.
* \param keys_file_name Name of wallet file
* \param password Password of wallet file
* \param watch_only true to save only view key, false to save both spend and view keys
* \return Whether it was successful.
*/
bool store_keys(const std::string& keys_file_name, const std::string& password, bool watch_only = false);
/*!
* \brief Load wallet information from wallet file.
* \param keys_file_name Name of wallet file
* \param password Password of wallet file
*/
bool load_keys(const std::string& keys_file_name, const std::string& password);
bool upgrade_legacy_wallet(const std::string& wallet_file_name, const std::string& password);
void process_new_transaction(const crypto::hash &txid, const cryptonote::transaction& tx, const std::vector<uint64_t> &o_indices, uint64_t height, uint64_t ts, bool miner_tx, bool pool);
void process_new_blockchain_entry(const cryptonote::block& b, const cryptonote::block_complete_entry& bche, const crypto::hash& bl_id, uint64_t height, const cryptonote::COMMAND_RPC_GET_BLOCKS_FAST::block_output_indices &o_indices);
void detach_blockchain(uint64_t height);
void get_short_chain_history(std::list<crypto::hash>& ids) const;
bool is_tx_spendtime_unlocked(uint64_t unlock_time, uint64_t block_height) const;
bool clear();
void pull_blocks(uint64_t start_height, uint64_t& blocks_start_height, const std::list<crypto::hash> &short_chain_history, std::list<cryptonote::block_complete_entry> &blocks, std::vector<cryptonote::COMMAND_RPC_GET_BLOCKS_FAST::block_output_indices> &o_indices);
void pull_hashes(uint64_t start_height, uint64_t& blocks_start_height, const std::list<crypto::hash> &short_chain_history, std::list<crypto::hash> &hashes);
void fast_refresh(uint64_t stop_height, uint64_t &blocks_start_height, std::list<crypto::hash> &short_chain_history);
void pull_next_blocks(uint64_t start_height, uint64_t &blocks_start_height, std::list<crypto::hash> &short_chain_history, const std::list<cryptonote::block_complete_entry> &prev_blocks, std::list<cryptonote::block_complete_entry> &blocks, std::vector<cryptonote::COMMAND_RPC_GET_BLOCKS_FAST::block_output_indices> &o_indices, bool &error);
void process_blocks(uint64_t start_height, const std::list<cryptonote::block_complete_entry> &blocks, const std::vector<cryptonote::COMMAND_RPC_GET_BLOCKS_FAST::block_output_indices> &o_indices, uint64_t& blocks_added);
uint64_t select_transfers(uint64_t needed_money, std::vector<size_t> unused_transfers_indices, std::list<size_t>& selected_transfers, bool trusted_daemon);
bool prepare_file_names(const std::string& file_path);
void process_unconfirmed(const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t height);
void process_outgoing(const crypto::hash &txid, const cryptonote::transaction& tx, uint64_t height, uint64_t ts, uint64_t spent, uint64_t received);
void add_unconfirmed_tx(const cryptonote::transaction& tx, uint64_t amount_in, const std::vector<cryptonote::tx_destination_entry> &dests, const crypto::hash &payment_id, uint64_t change_amount);
void generate_genesis(cryptonote::block& b);
void check_genesis(const crypto::hash& genesis_hash) const; //throws
bool generate_chacha8_key_from_secret_keys(crypto::chacha8_key &key) const;
crypto::hash get_payment_id(const pending_tx &ptx) const;
crypto::hash8 get_short_payment_id(const pending_tx &ptx) const;
void check_acc_out_precomp(const crypto::public_key &spend_public_key, const cryptonote::tx_out &o, const crypto::key_derivation &derivation, size_t i, bool &received, uint64_t &money_transfered, bool &error) const;
void parse_block_round(const cryptonote::blobdata &blob, cryptonote::block &bl, crypto::hash &bl_id, bool &error) const;
uint64_t get_upper_transaction_size_limit();
std::vector<uint64_t> get_unspent_amounts_vector();
uint64_t get_dynamic_per_kb_fee_estimate();
float get_output_relatedness(const transfer_details &td0, const transfer_details &td1) const;
std::vector<size_t> pick_preferred_rct_inputs(uint64_t needed_money) const;
void set_spent(size_t idx, uint64_t height);
void set_unspent(size_t idx);
void get_outs(std::vector<std::vector<get_outs_entry>> &outs, const std::list<size_t> &selected_transfers, size_t fake_outputs_count);
bool wallet_generate_key_image_helper(const cryptonote::account_keys& ack, const crypto::public_key& tx_public_key, size_t real_output_index, cryptonote::keypair& in_ephemeral, crypto::key_image& ki);
crypto::public_key get_tx_pub_key_from_received_outs(const tools::wallet2::transfer_details &td) const;
bool should_pick_a_second_output(bool use_rct, size_t n_transfers, const std::vector<size_t> &unused_transfers_indices, const std::vector<size_t> &unused_dust_indices) const;
std::vector<size_t> get_only_rct(const std::vector<size_t> &unused_dust_indices, const std::vector<size_t> &unused_transfers_indices) const;
cryptonote::account_base m_account;
boost::optional<epee::net_utils::http::login> m_daemon_login;
std::string m_daemon_address;
std::string m_wallet_file;
std::string m_keys_file;
epee::net_utils::http::http_simple_client m_http_client;
std::vector<crypto::hash> m_blockchain;
std::atomic<uint64_t> m_local_bc_height; //temporary workaround
std::unordered_map<crypto::hash, unconfirmed_transfer_details> m_unconfirmed_txs;
std::unordered_map<crypto::hash, confirmed_transfer_details> m_confirmed_txs;
std::unordered_multimap<crypto::hash, payment_details> m_unconfirmed_payments;
std::unordered_map<crypto::hash, crypto::secret_key> m_tx_keys;
transfer_container m_transfers;
payment_container m_payments;
std::unordered_map<crypto::key_image, size_t> m_key_images;
std::unordered_map<crypto::public_key, size_t> m_pub_keys;
cryptonote::account_public_address m_account_public_address;
std::unordered_map<crypto::hash, std::string> m_tx_notes;
std::vector<tools::wallet2::address_book_row> m_address_book;
uint64_t m_upper_transaction_size_limit; //TODO: auto-calc this value or request from daemon, now use some fixed value
std::atomic<bool> m_run;
boost::mutex m_daemon_rpc_mutex;
i_wallet2_callback* m_callback;
bool m_testnet;
bool m_restricted;
std::string seed_language; /*!< Language of the mnemonics (seed). */
bool is_old_file_format; /*!< Whether the wallet file is of an old file format */
bool m_watch_only; /*!< no spend key */
bool m_always_confirm_transfers;
bool m_print_ring_members;
bool m_store_tx_info; /*!< request txkey to be returned in RPC, and store in the wallet cache file */
uint32_t m_default_mixin;
uint32_t m_default_priority;
RefreshType m_refresh_type;
bool m_auto_refresh;
uint64_t m_refresh_from_block_height;
bool m_confirm_missing_payment_id;
bool m_ask_password;
uint32_t m_min_output_count;
uint64_t m_min_output_value;
bool m_merge_destinations;
bool m_confirm_backlog;
bool m_is_initialized;
NodeRPCProxy m_node_rpc_proxy;
std::unordered_set<crypto::hash> m_scanned_pool_txs[2];
};
}
BOOST_CLASS_VERSION(tools::wallet2, 18)
BOOST_CLASS_VERSION(tools::wallet2::transfer_details, 7)
BOOST_CLASS_VERSION(tools::wallet2::payment_details, 1)
BOOST_CLASS_VERSION(tools::wallet2::unconfirmed_transfer_details, 6)
BOOST_CLASS_VERSION(tools::wallet2::confirmed_transfer_details, 4)
BOOST_CLASS_VERSION(tools::wallet2::address_book_row, 16)
BOOST_CLASS_VERSION(tools::wallet2::unsigned_tx_set, 0)
BOOST_CLASS_VERSION(tools::wallet2::signed_tx_set, 0)
BOOST_CLASS_VERSION(tools::wallet2::tx_construction_data, 0)
BOOST_CLASS_VERSION(tools::wallet2::pending_tx, 0)
namespace boost
{
namespace serialization
{
template <class Archive>
inline typename std::enable_if<!Archive::is_loading::value, void>::type initialize_transfer_details(Archive &a, tools::wallet2::transfer_details &x, const boost::serialization::version_type ver)
{
}
template <class Archive>
inline typename std::enable_if<Archive::is_loading::value, void>::type initialize_transfer_details(Archive &a, tools::wallet2::transfer_details &x, const boost::serialization::version_type ver)
{
if (ver < 1)
{
x.m_mask = rct::identity();
x.m_amount = x.m_tx.vout[x.m_internal_output_index].amount;
}
if (ver < 2)
{
x.m_spent_height = 0;
}
if (ver < 4)
{
x.m_rct = x.m_tx.vout[x.m_internal_output_index].amount == 0;
}
if (ver < 6)
{
x.m_key_image_known = true;
}
if (ver < 7)
{
x.m_pk_index = 0;
}
}
template <class Archive>
inline void serialize(Archive &a, tools::wallet2::transfer_details &x, const boost::serialization::version_type ver)
{
a & x.m_block_height;
a & x.m_global_output_index;
a & x.m_internal_output_index;
if (ver < 3)
{
cryptonote::transaction tx;
a & tx;
x.m_tx = (const cryptonote::transaction_prefix&)tx;
x.m_txid = cryptonote::get_transaction_hash(tx);
}
else
{
a & x.m_tx;
}
a & x.m_spent;
a & x.m_key_image;
if (ver < 1)
{
// ensure mask and amount are set
initialize_transfer_details(a, x, ver);
return;
}
a & x.m_mask;
a & x.m_amount;
if (ver < 2)
{
initialize_transfer_details(a, x, ver);
return;
}
a & x.m_spent_height;
if (ver < 3)
{
initialize_transfer_details(a, x, ver);
return;
}
a & x.m_txid;
if (ver < 4)
{
initialize_transfer_details(a, x, ver);
return;
}
a & x.m_rct;
if (ver < 5)
{
initialize_transfer_details(a, x, ver);
return;
}
if (ver < 6)
{
// v5 did not properly initialize
uint8_t u;
a & u;
x.m_key_image_known = true;
return;
}
a & x.m_key_image_known;
if (ver < 7)
{
initialize_transfer_details(a, x, ver);
return;
}
a & x.m_pk_index;
}
template <class Archive>
inline void serialize(Archive &a, tools::wallet2::unconfirmed_transfer_details &x, const boost::serialization::version_type ver)
{
a & x.m_change;
a & x.m_sent_time;
if (ver < 5)
{
cryptonote::transaction tx;
a & tx;
x.m_tx = (const cryptonote::transaction_prefix&)tx;
}
else
{
a & x.m_tx;
}
if (ver < 1)
return;
a & x.m_dests;
a & x.m_payment_id;
if (ver < 2)
return;
a & x.m_state;
if (ver < 3)
return;
a & x.m_timestamp;
if (ver < 4)
return;
a & x.m_amount_in;
a & x.m_amount_out;
if (ver < 6)
{
// v<6 may not have change accumulated in m_amount_out, which is a pain,
// as it's readily understood to be sum of outputs.
// We convert it to include change from v6
if (!typename Archive::is_saving() && x.m_change != (uint64_t)-1)
x.m_amount_out += x.m_change;
}
}
template <class Archive>
inline void serialize(Archive &a, tools::wallet2::confirmed_transfer_details &x, const boost::serialization::version_type ver)
{
a & x.m_amount_in;
a & x.m_amount_out;
a & x.m_change;
a & x.m_block_height;
if (ver < 1)
return;
a & x.m_dests;
a & x.m_payment_id;
if (ver < 2)
return;
a & x.m_timestamp;
if (ver < 3)
{
// v<3 may not have change accumulated in m_amount_out, which is a pain,
// as it's readily understood to be sum of outputs. Whether it got added
// or not depends on whether it came from a unconfirmed_transfer_details
// (not included) or not (included). We can't reliably tell here, so we
// check whether either yields a "negative" fee, or use the other if so.
// We convert it to include change from v3
if (!typename Archive::is_saving() && x.m_change != (uint64_t)-1)
{
if (x.m_amount_in > (x.m_amount_out + x.m_change))
x.m_amount_out += x.m_change;
}
}
if (ver < 4)
{
if (!typename Archive::is_saving())
x.m_unlock_time = 0;
return;
}
a & x.m_unlock_time;
}
template <class Archive>
inline void serialize(Archive& a, tools::wallet2::payment_details& x, const boost::serialization::version_type ver)
{
a & x.m_tx_hash;
a & x.m_amount;
a & x.m_block_height;
a & x.m_unlock_time;
if (ver < 1)
return;
a & x.m_timestamp;
}
template <class Archive>
inline void serialize(Archive& a, cryptonote::tx_destination_entry& x, const boost::serialization::version_type ver)
{
a & x.amount;
a & x.addr;
}
template <class Archive>
inline void serialize(Archive& a, tools::wallet2::address_book_row& x, const boost::serialization::version_type ver)
{
a & x.m_address;
a & x.m_payment_id;
a & x.m_description;
}
template <class Archive>
inline void serialize(Archive &a, tools::wallet2::unsigned_tx_set &x, const boost::serialization::version_type ver)
{
a & x.txes;
a & x.transfers;
}
template <class Archive>
inline void serialize(Archive &a, tools::wallet2::signed_tx_set &x, const boost::serialization::version_type ver)
{
a & x.ptx;
a & x.key_images;
}
template <class Archive>
inline void serialize(Archive &a, tools::wallet2::tx_construction_data &x, const boost::serialization::version_type ver)
{
a & x.sources;
a & x.change_dts;
a & x.splitted_dsts;
a & x.selected_transfers;
a & x.extra;
a & x.unlock_time;
a & x.use_rct;
a & x.dests;
}
template <class Archive>
inline void serialize(Archive &a, tools::wallet2::pending_tx &x, const boost::serialization::version_type ver)
{
a & x.tx;
a & x.dust;
a & x.fee;
a & x.dust_added_to_fee;
a & x.change_dts;
a & x.selected_transfers;
a & x.key_images;
a & x.tx_key;
a & x.dests;
a & x.construction_data;
}
}
}
namespace tools
{
namespace detail
{
//----------------------------------------------------------------------------------------------------
inline void digit_split_strategy(const std::vector<cryptonote::tx_destination_entry>& dsts,
const cryptonote::tx_destination_entry& change_dst, uint64_t dust_threshold,
std::vector<cryptonote::tx_destination_entry>& splitted_dsts, std::vector<cryptonote::tx_destination_entry> &dust_dsts)
{
splitted_dsts.clear();
dust_dsts.clear();
for(auto& de: dsts)
{
cryptonote::decompose_amount_into_digits(de.amount, 0,
[&](uint64_t chunk) { splitted_dsts.push_back(cryptonote::tx_destination_entry(chunk, de.addr)); },
[&](uint64_t a_dust) { splitted_dsts.push_back(cryptonote::tx_destination_entry(a_dust, de.addr)); } );
}
cryptonote::decompose_amount_into_digits(change_dst.amount, 0,
[&](uint64_t chunk) {
if (chunk <= dust_threshold)
dust_dsts.push_back(cryptonote::tx_destination_entry(chunk, change_dst.addr));
else
splitted_dsts.push_back(cryptonote::tx_destination_entry(chunk, change_dst.addr));
},
[&](uint64_t a_dust) { dust_dsts.push_back(cryptonote::tx_destination_entry(a_dust, change_dst.addr)); } );
}
//----------------------------------------------------------------------------------------------------
inline void null_split_strategy(const std::vector<cryptonote::tx_destination_entry>& dsts,
const cryptonote::tx_destination_entry& change_dst, uint64_t dust_threshold,
std::vector<cryptonote::tx_destination_entry>& splitted_dsts, std::vector<cryptonote::tx_destination_entry> &dust_dsts)
{
splitted_dsts = dsts;
dust_dsts.clear();
uint64_t change = change_dst.amount;
if (0 != change)
{
splitted_dsts.push_back(cryptonote::tx_destination_entry(change, change_dst.addr));
}
}
//----------------------------------------------------------------------------------------------------
inline void print_source_entry(const cryptonote::tx_source_entry& src)
{
std::string indexes;
std::for_each(src.outputs.begin(), src.outputs.end(), [&](const cryptonote::tx_source_entry::output_entry& s_e) { indexes += boost::to_string(s_e.first) + " "; });
LOG_PRINT_L0("amount=" << cryptonote::print_money(src.amount) << ", real_output=" <<src.real_output << ", real_output_in_tx_index=" << src.real_output_in_tx_index << ", indexes: " << indexes);
}
//----------------------------------------------------------------------------------------------------
}
//----------------------------------------------------------------------------------------------------
template<typename T>
void wallet2::transfer(const std::vector<cryptonote::tx_destination_entry>& dsts, const size_t fake_outs_count, const std::vector<size_t> &unused_transfers_indices,
uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, T destination_split_strategy, const tx_dust_policy& dust_policy, bool trusted_daemon)
{
pending_tx ptx;
cryptonote::transaction tx;
transfer(dsts, fake_outs_count, unused_transfers_indices, unlock_time, fee, extra, destination_split_strategy, dust_policy, tx, ptx, trusted_daemon);
}
template<typename T>
void wallet2::transfer(const std::vector<cryptonote::tx_destination_entry>& dsts, size_t fake_outputs_count, const std::vector<size_t> &unused_transfers_indices,
uint64_t unlock_time, uint64_t fee, const std::vector<uint8_t>& extra, T destination_split_strategy, const tx_dust_policy& dust_policy, cryptonote::transaction& tx, pending_tx &ptx, bool trusted_daemon)
{
using namespace cryptonote;
// throw if attempting a transaction with no destinations
THROW_WALLET_EXCEPTION_IF(dsts.empty(), error::zero_destination);
uint64_t upper_transaction_size_limit = get_upper_transaction_size_limit();
uint64_t needed_money = fee;
// calculate total amount being sent to all destinations
// throw if total amount overflows uint64_t
for(auto& dt: dsts)
{
THROW_WALLET_EXCEPTION_IF(0 == dt.amount, error::zero_destination);
needed_money += dt.amount;
THROW_WALLET_EXCEPTION_IF(needed_money < dt.amount, error::tx_sum_overflow, dsts, fee, m_testnet);
}
// randomly select inputs for transaction
// throw if requested send amount is greater than amount available to send
std::list<size_t> selected_transfers;
uint64_t found_money = select_transfers(needed_money, unused_transfers_indices, selected_transfers, trusted_daemon);
THROW_WALLET_EXCEPTION_IF(found_money < needed_money, error::not_enough_money, found_money, needed_money - fee, fee);
typedef COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry out_entry;
typedef cryptonote::tx_source_entry::output_entry tx_output_entry;
COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::response daemon_resp = AUTO_VAL_INIT(daemon_resp);
if(fake_outputs_count)
{
COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::request req = AUTO_VAL_INIT(req);
req.outs_count = fake_outputs_count + 1;// add one to make possible (if need) to skip real output key
for(size_t idx: selected_transfers)
{
const transfer_container::const_iterator it = m_transfers.begin() + idx;
THROW_WALLET_EXCEPTION_IF(it->m_tx.vout.size() <= it->m_internal_output_index, error::wallet_internal_error,
"m_internal_output_index = " + std::to_string(it->m_internal_output_index) +
" is greater or equal to outputs count = " + std::to_string(it->m_tx.vout.size()));
req.amounts.push_back(it->amount());
}
m_daemon_rpc_mutex.lock();
bool r = epee::net_utils::invoke_http_bin("/getrandom_outs.bin", req, daemon_resp, m_http_client, rpc_timeout);
m_daemon_rpc_mutex.unlock();
THROW_WALLET_EXCEPTION_IF(!r, error::no_connection_to_daemon, "getrandom_outs.bin");
THROW_WALLET_EXCEPTION_IF(daemon_resp.status == CORE_RPC_STATUS_BUSY, error::daemon_busy, "getrandom_outs.bin");
THROW_WALLET_EXCEPTION_IF(daemon_resp.status != CORE_RPC_STATUS_OK, error::get_random_outs_error, daemon_resp.status);
THROW_WALLET_EXCEPTION_IF(daemon_resp.outs.size() != selected_transfers.size(), error::wallet_internal_error,
"daemon returned wrong response for getrandom_outs.bin, wrong amounts count = " +
std::to_string(daemon_resp.outs.size()) + ", expected " + std::to_string(selected_transfers.size()));
std::unordered_map<uint64_t, uint64_t> scanty_outs;
for(COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount& amount_outs: daemon_resp.outs)
{
if (amount_outs.outs.size() < fake_outputs_count)
{
scanty_outs[amount_outs.amount] = amount_outs.outs.size();
}
}
THROW_WALLET_EXCEPTION_IF(!scanty_outs.empty(), error::not_enough_outs_to_mix, scanty_outs, fake_outputs_count);
}
//prepare inputs
size_t i = 0;
std::vector<cryptonote::tx_source_entry> sources;
for(size_t idx: selected_transfers)
{
sources.resize(sources.size()+1);
cryptonote::tx_source_entry& src = sources.back();
const transfer_details& td = m_transfers[idx];
src.amount = td.amount();
src.rct = false;
//paste mixin transaction
if(daemon_resp.outs.size())
{
daemon_resp.outs[i].outs.sort([](const out_entry& a, const out_entry& b){return a.global_amount_index < b.global_amount_index;});
for(out_entry& daemon_oe: daemon_resp.outs[i].outs)
{
if(td.m_global_output_index == daemon_oe.global_amount_index)
continue;
tx_output_entry oe;
oe.first = daemon_oe.global_amount_index;
oe.second.dest = rct::pk2rct(daemon_oe.out_key);
oe.second.mask = rct::identity();
src.outputs.push_back(oe);
if(src.outputs.size() >= fake_outputs_count)
break;
}
}
//paste real transaction to the random index
auto it_to_insert = std::find_if(src.outputs.begin(), src.outputs.end(), [&](const tx_output_entry& a)
{
return a.first >= td.m_global_output_index;
});
//size_t real_index = src.outputs.size() ? (rand() % src.outputs.size() ):0;
tx_output_entry real_oe;
real_oe.first = td.m_global_output_index;
real_oe.second.dest = rct::pk2rct(boost::get<txout_to_key>(td.m_tx.vout[td.m_internal_output_index].target).key);
real_oe.second.mask = rct::identity();
auto interted_it = src.outputs.insert(it_to_insert, real_oe);
src.real_out_tx_key = get_tx_pub_key_from_extra(td.m_tx);
src.real_output = interted_it - src.outputs.begin();
src.real_output_in_tx_index = td.m_internal_output_index;
detail::print_source_entry(src);
++i;
}
cryptonote::tx_destination_entry change_dts = AUTO_VAL_INIT(change_dts);
if (needed_money < found_money)
{
change_dts.addr = m_account.get_keys().m_account_address;
change_dts.amount = found_money - needed_money;
}
std::vector<cryptonote::tx_destination_entry> splitted_dsts, dust_dsts;
uint64_t dust = 0;
destination_split_strategy(dsts, change_dts, dust_policy.dust_threshold, splitted_dsts, dust_dsts);
for(auto& d: dust_dsts) {
THROW_WALLET_EXCEPTION_IF(dust_policy.dust_threshold < d.amount, error::wallet_internal_error, "invalid dust value: dust = " +
std::to_string(d.amount) + ", dust_threshold = " + std::to_string(dust_policy.dust_threshold));
}
for(auto& d: dust_dsts) {
if (!dust_policy.add_to_fee)
splitted_dsts.push_back(cryptonote::tx_destination_entry(d.amount, dust_policy.addr_for_dust));
dust += d.amount;
}
crypto::secret_key tx_key;
bool r = cryptonote::construct_tx_and_get_tx_key(m_account.get_keys(), sources, splitted_dsts, extra, tx, unlock_time, tx_key);
THROW_WALLET_EXCEPTION_IF(!r, error::tx_not_constructed, sources, splitted_dsts, unlock_time, m_testnet);
THROW_WALLET_EXCEPTION_IF(upper_transaction_size_limit <= get_object_blobsize(tx), error::tx_too_big, tx, upper_transaction_size_limit);
std::string key_images;
bool all_are_txin_to_key = std::all_of(tx.vin.begin(), tx.vin.end(), [&](const txin_v& s_e) -> bool
{
CHECKED_GET_SPECIFIC_VARIANT(s_e, const txin_to_key, in, false);
key_images += boost::to_string(in.k_image) + " ";
return true;
});
THROW_WALLET_EXCEPTION_IF(!all_are_txin_to_key, error::unexpected_txin_type, tx);
bool dust_sent_elsewhere = (dust_policy.addr_for_dust.m_view_public_key != change_dts.addr.m_view_public_key
|| dust_policy.addr_for_dust.m_spend_public_key != change_dts.addr.m_spend_public_key);
if (dust_policy.add_to_fee || dust_sent_elsewhere) change_dts.amount -= dust;
ptx.key_images = key_images;
ptx.fee = (dust_policy.add_to_fee ? fee+dust : fee);
ptx.dust = ((dust_policy.add_to_fee || dust_sent_elsewhere) ? dust : 0);
ptx.dust_added_to_fee = dust_policy.add_to_fee;
ptx.tx = tx;
ptx.change_dts = change_dts;
ptx.selected_transfers = selected_transfers;
ptx.tx_key = tx_key;
ptx.dests = dsts;
ptx.construction_data.sources = sources;
ptx.construction_data.change_dts = change_dts;
ptx.construction_data.splitted_dsts = splitted_dsts;
ptx.construction_data.selected_transfers = selected_transfers;
ptx.construction_data.extra = tx.extra;
ptx.construction_data.unlock_time = unlock_time;
ptx.construction_data.use_rct = false;
ptx.construction_data.dests = dsts;
}
}
| [
"valiant1x@users.noreply.github.com"
] | valiant1x@users.noreply.github.com |
05ad101c9d8c202f845158287e96c22fbe7d0194 | b1ab61c6d376b8bdae6c838cfb3fd6c5153ad4e3 | /Headers/H_Trade_Entry.h | 6e0cc6f895cd6507c2dac11c06f4e08600e34243 | [] | no_license | Rahul-Ravindran-Official/Master-Insight-Trading-Bot | 09d1d5b57d899fcce8940abc9f36ac4776154632 | 4c01020bc3a9abcc13881ceadfb5df34b4708305 | refs/heads/master | 2020-12-28T00:43:19.681644 | 2020-02-05T20:40:18 | 2020-02-05T20:40:18 | 238,124,489 | 2 | 0 | null | 2020-02-05T20:40:20 | 2020-02-04T04:40:32 | C++ | UTF-8 | C++ | false | false | 462 | h | //
// Created by Rahul Ravindran on 01-02-2020.
//
#include "../Enums/E_BBHSS.cpp"
#include "../Enums/E_BHS.cpp"
#include "../Structs/S_Order.cpp"
class H_Trade_Entry{
public:
virtual S_Order monitor(float tick) = 0;
private:
virtual E_BBHSS potential_trade_entry_detector(float tick) = 0;
virtual E_BHS potential_trade_entry_validator(E_BBHSS strength) = 0;
virtual S_Order trade_risk_setter(E_BHS order_type) = 0;
}; | [
"rahulravindran.in@gmail.com"
] | rahulravindran.in@gmail.com |
ff440905568b363158b9f3a4b0a479b5fd8d33c8 | 23c524e47a96829d3b8e0aa6792fd40a20f3dd41 | /.history/vector/Vector_20210423221625.hpp | 197b3f4ba81c64c8e147d1906cce7f363a5402eb | [] | no_license | nqqw/ft_containers | 4c16d32fb209aea2ce39e7ec25d7f6648aed92e8 | f043cf52059c7accd0cef7bffcaef0f6cb2c126b | refs/heads/master | 2023-06-25T16:08:19.762870 | 2021-07-23T17:28:09 | 2021-07-23T17:28:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,675 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Vector.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dbliss <dbliss@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/29 19:04:34 by dbliss #+# #+# */
/* Updated: 2021/04/23 17:3 by dbliss ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef VECTOR_HPP
#define VECTOR_HPP
#include <iostream>
#include <memory>
#include <algorithm>
#include "Iterator.hpp"
#include "Algorithm.hpp"
#include "Identifiers.hpp"
#include "stddef.h"
namespace ft
{
template <class T, class Alloc = std::allocator<T> >
class vector
{
public:
typedef T value_type;
typedef Alloc allocator_type;
typedef typename Alloc::reference reference;
typedef typename Alloc::const_reference const_reference;
typedef typename Alloc::pointer pointer;
typedef typename Alloc::const_pointer const_pointer;
typedef ft::myIterator<pointer> iterator;
typedef ft::myIterator<const_pointer> const_iterator;
typedef ft::myReverse_iterator<iterator> reverse_iterator;
typedef ft::myReverse_iterator<const_iterator> const_reverse_iterator;
typedef ptrdiff_t difference_type;
typedef size_t size_type;
/* 4 CONSTRUCTORS: */
// #1: default constructor
explicit vector(const allocator_type &alloc = allocator_type()) : _allocator_type(alloc), _capacity(NULL), _v_begin(NULL), _v_end(NULL) {}
// #2: fill constructor: constructs a container with n elements. Each element is a copy of val.
explicit vector(size_type n, const value_type &val = value_type(),
const allocator_type &alloc = allocator_type()) : _allocator_type(alloc), _capacity(NULL), _v_begin(NULL), _v_end(NULL)
{
if (n)
assign(n, val);
}
/* #3: Constructs a container with as many elements as the range [first,last),
with each element constructed from its corresponding element in that range, in the same order. */
template <class InputIterator>
vector(InputIterator first, InputIterator last, typename ft::enable_if<!is_integral<InputIterator>::value> * = NULL, const allocator_type &alloc = allocator_type()) : _allocator_type(alloc), _capacity(NULL), _v_begin(NULL), _v_end(NULL)
{
assign(first, last);
}
//#4: copy constructor: */
vector(const vector &src) : _v_begin(NULL), _v_end(NULL), _capacity(NULL), _allocator_type(src._allocator_type)
{
//assign(src.begin(), src.end());
//operator =(src);
}
/* DESTRUCTOR */
~vector()
{
if (this->_v_begin)
{
clear();
this->_allocator_type.deallocate(this->_v_begin, capacity());
this->_v_begin = NULL;
this->_v_end = NULL;
this->_capacity = NULL;
}
}
/*ASSIGNMENT OPERATOR*/
vector &operator=(vector const &x)
{
if (x == *this)
return (*this);
this->clear();
this->insert(this->end(), x.begin(), x.end());
return (*this);
}
/* ITERATORS */
iterator begin() { return (iterator(&(front()))); } // тут мы получаем ссылку из указателя (фронт возвращает указатель, и подставляем в конструктор)
iterator end() { return iterator(&(back()) + 1); } // Unlike member vector::end, which returns an iterator just past this element, this function returns a direct reference, поэтому +1
const_iterator begin() const { return const_iterator(&(front())); }
const_iterator end() const { return const_iterator(&(back()) + 1); }
reverse_iterator rbegin()
{
return reverse_iterator(end());
}
reverse_iterator rend()
{
return reverse_iterator(begin());
}
const_reverse_iterator rbegin() const
{
return const_reverse_iterator(end());
}
const_reverse_iterator rend() const
{
return const_reverse_iterator(begin());
}
/* CAPACITY */
size_type size() const { return static_cast<size_type>(this->_v_end - this->_v_begin); }
size_t max_size(void) const
{
return this->_allocator_type.max_size();
}
// Resizes the container so that it contains n elements.
void resize(size_type n, value_type val = value_type())
{
size_type v_size = size();
if (n < v_size)
{
erase(begin() + n, end());
}
else if (v_size < n)
{
size_type offset;
offset = n - v_size;
insert(end(), offset, val);
}
}
size_type capacity() const
{
return static_cast<size_type>(this->_capacity - this->_v_begin);
}
bool empty() const
{
if (size() == 0)
return true;
else
return false;
}
void reserve(size_type n)
{
// If n is greater than the current vector capacity,
// the function causes the container to reallocate its storage increasing its capacity to n (or greater).
if (n < capacity())
return;
if (n > capacity())
{
pointer old_begin = this->_v_begin;
pointer old_end = this->_v_end;
size_type old_capacity = capacity();
pointer array = _allocator_type.allocate(n); // allocate enough space for n objects
this->_v_end = array;
while (this->_v_begin != old_end) // copy all previous content to the new array
{
_allocator_type.construct(this->_v_end, *(this->_v_begin)); // construct objects
this->_v_end++;
this->_v_begin++;
}
_allocator_type.deallocate(old_begin, old_capacity);
this->_v_begin = array;
this->_capacity = this->_v_begin + n; // extend the capacity ??? //check this
}
}
/* ELEMENT ACCESS */
reference operator[](size_type n)
{
return this->_v_begin[n];
}
const_reference operator[](size_type n) const
{
return this->_v_begin[n];
}
reference at(size_type n)
{
if (n < 0 || n > size())
throw(std::out_of_range("error: std::out_of_range"));
return (this->_v_begin[n]);
}
const_reference at(size_type n) const
{
if (n < 0 || n > size())
throw(std::out_of_range("error: std::out_of_range"));
return this->_v_begin[n];
}
reference front() { return *(this->_v_begin); }
const_reference front() const { return *(this->_v_begin); }
reference back() { return *(this->_v_end - 1); }
const_reference back() const { return *(this->_v_end - 1); }
/* MODIFIERS */
template <class InputIterator>
void assign(InputIterator first, InputIterator last, typename ft::enable_if<!is_integral<InputIterator>::value, InputIterator>::type isIterator = InputIterator())
{
(void)isIterator;
clear();
insert(begin(), first, last);
}
void assign(size_type n, const value_type &val)
{
clear();
insert(begin(), n, val);
}
// Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.
// If size < capacity, a push_back simply puts the new element at the end and increments the size by 1.
void push_back(const value_type &val)
{
if (this->_v_end == this->_capacity)
{
size_type reserve_cap = capacity();
reserve(2 * reserve_cap + 1);
}
_allocator_type.construct(this->_v_end, val);
this->_v_end++;
}
// Removes the last element in the vector, effectively reducing the container size by one.
// If the container is not empty, the function never throws exceptions (no-throw guarantee).
// Otherwise, it causes undefined behavior.
void pop_back()
{
this->_allocator_type.destroy(&back());
this->_v_end--;
}
void insert(iterator position, size_type n, const value_type &val)
{
size_type len = /*static_cast<size_type>*/ (&(*position)) - this->_v_begin;
if (capacity() >= n + size())
{
for (size_type i = 0; i < size() - len; i++) // size - len it's the nums of elem aftern n to move
this->_allocator_type.construct(this->_v_end - i + (n - 1), *(this->_v_end - i - 1));
//this->_allocator_type.construct(&(*position) + n + i, *(position + i)); // moving the rest of the array after 'n' to new positions
this->_v_end += n;
while (n != 0)
{
this->_allocator_type.construct(&(*position) + (n - 1), val); // filling from the "end"
n--;
}
}
else
{
reserve(size() * 2 + n);
for (size_type i = 0; i < this->size() - len; i++)
this->_allocator_type.construct(this->_v_end - i + (n - 1), *(this->_v_end - i - 1)); // creating elements followed after the inserted elements
this->_v_end += n;
size_type i = len;
for (int j = 0; j < n; j++, i++)
{
this->_allocator_type.construct(this->_v_begin + i, val); // creating the inserted elements
}
}
}
iterator insert(iterator position, const value_type &val)
{
difference_type offset = position - begin();
insert(position, 1, val);
return (iterator(begin() + offset));
}
template <class InputIterator>
void insert(iterator position, InputIterator first, InputIterator last, typename ft::enable_if<!is_integral<InputIterator>::value, InputIterator>::type isIterator = InputIterator())
{
(void)isIterator;
size_type len = /*static_cast<size_type>*/ (&(*position)) - this->_v_begin;
difference_type diff = ft::distance(first, last);
if (capacity() >= diff + size())
{
for (size_type i = 0; i < size() - len; i++)
this->_allocator_type.construct(this->_v_end - i + (diff - 1), *(this->_v_end - i - 1)); // moving the rest of the array after 'n' to new positions
this->_v_end += diff;
for (int i = 0; i < diff; ++i)
{
this->_allocator_type.construct(&(*position) + i, *first);
first++;
}
}
else
{
reserve(size() * 2 + diff);
for (size_type i = 0; i < this->size() - len; i++)
this->_allocator_type.construct(this->_v_end - i + (diff - 1), *(this->_v_end - i - 1)); // creating elements followed after the inserted elements
this->_v_end += diff;
size_type i = len;
for (int j = 0; j < diff; j++, i++, first++)
{
this->_allocator_type.construct(this->_v_begin + i, *first); // creating the inserted elements
}
}
}
iterator erase(iterator position) // returns iterator of the end
{
pointer ptr_pos = &(*position);
this->_allocator_type.destroy(&(*position));
//if (ptr_pos + 1 == this->_v_end - 1)
//this->_allocator_type.destroy(ptr_pos);
for (int i = 0; i < this->_v_end - ptr_pos - 1; i++)
{
this->_allocator_type.construct(ptr_pos + i, *(ptr_pos + i + 1)); // put the right side of the array to the place pointed by the destroyed element;
this->_allocator_type.destroy(ptr_pos + i + 1); // destroy the duplicate
}
this->_v_end--;
return (iterator(ptr_pos));
}
iterator erase(iterator first, iterator last) // returns iterator to the place of the first erased element
{
pointer ptr_first = &(*first);
pointer ptr_last = &(*last);
while (&(*first) != &(*last))
{
this->_allocator_type.destroy(&(*first)); // delete the ranged elements
first++;
}
for (int i = 0; i < this->_v_end - ptr_last; i++)
{
this->_allocator_type.construct(ptr_first + i, *(ptr_last + i)); // copy the contents of the array to the place of deleted elements
this->_allocator_type.destroy(ptr_last + i); // destroy the copied element
}
this->_v_end -= ptr_last - ptr_first;
return (iterator(ptr_first));
}
void swap(vector &x)
{
if (this == &x)
return;
ft::swap(this->_v_begin, x._v_begin);
ft::swap(this->_v_end, x._v_end);
ft::swap(this->_capacity, x._capacity);
}
void clear()
{
size_type v_size = size();
for (size_type i = 0; i < v_size; i++)
{
this->_allocator_type.destroy(this->_v_end--);
}
}
private:
pointer _capacity;
pointer _v_begin;
pointer _v_end;
allocator_type _allocator_type;
};
/* NON-MEMBER FUNCTION OVERLOADS: */
/* RELATIONAL OPERATORS */
/* The equality comparison (operator==) is performed by first comparing sizes, and if they match,
** the elements are compared sequentially using operator==,
** stopping at the first mismatch (as if using algorithm equal).
*/
template <class T, class Alloc>
bool operator==(const vector<T, Alloc> &lhs, const vector<T, Alloc> &rhs)
{
return (lhs.size() == rhs.size() && ft::equal(lhs.begin(), lhs.end(), rhs.begin()));
}
template <class T, class Alloc>
bool operator!=(const vector<T, Alloc> &lhs, const vector<T, Alloc> &rhs)
{
return !(lhs == rhs);
}
template <class T, class Alloc>
bool operator<(const vector<T, Alloc> &lhs, const vector<T, Alloc> &rhs)
{
return ft::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
// a<=b equivalent !(b<a)
template <class T, class Alloc>
bool operator<=(const vector<T, Alloc> &lhs, const vector<T, Alloc> &rhs)
{
return !(rhs < lhs);
}
// a>b equivalent to b<a
template <class T, class Alloc>
bool operator>(const vector<T, Alloc> &lhs, const vector<T, Alloc> &rhs)
{
return (rhs < lhs);
}
// a>=b equivalent !(a<b)
template <class T, class Alloc>
bool operator>=(const vector<T, Alloc> &lhs, const vector<T, Alloc> &rhs)
{
return !(lhs < rhs);
}
/* SWAP */
template <class T, class Alloc>
void swap(vector<T, Alloc> &x, vector<T, Alloc> &y)
{
x.swap(y);
}
}
#endif /* ***************************************************** MUTANTSTACK_H */ | [
"dbliss@at-q1.msk.21-school.ru"
] | dbliss@at-q1.msk.21-school.ru |
6aef364003e10c5c3e4fdb9dcae2f41a7515ca29 | 641abcbcdd3c1860905454ae5183947de94ef589 | /2018/Jiaozi-new/src/privatepay-relay.h | 76a5db356478a6e39041f426302263011ca69f82 | [
"BSD-3-Clause",
"MIT"
] | permissive | playgamelxh/lxh | 703965e4741bea76b16bd01882f8268b0e36d824 | f4abb2a7c03ff0da68091ce12a930c0b505856bc | refs/heads/master | 2020-04-05T14:01:09.227380 | 2019-12-30T02:20:22 | 2019-12-30T02:20:22 | 30,052,695 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,329 | h |
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2017 The OIOCoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef PRIVATEPAY_RELAY_H
#define PRIVATEPAY_RELAY_H
#include "validation.h"
#include "activemasternode.h"
#include "masternodeman.h"
class CPrivatePayRelay
{
public:
CTxIn vinMasternode;
vector<unsigned char> vchSig;
vector<unsigned char> vchSig2;
int nBlockHeight;
int nRelayType;
CTxIn in;
CTxOut out;
CPrivatePayRelay();
CPrivatePayRelay(CTxIn& vinMasternodeIn, vector<unsigned char>& vchSigIn, int nBlockHeightIn, int nRelayTypeIn, CTxIn& in2, CTxOut& out2);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(vinMasternode);
READWRITE(vchSig);
READWRITE(vchSig2);
READWRITE(nBlockHeight);
READWRITE(nRelayType);
READWRITE(in);
READWRITE(out);
}
std::string ToString();
bool Sign(std::string strSharedKey);
bool VerifyMessage(std::string strSharedKey);
void Relay();
void RelayThroughNode(int nRank);
};
#endif
| [
"419006096@qq.com"
] | 419006096@qq.com |
c05973bbb0b53ce1104d6057e80dd13122c59623 | 07f1b6912cc38d41f73eddb27ee21590e7cb6b1a | /Projet1/Entity.h | 431a6ea093aa1c54926d42d4d8330a6a906be2ea | [] | no_license | drakkath3000/jeuVideo | 5a8ea5fba07356e12f31bfe54e48d4a9c2eda770 | c42e5d4f02f30e1caee2d72cda54dd8e9d808381 | refs/heads/master | 2020-09-13T11:21:02.470355 | 2019-11-18T15:46:00 | 2019-11-18T15:46:00 | 222,759,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | h | #pragma once
#include "EntityAnimated.h"
#include "EntityBrain.h"
#include "EntityPhysic.h"
class Action;
class Entity :
public EntityAnimated,
public EntityBrain,
public EntityPhysic
{
public:
Entity();
~Entity();
void setPosition(const sf::Vector2f& pos);
void setPosition(const int& x, const int& y);
void Update();
void MoveOnHitBox();
protected:
sf::RectangleShape* body;
};
| [
"PerBr0430009@etu.cegepjonquiere.ca"
] | PerBr0430009@etu.cegepjonquiere.ca |
45818b4429df0cebe4e6df76481e4c459a8e7ada | 5ebd5cee801215bc3302fca26dbe534e6992c086 | /blazetest/src/mathtest/dvecdvecmax/VHbVUb.cpp | a194bfda8080f2ec2d94bb8822b3ead72dbd71e5 | [
"BSD-3-Clause"
] | permissive | mhochsteger/blaze | c66d8cf179deeab4f5bd692001cc917fe23e1811 | fd397e60717c4870d942055496d5b484beac9f1a | refs/heads/master | 2020-09-17T01:56:48.483627 | 2019-11-20T05:40:29 | 2019-11-20T05:41:35 | 223,951,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,973 | cpp | //=================================================================================================
/*!
// \file src/mathtest/dvecdvecmax/VHbVUb.cpp
// \brief Source file for the VHbVUb dense vector/dense vector maximum math test
//
// Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/HybridVector.h>
#include <blaze/math/UniformVector.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dvecdvecmax/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'VHbVUb'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Vector type definitions
using VHb = blaze::HybridVector<TypeB,128UL>;
using VUb = blaze::UniformVector<TypeB>;
// Creator type definitions
using CVHb = blazetest::Creator<VHb>;
using CVUb = blazetest::Creator<VUb>;
// Running tests with small vectors
for( size_t i=0UL; i<=6UL; ++i ) {
RUN_DVECDVECMAX_OPERATION_TEST( CVHb( i ), CVUb( i ) );
}
// Running tests with large vectors
RUN_DVECDVECMAX_OPERATION_TEST( CVHb( 127UL ), CVUb( 127UL ) );
RUN_DVECDVECMAX_OPERATION_TEST( CVHb( 128UL ), CVUb( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector maximum:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
c28a08fafbe4787e159c6fe0f2b64875af4dca63 | eaaaf8964ea65292c2fb0498eb4c3d73f3b6186c | /OPENGL/OpenGL_3DJV1/Triangle02/Triangle02.cpp | 1843f508e43bc6668f5b85780400c18463b50872 | [] | no_license | VisualPi/ESGI_COURS_VISUALPI | 1c2ae02913c93ba43cf57e6eca1a19a0a69cf72f | 71a8bd664bc3d9fb4aaa1f9ec289f965d50abe72 | refs/heads/master | 2021-01-10T14:31:32.983105 | 2016-02-08T14:47:46 | 2016-02-08T14:47:46 | 44,498,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,594 | cpp | // Triangle01.cpp : Defines the entry point for the console application.
//
// Specifique a Windows
#if _WIN32
#include <Windows.h>
#define FREEGLUT_LIB_PRAGMAS 0
#pragma comment(lib, "freeglut.lib")
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glew32s.lib")
#endif
// Entete OpenGL
#define GLEW_STATIC 1
#include <GL/glew.h>
//#include <gl/GL.h>
//#include "GL/glext.h"
// FreeGLUT
#include "GL/freeglut.h"
#include <cstdio>
#include <cmath>
#include "../common/EsgiShader.h"
EsgiShader basicShader;
GLuint triangleVBO;
void Initialize()
{
printf("Version Pilote OpenGL : %s\n", glGetString(GL_VERSION));
printf("Type de GPU : %s\n", glGetString(GL_RENDERER));
printf("Fabricant : %s\n", glGetString(GL_VENDOR));
printf("Version GLSL : %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
int numExtensions;
glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
GLenum error = glewInit();
if (error != GL_NO_ERROR) {
// TODO
}
for (int index = 0; index < numExtensions; ++index)
{
printf("Extension[%d] : %s\n", index, glGetStringi(GL_EXTENSIONS, index));
}
basicShader.LoadVertexShader("basic.vs");
basicShader.LoadFragmentShader("basic.fs");
basicShader.Create();
static const float g_Triangle[] = {
-0.8f, 0.8f, 1.0f,
0.0f, -0.8f, 0.5f,
0.8f, 0.8f, 0.0f
};
glGenBuffers(1, &triangleVBO);
glBindBuffer(GL_ARRAY_BUFFER, triangleVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*9, g_Triangle, GL_STATIC_DRAW);
//glBufferData(GL_ARRAY_BUFFER, sizeof(float)*9, nullptr, GL_STATIC_DRAW);
//glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(float)*9, g_Triangle);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void Terminate()
{
glDeleteBuffers(1, &triangleVBO);
basicShader.Destroy();
}
void Render()
{
glViewport(0, 0, glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT));
glClearColor(0.f, 0.5f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
GLuint program = basicShader.GetProgram();
glUseProgram(program);
glBindBuffer(GL_ARRAY_BUFFER, triangleVBO);
GLint positionLocation = glGetAttribLocation(program, "a_position");
glVertexAttribPointer(positionLocation, 2, GL_FLOAT, GL_FALSE,3*sizeof(float), 0);
glEnableVertexAttribArray(positionLocation);
GLint intensityLocation = glGetAttribLocation(program, "a_intensity");
glVertexAttribPointer(intensityLocation, 1, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void*)(2*sizeof(float)));
glEnableVertexAttribArray(intensityLocation);
// variables uniformes (constantes) durant le rendu de la primitive
GLint offsetLocation = glGetUniformLocation(program, "u_offset");
glUniform3f(offsetLocation, 0.0f, 0.0f, 0.0f);
GLint colorLocation = glGetUniformLocation(program, "u_constantColor");
glUniform4f(colorLocation, 1.0f, 0.0f, 0.0f, 1.0f);
glDrawArrays(GL_TRIANGLES, 0, 3);
static float time = 1.f;
time += 1.f/100.f;
glUniform3f(offsetLocation, cos(time), sin(time), 0.0f);
glUniform4f(colorLocation, 1.0f, 1.0f, 0.0f, 1.0f);
glDrawArrays(GL_TRIANGLES, 0, 3);
glUseProgram(0);
glutSwapBuffers();
glutPostRedisplay();
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutInitWindowSize(800, 600);
glutCreateWindow("Basic");
#ifdef FREEGLUT
// Note: glutSetOption n'est disponible qu'avec freeGLUT
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE,
GLUT_ACTION_GLUTMAINLOOP_RETURNS);
#endif
Initialize();
glutDisplayFunc(Render);
glutMainLoop();
Terminate();
return 0;
}
| [
"gintakun2@yahoo.fr"
] | gintakun2@yahoo.fr |
086b7e3f72bb54ac4faa286532a9b8ce1fef6fd5 | 46408972a5747f8ee8188f6ada10e3dd903edac0 | /map/Map.cpp | d5b3173da08a146f659210e89ab2e28625334e36 | [] | no_license | GuJun1990/DXF | efa27ea412dc05a7d288e8430b3b03ffdf91910c | b729e4e75f0ede09251714d14d0ccbfe1dbd6909 | refs/heads/master | 2021-03-11T01:23:49.315605 | 2020-03-11T09:52:34 | 2020-03-11T09:52:34 | 246,501,530 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 58 | cpp | //
// Created by GuJun on 2020/3/11.
//
#include "Map.h"
| [
"gujun@qiyi.com"
] | gujun@qiyi.com |
1885a5c4b383ba3e2b9dd23acbc75384c7ee1ea0 | 9d5a083813193f4eba906658a1d2ce75b3e6b927 | /tinyweb/LINEDRAW/C_VERS~1.CPP | bbe9d0880e419a698dcc6798176344d979708a9d | [
"MIT"
] | permissive | j-pel/tinyedit | 253e9ac337fb3d99e5b4afab9bc25e14b2d47fb0 | 87037f19cbaed118c4f04fb278640c5f6053b45a | refs/heads/master | 2021-05-24T15:29:42.286753 | 2020-04-07T05:38:46 | 2020-04-07T05:38:46 | 253,630,535 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,213 | cpp | ///////////////////////////////////////////////////////////////////////////////
// DrawBresenhamLine()
//
// Description:
// Routine to draw a line on the given surface from x1, y1 to x2, y2
// with the given R, G, and B color components. Uses the Bresenham
// algorithm for the line.
//
// Input:
// - Buffer to draw on
// - Pitch of a line (in dwords per line)
// - X1, Y1 and X2, Y2 Coordinates
// - Red, Green, and Blue color components
//
// Output:
// - N/A
//
// Speed:
// - Random Seed of 100
// - 300,000 Lines
// - 5.810 Seconds
// - 51,635 lines per second
//
// - Drawing a line from (0, 0) - (799, 599)
// - Is 1K pixels per line
// - Runs around 17,000 lines per second
// - Total of 17,000,000 pixels per second
//
///////////////////////////////////////////////////////////////////////////////
void DrawBresenhamLine(void* buffer, int pitch, int x1, int y1, int x2, int y2,
Uint8 R, Uint8 G, Uint8 B)
{
int x, y;
int index;
int dx, dy;
int incx, incy;
int iErrorTerm;
DWORD* pBuffer = (DWORD*)buffer;
DWORD color;
// We are always going to draw top to bottom so swap things if needed
if( y1 > y2 )
{
int Temp = y1;
y1 = y2;
y2 = Temp;
Temp = x1;
x1 = x2;
x2 = x1;
}
// Is our X Axis moving in a positive direction?
if( x2 >= x1 )
{
// Yes, we are going positive so calculate
// the distance and set the X increment to be
// a positive 1
dx = x2 - x1;
incx = 1;
}
else
{
// No, we are going negative so calculate
// the distance and set the X increment to be
// a negative 1
dx = x1 - x2;
incx = -1;
}
// Since the Y is always positive we can just
// calc the distance and set the Y increment to be
// a positive 1
dy = y2 - y1;
incy = 1;
// Set the current X and Y coordinate to the start
// of the line specified
x = x1;
y = y1;
// Set our starting point for the buffer
pBuffer = (DWORD*)buffer + (y * pitch) + x;
// Compute the color we will use
color = (R << 16 | G << 8 | B);
// Special case the horixontal, vertical, and diagonal lines
// since they don't need "normal calculations"
// Is the line vertical?
if( dx == 0 )
{
// The line is vertical
for(index = 0; index <= dy; index++)
{
// Draw the pixel at the current location
*pBuffer = color;
// Move down one line
pBuffer += pitch;
}
// Done drawing
return;
}
// Is the line horizontal?
if( dy == 0 )
{
// The line is horizontal
for(index = 0; index <= dx; index++)
{
// Draw the pixel at the current location
*pBuffer = color;
// Move to the next pixel on this line
pBuffer += incx;
}
// Done drawing
return;
}
// Is this line diagonal
if( dx == dy )
{
// The line is diagonal
for(index = 0; index <= dx; index++)
{
// Draw the pixel at the current location
*pBuffer = color;
// Move down one line and over by the x increment
pBuffer += (pitch + incx);
}
// Done drawing
return;
}
// Is this an X major or Y major line?
if( dx >= dy )
{
// The line is X Major
// Scale the Y length up by a factor of 2
// Compute the starting ErrorTerm
// Then scale the X length up by a factor of 2
dy <<= 1;
iErrorTerm = dy - dx;
dx <<= 1;
// Loop until we reach the end of the X axis
while( x != x2 )
{
// Draw the pixel at the current location
*pBuffer = color;
// Does our ErrorTerm indicate we need to move to
// the next pixel on our minor axis (the Y axis)?
if( iErrorTerm >= 0 )
{
// Move to the next Y line in the buffer
pBuffer += pitch;
// Adjust the error term back down again
iErrorTerm -= dx;
}
// Add another Y delta on since we moved a pixel
// along the X axis
iErrorTerm += dy;
// Move to the next coordinate along the X axis
x += incx;
pBuffer += incx;
}
// Draw the pixel at the final location
*pBuffer = color;
}
else
{
// The line is Y major
// Scale the X length up by a factor of 2
// Compute the starting ErrorTerm
// Then scale the Y length up by a factor of 2
dx <<= 1;
iErrorTerm = dx - dy;
dy <<= 1;
// Loop until we reach the end of the Y axis
while( y != y2 )
{
// Draw a pixel at the current location
*pBuffer = color;
// Does our ErrorTerm indicate we need to move to
// the next pixel on our minor axis (the X axis)?
if( iErrorTerm >= 0 )
{
// Move to the next X coordinate in the buffer
pBuffer += incx;
// Adjust the error term back down again
iErrorTerm -= dy;
}
// Add another X delta on since we moved a pixel
// along the Y axis
iErrorTerm += dx;
// Move to the next coordinate along the Y axis
y += incy;
pBuffer += pitch;
}
// Draw the pixel at the final location
*pBuffer = color;
}
// Done drawing
return;
}
///////////////////////////////////////////////////////////////////////////////
// END DrawBresenhamLine()
///////////////////////////////////////////////////////////////////////////////
| [
"jmpelaez@gmail.com"
] | jmpelaez@gmail.com |
f76fc3da5656358c84946306f7054092c2916b5d | d0bdb9ec3508f7d20d8f442838a2b41e29839b8b | /packages/Adapters/Moab/src/DTK_MoabEntityIterator.hpp | 6d090d2f4c22b2e16c48561b88cb7da8145665ca | [] | no_license | vijaysm/DataTransferKit | e8f8fb42608fcc70476d97b0cbb6cbfff684f835 | 1564b068e8ac012478f0c244a2ca132ea7a89c1f | refs/heads/master | 2021-01-17T20:14:36.362260 | 2015-03-27T18:47:39 | 2015-03-27T18:47:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,902 | hpp | //---------------------------------------------------------------------------//
/*
Copyright (c) 2012, Stuart R. Slattery
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 University of Wisconsin - Madison 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.
*/
//---------------------------------------------------------------------------//
/*!
* \brief DTK_MoabEntityIterator.hpp
* \author Stuart R. Slattery
* \brief Entity iterator interface.
*/
//---------------------------------------------------------------------------//
#ifndef DTK_MOABENTITYITERATOR_HPP
#define DTK_MOABENTITYITERATOR_HPP
#include <vector>
#include <functional>
#include "DTK_EntityIterator.hpp"
#include "DTK_Entity.hpp"
#include "DTK_MoabEntityIteratorRange.hpp"
#include "DTK_MoabMeshSetIndexer.hpp"
#include <Teuchos_RCP.hpp>
#include <Teuchos_Ptr.hpp>
#include <MBParallelComm.hpp>
namespace DataTransferKit
{
//---------------------------------------------------------------------------//
/*!
\class MoabEntityIterator
\brief Moab mesh entity iterator implementation.
*/
//---------------------------------------------------------------------------//
class MoabEntityIterator : public EntityIterator
{
public:
/*!
* \brief Default constructor.
*/
MoabEntityIterator();
/*!
* \brief Constructor.
*/
MoabEntityIterator(
const Teuchos::RCP<MoabEntityIteratorRange>& entity_range,
const Teuchos::Ptr<moab::ParallelComm>& moab_mesh,
const Teuchos::Ptr<MoabMeshSetIndexer>& set_indexer,
const PredicateFunction& predicate );
/*!
* \brief Copy constructor.
*/
MoabEntityIterator( const MoabEntityIterator& rhs );
/*!
* \brief Destructor.
*/
~MoabEntityIterator();
/*!
* \brief Assignment operator.
*/
MoabEntityIterator& operator=( const MoabEntityIterator& rhs );
// Pre-increment operator.
EntityIterator& operator++() override;
// Dereference operator.
Entity& operator*(void) override;
// Dereference operator.
Entity* operator->(void) override;
// Equal comparison operator.
bool operator==( const EntityIterator& rhs ) const override;
// Not equal comparison operator.
bool operator!=( const EntityIterator& rhs ) const override;
// An iterator assigned to the first valid element in the iterator.
EntityIterator begin() const override;
// An iterator assigned to the end of all elements under the iterator.
EntityIterator end() const override;
// Create a clone of the iterator. We need this for the copy constructor
// and assignment operator to pass along the underlying implementation.
EntityIterator* clone() const override;
private:
// Range of entities over which the iterator is defined.
Teuchos::RCP<MoabEntityIteratorRange> d_entity_range;
// Iterator over the entities.
std::vector<moab::EntityHandle>::const_iterator d_moab_entity_it;
// The mesh owning the entities.
Teuchos::Ptr<moab::ParallelComm> d_moab_mesh;
// Mesh set indexer.
Teuchos::Ptr<MoabMeshSetIndexer> d_set_indexer;
// Current entity.
Entity d_current_entity;
};
//---------------------------------------------------------------------------//
} // end namespace DataTransferKit
#endif // end DTK_MOABENTITYITERATOR_HPP
//---------------------------------------------------------------------------//
// end DTK_MoabEntityIterator.hpp
//---------------------------------------------------------------------------//
| [
"sslattery617@gmail.com"
] | sslattery617@gmail.com |
b6680f669f6dc6c6042bd09eba3f67ad61a9bb1b | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/wget/hunk_254.cpp | 67c4de28737339d1387b6bc513eedbfc50ceb17c | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 696 | cpp | {
int type;
if (opt.private_key_type != opt.cert_type)
- {
- /* GnuTLS can't handle this */
- logprintf (LOG_NOTQUIET, _("ERROR: GnuTLS requires the key and the \
+ {
+ /* GnuTLS can't handle this */
+ logprintf (LOG_NOTQUIET, _("ERROR: GnuTLS requires the key and the \
cert to be of the same type.\n"));
- }
+ }
type = key_type_to_gnutls_type (opt.private_key_type);
gnutls_certificate_set_x509_key_file (credentials, opt.cert_file,
- opt.private_key,
- type);
+ opt.private_key,
+ type);
}
if (opt.ca_cert)
| [
"993273596@qq.com"
] | 993273596@qq.com |
7e33702b0e76b9b8fca1a9781fcead7b19d3f201 | 19865cda31b2a42fbb17ac4105e4a422a83342f6 | /BOJ/09000/9084_동전.cpp | 063de6908de0a8011355a7564f01041df721655b | [] | no_license | warmwhiten/PS | 0f19c3742b09ee966196fc4e25f4fd58070a0eb2 | a2a1d8952e6cb4f65cc0fede35d730a80af617ff | refs/heads/master | 2023-02-08T15:55:06.389594 | 2020-12-28T06:57:40 | 2020-12-28T06:57:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 898 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define FUP(i, a, b) for(int i = a; i <= b; i++)
#define FDOWN(i, a, b) for(int i = a; i >= b; i--)
#define MS(a, b) memset(a, b, sizeof(a))
#define ALL(v) v.begin(), v.end()
#define CIN(a) cin >> a;
#define CIN2(a, b) cin >> a >> b
#define CIN3(a, b, c) cin >> a >> b >> c
#define COUT(a) cout << a
#define COUT2(a, b) cout << a << ' ' << b
#define COUT3(a, b, c) cout << a << ' ' << b << ' ' << c
#define ENDL cout << '\n'
int dy[4] = { -1, 1, 0, 0 };
int dx[4] = { 0, 0, 1, -1 };
int T, N, coin[20], M, dp[10001];
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
CIN(T);
while (T--)
{
CIN(N);
FUP(i, 0, N - 1) CIN(coin[i]);
CIN(M);
MS(dp, 0);
dp[0] = 1;
FUP(i, 0, N - 1)
{
FUP(j, coin[i], M)
{
dp[j] += dp[j - coin[i]];
}
}
COUT(dp[M]);
ENDL;
}
return 0;
} | [
"gyuho965@gmail.com"
] | gyuho965@gmail.com |
1f16e1bf784424b64297fb648186a319970bf023 | 24c5c53b7275f70844548df6f7e315aca18fb23d | /encrypted-web-proxy-localserver/encrypted-web-proxy-localserver/stdafx.cpp | fd3918edfbdbbcbf1302ab39616f4d132211e318 | [] | no_license | luyy/enctrypted-web-proxy | 8032a0d2d977c000147e53a7bb744570c079fc79 | 72bf229b27d586a2b1aeb54fc1711fc2e711e822 | refs/heads/master | 2021-01-10T20:30:18.890439 | 2010-06-11T03:12:29 | 2010-06-11T03:12:29 | 32,114,327 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 291 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// encrypted-web-proxy-localserver.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
| [
"luyouyou87@7e48bea9-130a-f1ab-edc1-274fd046b959"
] | luyouyou87@7e48bea9-130a-f1ab-edc1-274fd046b959 |
28ad5c007e1cbb5171aa01ff58e23d907cdd6df7 | 602e0f4bae605f59d23688cab5ad10c21fc5a34f | /MyToolKit/GB28181Client/DllCataloginfoSession.h | f64c56b67cb8f256b8c10f5e38feebc9a6b851c8 | [] | no_license | yanbcxf/cpp | d7f26056d51f85254ae1dd2c4e8e459cfefb2fb6 | e059b02e7f1509918bbc346c555d42e8d06f4b8f | refs/heads/master | 2023-08-04T04:40:43.475657 | 2023-08-01T14:03:44 | 2023-08-01T14:03:44 | 172,408,660 | 8 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 393 | h | #pragma once
#include "abstractobject.h"
class CDllCataloginfoSession :
public CAbstractObject
{
public:
CDllCataloginfoSession(UsageEnvironment & environ, int nSerialNumber , string device_id);
~CDllCataloginfoSession(void);
string ObjectType() { return "CDllCataloginfoSession"; }
virtual void ProcessTimeout();
public :
int m_tid;
int m_nCurrentSumNum;
string m_device_id;
};
| [
"yangbin@star-net.cn"
] | yangbin@star-net.cn |
5af523fae25b1b7f37a618af8f61b32976307470 | 7f61157de79c6ac30f6314799423daf0a96624c9 | /Fissure/http/http.cpp | e2cad73d12422847b923becc6afeee1e93fe25b5 | [
"Apache-2.0"
] | permissive | all-in-one-of/lava | 046033d68ca7e1eec9be89173b889ab15a5e6c03 | 5a32647c7ebc2929a00ba13ee002dfac6986fc11 | refs/heads/master | 2020-07-08T13:54:57.575868 | 2019-08-30T09:25:44 | 2019-08-30T09:25:44 | 203,694,104 | 0 | 0 | Apache-2.0 | 2019-08-22T01:50:12 | 2019-08-22T01:50:12 | null | UTF-8 | C++ | false | false | 35,908 | cpp |
// -todo: use output to make a tbl that can be made into a const file that contains the directory to monitor and the window to refresh
// -todo: in the tbl possibly put the msg to send and the arguments in the input tbl as well
// -todo: use FindFirstChangeNotification and possibly WaitForSingleObject(m_dir, INFINITE); to monitor directory
// -todo: use FindWindow function to possibly find a web browser window
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define WIN32_EXTRA_LEAN
#define NOMINMAX
//#define _NO_CRT_STDIO_INLINE
#include <windows.h>
#include <winsock2.h>
#endif // WIN32
#define NO_RT_UTIL_IMPL
#define SQLITE_CONFIG_SINGLETHREAD 0
#include <iostream>
#include <fstream>
#include <algorithm>
#include "sqlite3.h"
#include "happyhttp.h"
#include "tinyxml2.h"
#include "json_fwd.hpp"
#include "json.hpp"
#include "../../no_rt_util.h"
#include "../../tbl.hpp"
#include "../../str_util.hpp"
#include "../LavaFlow.hpp"
#include "url_encode_decode.h"
using namespace tinyxml2;
using namespace nlohmann;
using abool = std::atomic<bool>;
using au32 = std::atomic<uint32_t>;
using au64 = std::atomic<uint64_t>;
enum Slots
{
IN_HTTP_URL = 0,
IN_XML_PARSE_TXT = 0,
IN_JSON_PARSE_ASCII = 0,
IN_JSON_KEYS = 1,
IN_WINMSG_MSG = 0,
IN_TBL_TO_STR_ASCII = 0,
IN_SQLLITE_PARAMS = 0,
OUT_HTTP_TXT = 0,
OUT_XML_PARSE_XML = 0,
OUT_WINMSG_STAT = 0,
OUT_JSON_PARSE_TBL = 0,
OUT_TBL_TO_STR_TXT = 0,
OUT_SQLLITE_RESULT = 0
};
struct SocketInit
{
SocketInit()
{
#ifdef _WIN32
WSAData wsaData;
int code = WSAStartup(MAKEWORD(1, 1), &wsaData);
if( code != 0 )
{
fprintf(stderr, "shite. %d\n",code);
//return 0;
}
#endif //WIN32
}
~SocketInit()
{
#ifdef _WIN32
WSACleanup();
#endif // WIN32
}
};
static int count = 0;
static int runCount = 0;
//#ifdef _WIN32
//
//static int winErr = 0;
//static au64 winHndl = 0;
//static au32 msg = 0;
//static au32 wParam = 0;
//static au32 lParam = 0;
//static au64 waitHndl = 0;
//static abool runCb = false;
//
//VOID CALLBACK cb_WaitOrTimerCallback(
// _In_ PVOID lpParameter,
// _In_ BOOLEAN TimerOrWaitFired
//)
//{
// if( !TimerOrWaitFired ){
// if( runCb.exchange(false) ){
// LRESULT ok = SendMessage( (HWND)(winHndl.load()), msg, wParam, lParam);
// printf("\n send message ok: %ld \n", (long)ok);
// }
// }
//}
//
//int (WINAPIV * __vsnprintf)(char *, size_t, const char*, va_list) = _vsnprintf;
//
//#endif
//#define GET_KEY(type, name, defaultVal) TYPE itemID = keys.has(#name)? (str)(tbl)keys(#name) : "";
namespace{
template<class... T> inline void
Print(LavaParams const* lp, const T&... args)
{
lp->lava_puts( toString(args ...).c_str() );
}
template<class... T> inline void
Println(LavaParams const* lp, const T&... args)
{
Print(lp, args ...);
lp->lava_puts("\n");
}
const char* headers[] =
{
"Connection", "close",
"Content-type", "application/x-www-form-urlencoded",
"Accept", "text/plain",
nullptr
};
class Vis : public tinyxml2::XMLVisitor
{
void printTxt(const char* label, const XMLText* txt)
{
printf("\n %s: %s \n", label, txt? txt->Value() : "NULL");
}
bool VisitEnter(const XMLElement& elem, const XMLAttribute* firstAttr)
{
printf("\n%s: %s \n", elem.Name(), elem.GetText()? elem.GetText() : "");
return true;
}
};
void OnBegin( const happyhttp::Response* r, void* tblPtr)
{
printf( "BEGIN (%d %s)\n", r->getstatus(), r->getreason() );
count = 0;
tbl* t = (tbl*)tblPtr;
}
void OnData( const happyhttp::Response* r, void* tblPtr, const unsigned char* data, int n )
{
fwrite( data,1,n, stdout );
count += n;
tbl* t = (tbl*)tblPtr;
t->push<i8>('\n');
// inefficient
TO(n,i)
t->push<i8>( data[i] );
}
void OnComplete( const happyhttp::Response* r, void* tblPtr)
{
printf( "COMPLETE (%d bytes)\n", count );
tbl* t = (tbl*)tblPtr;
}
void PrintElem(LavaParams const* lp, json::value_type& e)
{
using namespace std;
switch(e.type()){
case json::value_t::array:
case json::value_t::object:{
for(auto& ee : e){
PrintElem(lp, ee);
}
}break;
default:
str de = urldecode(toString(e));
lp->lava_puts( toString(de,"\n\n").c_str() );
lp->lava_puts( toString(e,"\n\n").c_str() );
break;
}
}
void ExtractKey(LavaParams const* lp, json::iterator& iter, tbl* keysTbl)
{
using namespace std;
auto val = iter.value();
switch(val.type()){
case json::value_t::number_float:
case json::value_t::number_integer:
case json::value_t::number_unsigned:
case json::value_t::boolean:
case json::value_t::string:{
str k = iter.key();
if( keysTbl->has(k.c_str()) )
{
switch(val.type()){
case json::value_t::number_float:{
(*keysTbl)(k.c_str()) = (f64)iter.value();
}break;
case json::value_t::number_integer:
case json::value_t::boolean:{
(*keysTbl)(k.c_str()) = (i64)iter.value();
}break;
case json::value_t::number_unsigned:{
(*keysTbl)(k.c_str()) = (u64)iter.value();
}break;
default: break;
}
str s = toString(iter.key(), ": ", iter.value(),"\n");
lp->lava_puts( s.c_str() );
}
}break;
case json::value_t::array:
case json::value_t::object:{
//for(auto& ee : e){
//ExtractKey(lp, ee, keysTbl);
for(auto it=val.begin(); it!=val.end(); ++it){
ExtractKey(lp, it, keysTbl);
}
}break;
default:
//str de = urldecode(toString(e));
//lp->lava_puts( toString(de,"\n\n").c_str() );
//
//lp->lava_puts( toString(e,"\n\n").c_str() );
break;
}
}
void ExtractKey(LavaParams const* lp, tbl* keysTbl, json& j)
{
for(auto it=j.begin(); it!=j.end(); ++it){
ExtractKey(lp, it, keysTbl);
}
}
str GetKey(tbl const& t, const char* key, str defaultVal="")
{
return t.has(key)? (str)(tbl)t(key) : defaultVal;
}
}
extern "C"
{
const char* TblToStr_InTypes[] = {"ASCII", nullptr}; // This array contains the type that each slot of the same index will accept as input.
const char* TblToStr_InNames[] = {"Raw Text", nullptr}; // This array contains the names of each input slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing.
const char* TblToStr_OutTypes[] = {"Text", nullptr}; // This array contains the types that are output in each slot of the same index
const char* TblToStr_OutNames[] = {"Text as Tbl", nullptr}; // This array contains the names of each output slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing.
uint64_t TblToStr(LavaParams const* lp, LavaFrame const* in, lava_threadQ* out) noexcept
{
auto inTxtPckt = in->packets[IN_TBL_TO_STR_ASCII];
tbl txt = LavaMakeTbl(lp, inTxtPckt.sz_bytes, (i8)0);
memcpy(txt.data<i8>(), (void*)inTxtPckt.val.value, inTxtPckt.sz_bytes);
out->push( LavaTblToOut(txt, OUT_TBL_TO_STR_TXT) );
return 0;
}
const char* http_InTypes[] = {"ASCII", nullptr}; // This array contains the type that each slot of the same index will accept as input.
const char* http_InNames[] = {"URL", nullptr}; // This array contains the names of each input slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing.
const char* http_OutTypes[] = {"ASCII", nullptr}; // This array contains the types that are output in each slot of the same index
const char* http_OutNames[] = {"txt", nullptr}; // This array contains the names of each output slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing.
uint64_t http(LavaParams const* lp, LavaFrame const* in, lava_threadQ* out) noexcept
{
using namespace std;
using namespace happyhttp;
str url = (str)LavaTblFromPckt(lp, in, IN_HTTP_URL);
SocketInit si; // inits windows sockets and on destruction cleans them up
auto addrSt = url.find("//") + 2;
auto pageSt = find( url.begin()+addrSt, url.end(), '/');
str addr(url.begin()+addrSt, pageSt);
str page(pageSt, url.end());
tbl response = LavaMakeTbl(lp, 0, (i8)0);
Connection cnct(addr.c_str(), 80);
cnct.connect();
cnct.setcallbacks(OnBegin, OnData, OnComplete, &response);
cnct.request("GET", page.c_str(), 0, 0, 0);
//fprintf(lp->lava_stdout, "\n");
while( cnct.outstanding() ){
lp->lava_puts(".");
cnct.pump();
nort_sleep(10);
}
//fprintf(lp->lava_stdout, "\n");
out->push( LavaTblToOut(response, OUT_HTTP_TXT) );
return 1;
}
const char* xml_parse_InTypes[] = {"txt", nullptr}; // This array contains the type that each slot of the same index will accept as input.
const char* xml_parse_InNames[] = {"XML Text", nullptr}; // This array contains the names of each input slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing.
const char* xml_parse_OutTypes[] = {"XML", nullptr}; // This array contains the types that are output in each slot of the same index
const char* xml_parse_OutNames[] = {"Parsed XML Tbl", nullptr}; // This array contains the names of each output slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing.
void xml_parse_construct(){}
void xml_parse_destruct(){}
uint64_t xml_parse(LavaParams const* lp, LavaFrame const* in, lava_threadQ* out) noexcept
{
//printf("entered");
Vis v;
auto inTxtPckt = in->packets[IN_XML_PARSE_TXT];
str inTxt;
inTxt.resize( inTxtPckt.sz_bytes );
memcpy( (void*)inTxt.data(), (void*)inTxtPckt.val.value, inTxtPckt.sz_bytes);
//printf("\n\n %s \n", inTxt.c_str() );
tinyxml2::XMLDocument doc(true, tinyxml2::COLLAPSE_WHITESPACE);
doc.Parse( inTxt.c_str(), inTxt.size() );
doc.Accept( &v );
tbl xmlParse = LavaMakeTbl(lp);
xmlParse.resize<i8>(1,0);
out->push( LavaTblToOut(xmlParse, OUT_XML_PARSE_XML) );
return 0;
}
const char* json_parse_InTypes[] = {"JSON", "PARAMS", nullptr}; // This array contains the type that each slot of the same index will accept as input.
const char* json_parse_InNames[] = {"JSON to Parse", "Keys to Extract", nullptr}; // This array contains the names of each input slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing.
const char* json_parse_OutTypes[] = {"TBL", nullptr}; // This array contains the types that are output in each slot of the same index
const char* json_parse_OutNames[] = {"Nested Tbls of JSON values", nullptr}; // This array contains the names of each output slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing.
void json_parse_construct(){}
void json_parse_destruct(){}
uint64_t json_parse(LavaParams const* lp, LavaFrame const* in, lava_threadQ* out) noexcept
{
using namespace std;
using namespace nlohmann;
str s = (str)LavaTblFromPckt(lp, in, IN_JSON_PARSE_ASCII);
tbl keys = LavaTblFromPckt(lp, in, IN_JSON_KEYS);
json j = json::parse(s, nullptr, false);
ExtractKey(lp, &keys, j);
tbl keysOut = keys; // LavaMakeTbl(lp);
out->push( LavaTblToOut(keysOut, OUT_JSON_PARSE_TBL) );
//lp->lava_puts(s.c_str());
//
//for(auto&& e : j){
// PrintElem(lp, e);
//}
//
//lp->lava_puts("\n 17 \n");
//
//tbl tmp = LavaMakeTbl(lp, 1, (i8)0);
//tmp("itemId") = (u64)0;
//tmp("name") = (u64)0; //&tbl();
//tmp("salePrice") = (f64)0;
//out->push( LavaTblToOut(tmp, OUT_JSON_PARSE_TBL) );
return 0;
}
const char* sqlite_InTypes[] = {"SQLPARAM", nullptr}; // This array contains the type that each slot of the same index will accept as input.
const char* sqlite_InNames[] = {"Sqlite3 Params", nullptr}; // This array contains the names of each input slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing.
const char* sqlite_OutTypes[] = {"SQLRSULT", nullptr}; // This array contains the types that are output in each slot of the same index
const char* sqlite_OutNames[] = {"Tbls of SQL Query Results", nullptr}; // This array contains the names of each output slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing.
void sqlite_construct(){}
void sqlite_destruct(){}
uint64_t sqlite(LavaParams const* lp, LavaFrame const* in, lava_threadQ* out) noexcept
{
using namespace std;
//str query = (str)LavaTblFromPckt(lp, in, IN_SQLLITE_PARAMS);
tbl keys = LavaTblFromPckt(lp, in, IN_SQLLITE_PARAMS);
sqlite3* sl;
sqlite3_open("sqlite_test.db", &sl);
Println(lp, sqlite3_errmsg(sl) );
str itemID = ""; //GetKey(keys, "itemID"); // keys.has("itemID")? (str)(tbl)keys("itemID") : "";
str name = ""; //GetKey(keys, "name"); // keys.has("name")? (str)(tbl)keys("name") : "";
str model = ""; //GetKey(keys, "model");
str price = toString( keys.has("salePrice")? (f64)keys("salePrice") : 0.0 );
Println(lp, "mark 1");
str query = toString(
"INSERT INTO TVS (Item_ID, Name, Model, Price) VALUES (",
"\"", itemID, "\", ",
"\"", name, "\", ",
"\"", model, "\", ",
price,
");");
//char query[1024];
//sscanf(query,
// "INSERT INTO TVS (Item_ID, Name, Model, Price) VALUES ( \"%s\", \"%s\", \"%s\", \"%s\"); ",
// itemID.c_str(), name.c_str(), model.c_str(), price.c_str());
//str query = "INSERT INTO TVS (Item_ID, Name, Model, Price) VALUES ( \"\", \"\", \"\", 0); ";
Println(lp, query);
//sqlite3_exec(sl, "BEGIN", nullptr, nullptr, nullptr);
sqlite3_exec(sl, query.c_str(), nullptr, nullptr, nullptr);
//sqlite3_exec(sl, query.c_str(), nullptr, nullptr, nullptr);
//sqlite3_exec(sl, "COMMIT", nullptr, nullptr, nullptr);
Println(lp, sqlite3_errmsg(sl) );
Println(lp, sqlite3_errmsg(sl) );
// Println(lp, sqlite3_threadsafe() );
int closeOk = sqlite3_close(sl);
tbl tmp = LavaMakeTbl(lp, 1, (i8)0);
out->push( LavaTblToOut(tmp, OUT_SQLLITE_RESULT) );
return 0;
}
//const char* winmsg_InTypes[] = {"params", nullptr}; // This array contains the type that each slot of the same index will accept as input.
//const char* winmsg_InNames[] = {"Watch and MSG", nullptr}; // This array contains the names of each input slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing.
//const char* winmsg_OutTypes[] = {"STATS", nullptr}; // This array contains the types that are output in each slot of the same index
//const char* winmsg_OutNames[] = {"Status", nullptr}; // This array contains the names of each output slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing.
//void winmsg_construct(){}
//void winmsg_destruct(){}
//uint64_t winmsg(LavaParams const* lp, LavaFrame const* in, lava_threadQ* out) noexcept
//{
// runCount++;
//
// tbl params = LavaTblFromPckt(lp, in, IN_WINMSG_MSG);
// str path = (str)params;
// winHndl = (u64)params("window handle");
// msg = (u32)params("windows message");
// wParam = (u32)params("wParam");
// lParam = (u32)params("lParam");
//
// //u64 winHndl = params("window handle");
// //u32 msg = params("windows message");
// //u32 wParam = params("wParam");
// //u32 lParam = params("lParam");
//
// //WindowFromPoint() // gets the handle from a point on the screen
//
// #ifdef _WIN32
// printf("\n cnt: %d path: %s \n", runCount, path.c_str() );
// printf("\n hndl: %lld msg: %d wParam: %d lParam %d \n", winHndl.load(), msg.load(), wParam.load(), lParam.load());
//
// //SendMessage( (HWND)0x00040A68, WM_KEYDOWN, VK_F5, 0); // F5 key
// //SendMessage( (HWND)winHndl, msg, VK_RCONTROL, lParam);
// //SendMessage( (HWND)winHndl, msg, wParam, lParam);
// //SendMessage( (HWND)winHndl, msg, VK_BROWSER_REFRESH, lParam);
//
// // 0x52 r key | 0xA3 RCONTROL | VK_BROWSER_REFRESH 0xA8 | 0x74 VK_F5
// //SendMessage( (HWND)winHndl, msg, wParam, lParam);
//
// //HANDLE prevHndl = (HANDLE)waitHndl.exchange(0);
// //if(prevHndl){
// // bool ok = UnregisterWait( (HANDLE)prevHndl );
// // printf("\n unregister ok: %d \n", ok);
// //}else{
//
// bool prev = false;
// //while(true)
// //{
// HANDLE dirHndl = FindFirstChangeNotification(
// path.c_str(), // directory to watch
// FALSE, // do not watch subtree
// FILE_NOTIFY_CHANGE_LAST_WRITE);
//
// if(dirHndl == INVALID_HANDLE_VALUE){
// winErr = true;
// dirHndl = nullptr;
// //break;
// }
//
// WaitForSingleObject(dirHndl, INFINITE);
//
// LRESULT ok = SendMessage( (HWND)(winHndl.load()), msg, wParam, lParam);
// printf("\n send message ok: %ld \n", (long)ok);
//
// //prev = false;
// //if( runCb.compare_exchange_strong(prev, true) )
// //{
// // PHANDLE pHndl = (void**)&waitHndl;
// // auto ok = RegisterWaitForSingleObject(
// // pHndl,
// // dirHndl,
// // cb_WaitOrTimerCallback,
// // 0,
// // INFINITE,
// // WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD | WT_EXECUTEDEFAULT);
// // printf("\n register ok: %d \n", ok);
// //}
//
// auto closeOk = FindCloseChangeNotification(dirHndl);
//
// //Sleep(20000);
// //}
// //}
//
// //RegisterWaitForSingleObject
// //while(true){
// // auto waitRet = WaitForSingleObject(dirHndl, INFINITE);
// // if(waitRet == WAIT_OBJECT_0){
// // SendMessage( (HWND)winHndl, msg, wParam, lParam);
// // break;
// // }
// //}
// #endif
//
// tbl tmp = LavaMakeTbl(lp);
// tmp("window handle") = (u64)0;
// tmp("windows message") = (u32)WM_KEYDOWN;
// tmp("wParam") = (u32)VK_F5;
// tmp("lParam") = (u32)0;
// tmp.resize<i8>(1024, 0);
// strncpy(tmp.data<char>(), "file to watch", 1023);
// out->push( LavaTblToOut(tmp, OUT_WINMSG_STAT) );
//
// return 0;
//}
LavaNode LavaNodes[] =
{
{
TblToStr, // function
nullptr, // constructor - this can be set to nullptr if not needed
nullptr, // destructor - this can also be set to nullptr
LavaNode::FLOW, // node_type - this should be eighther LavaNode::MSG (will be run even without input packets) or LavaNode::FLOW (will be run only when at least one packet is available for input)
"TblToStr", // name
TblToStr_InTypes, // in_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
TblToStr_InNames, // in_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
TblToStr_OutTypes, // out_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
TblToStr_OutNames, // out_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
nullptr, // description
0 // version
},
{
http, // function
nullptr, // constructor - this can be set to nullptr if not needed
nullptr, // destructor - this can also be set to nullptr
LavaNode::FLOW, // node_type - this should be eighther LavaNode::MSG (will be run even without input packets) or LavaNode::FLOW (will be run only when at least one packet is available for input)
"http", // name
http_InTypes, // in_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
http_InNames, // in_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
http_OutTypes, // out_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
http_OutNames, // out_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
nullptr, // description
0 // version
},
{
xml_parse, // function
xml_parse_construct, // constructor - this can be set to nullptr if not needed
xml_parse_destruct, // destructor - this can also be set to nullptr
LavaNode::FLOW, // node_type - this should be eighther LavaNode::MSG (will be run even without input packets) or LavaNode::FLOW (will be run only when at least one packet is available for input)
"xml_parse", // name
xml_parse_InTypes, // in_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
xml_parse_InNames, // in_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
xml_parse_OutTypes, // out_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
xml_parse_OutNames, // out_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
nullptr, // description
0 // version
},
{
json_parse, // function
json_parse_construct, // constructor - this can be set to nullptr if not needed
json_parse_destruct, // destructor - this can also be set to nullptr
LavaNode::FLOW, // node_type - this should be eighther LavaNode::MSG (will be run even without input packets) or LavaNode::FLOW (will be run only when at least one packet is available for input)
"json_parse", // name
json_parse_InTypes, // in_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
json_parse_InNames, // in_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
json_parse_OutTypes, // out_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
json_parse_OutNames, // out_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
nullptr, // description
0 // version
},
{
sqlite, // function
sqlite_construct, // constructor - this can be set to nullptr if not needed
sqlite_destruct, // destructor - this can also be set to nullptr
LavaNode::FLOW, // node_type - this should be eighther LavaNode::MSG (will be run even without input packets) or LavaNode::FLOW (will be run only when at least one packet is available for input)
"sqlite", // name
sqlite_InTypes, // in_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
sqlite_InNames, // in_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
sqlite_OutTypes, // out_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
sqlite_OutNames, // out_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
nullptr, // description
0 // version
},
LavaNodeListEnd // This is a constant that has all the members of the LavaNode struct set to 0 or nullptr - it is used as a special value that ends the static list of LavaNodes. This negates the need for a separate static variable that gives the size of the list, which would be have to be kept in sync and therefore be error prone.
};
__declspec(dllexport) LavaNode* GetLavaNodes()
{
return (LavaNode*)LavaNodes;
}
}
//bool VisitEnter(const XMLDocument& doc){
// printTxt("doc text:", doc.ToText() );
// printf("doc val: %s", doc.Value()? doc.Value() : "val null");
// //printf("doc get text: %s", doc.Value() );
// return true;
//}
//bool VisitExit(const XMLDocument& doc){
// printTxt("doc text:", doc.ToText() );
// printf("doc val: %s", doc.Value()? doc.Value() : "val null");
// //printf("doc get text: %s", doc.GetText() );
// return true;
//}
//auto txt = elem.ToText();
////if(txt){
// printf("\n elem text: %s \n", txt? txt->Value() : "NULL");
////}
//
//printTxt("elem text:", elem.ToText());
//printf(" elem get text: %s", elem.GetText());
//printTxt("attr text:", firstAttr.ToText() );
//
//if(firstAttr){
// auto txt = firstAttr->Value();
// printf("\n attr text: %s \n", txt? txt : "NULL");
//}
//bool VisitExit(const XMLElement& elem)
//{
// printTxt("elem exit:", elem.ToText());
// return true;
//}
//bool Visit(const XMLText& xt)
//{
// printTxt("text txt:", xt.ToText());
//
// //auto txt = xt.ToText();
// //if(txt){
// // printf("\n text: %s \n", txt? txt->Value() : "NULL");
// //}
//
// return true;
//}
//bool Visit(const XMLDeclaration& decl)
//{
// printTxt("declaration:", decl.ToText() );
// printf("declaration val: %s", decl.Value()? decl.Value() : "val null");
//
// //auto txt = decl.ToText();
// //printf("\n declaration: %s \n", txt? txt->Value() : "NULL");
//
// return true;
//}
//bool Visit(const XMLComment& com){
// printTxt("commment txt:", com.ToText() );
// return true;
//}
//bool Visit(const XMLUnknown& unknown){
// printTxt("unknown txt:", unknown.ToText() );
// return true;
//}
//str de = toString(e);
//
//ofstream o(lp->lava_stdout);
//o << e << endl << endl << endl;
//cout << e << endl << endl << endl;
//void Print(LavaParams const* lp, str s)
//{
// lp->lava_puts( s.c_str() );
//}
//lp->lava_puts( toString("\n",sl,"\n\n").c_str() );
//lp->lava_puts( toString("\n", sqlite3_errmsg(sl), "\n\n").c_str() );
//
//int rc = 0; // resource cursor?
//
//Print(lp, toString("\ncloseOk: ", closeOk, "\n\n") );
//
//lp->lava_puts( toString("\n", sqlite3_errmsg(sl), "\n\n").c_str() );
//
//str s = LavaStrFromPckt(in, IN_JSON_PARSE_ASCII);
//printf(s.c_str());
//fprintf(lp->lava_stdout, s.c_str());
//fprintf(stdout, s.c_str());
//json::json_pointer jp;
//json::
//json j = s;
//j.parse();
//{
//winmsg, // function
// winmsg_construct, // constructor - this can be set to nullptr if not needed
// winmsg_destruct, // destructor - this can also be set to nullptr
// LavaNode::FLOW, // node_type - this should be eighther LavaNode::MSG (will be run even without input packets) or LavaNode::FLOW (will be run only when at least one packet is available for input)
// "winmsg", // name
// winmsg_InTypes, // in_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
// winmsg_InNames, // in_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
// winmsg_OutTypes, // out_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
// winmsg_OutNames, // out_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr
// nullptr, // description
// 0 // version
//},
//std::string UriEncode(const std::string & sSrc)
//{
// const char DEC2HEX[16 + 1] = "0123456789ABCDEF";
// const unsigned char * pSrc = (const unsigned char *)sSrc.c_str();
// const int SRC_LEN = sSrc.length();
// unsigned char * const pStart = new unsigned char[SRC_LEN * 3];
// unsigned char * pEnd = pStart;
// const unsigned char * const SRC_END = pSrc + SRC_LEN;
//
// for (; pSrc < SRC_END; ++pSrc)
// {
// if (SAFE[*pSrc])
// *pEnd++ = *pSrc;
// else
// {
// // escape this char
// *pEnd++ = '%';
// *pEnd++ = DEC2HEX[*pSrc >> 4];
// *pEnd++ = DEC2HEX[*pSrc & 0x0F];
// }
// }
//
// std::string sResult((char *)pStart, (char *)pEnd);
// delete [] pStart;
// return sResult;
//}
//std::string UriDecode(const std::string & sSrc)
//{
// // Note from RFC1630: "Sequences which start with a percent
// // sign but are not followed by two hexadecimal characters
// // (0-9, A-F) are reserved for future extension"
//
// const unsigned char * pSrc = (const unsigned char *)sSrc.c_str();
// const int SRC_LEN = sSrc.length();
// const unsigned char * const SRC_END = pSrc + SRC_LEN;
// // last decodable '%'
// const unsigned char * const SRC_LAST_DEC = SRC_END - 2;
//
// char * const pStart = new char[SRC_LEN];
// char * pEnd = pStart;
//
// while (pSrc < SRC_LAST_DEC)
// {
// if (*pSrc == '%')
// {
// char dec1, dec2;
// if (-1 != (dec1 = HEX2DEC[*(pSrc + 1)])
// && -1 != (dec2 = HEX2DEC[*(pSrc + 2)]))
// {
// *pEnd++ = (dec1 << 4) + dec2;
// pSrc += 3;
// continue;
// }
// }
//
// *pEnd++ = *pSrc++;
// }
//
// // the last 2- chars
// while (pSrc < SRC_END)
// *pEnd++ = *pSrc++;
//
// std::string sResult(pStart, pEnd);
// delete [] pStart;
// return sResult;
//}
//void OnBegin( const happyhttp::Response* r, void* userdata )
//{
// printf( "BEGIN (%d %s)\n", r->getstatus(), r->getreason() );
// count = 0;
//}
//void OnData( const happyhttp::Response* r, void* userdata, const unsigned char* data, int n )
//{
// fwrite( data,1,n, stdout );
// count += n;
//}
//void OnComplete( const happyhttp::Response* r, void* userdata )
//{
// printf( "COMPLETE (%d bytes)\n", count );
//}
// todo: change this to raw text
//tbl pageTxt;
//out->push( LavaTblToOut(pageTxt, OUT_HTTP_TXT) );
//printf("url: %s \n\n addr: %s \n\n file: %s", url.c_str());
//
//str urlStr = "www.google.com";
//
//str pgeStr = "/";
//
//while((result = strchr(result, target)) != NULL) {
// printf("Found '%c' starting at '%s'\n", target, result);
// ++result; // Increment result, otherwise we'll find target at the same location
//}
//void http_construct(){}
//void http_destruct(){}
//http_construct, // constructor - this can be set to nullptr if not needed
//http_destruct, // destructor - this can also be set to nullptr
//str s = LavaStrFromPckt(in, IN_TBL_TO_STR_ASCII);
//
//str inTxt;
//inTxt.resize( inTxtPckt.sz_bytes );
//memcpy( (void*)inTxt.data(), (void*)inTxtPckt.val.value, inTxtPckt.sz_bytes);
//
//tbl tmp = LavaMakeTbl(lp);
//cnct.request( "POST",
// "/happyhttp/test.php",
// headers,
// (const unsigned char*)body,
// strlen(body) );
//str tst = j.dump();
//printf("\ntest string:\n%s", tst.c_str());
//printf("\n\n");
//
//cout << setw(2) << j << endl;
//cout << e << endl << endl << endl;
//switch(e.type()){
//case json::value_t::array:
//case json::value_t::object:
//
//default: ;
//}
//const str s = (const str)LavaTblFromPckt(lp, in, IN_JSON_PARSE_ASCII);
//
//auto inTxtPckt = in->packets[IN_XML_PARSE_TXT];
//str inTxt;
//inTxt.resize( inTxtPckt.sz_bytes );
//memcpy( (void*)inTxt.data(), (void*)inTxtPckt.val.value, inTxtPckt.sz_bytes);
//tmp.resize<i8>(1024, 0);
//strncpy(tmp.data<char>(), "file to watch", 1023);
//u64 pathLen = strnlen( params.data<char>(), params.size() );
//str path;
//path.resize(pathLen);
//strncpy( (char*)path.data(), params.data<char>(), path.size() );
//#ifdef _WIN32
// m_dir = FindFirstChangeNotification(
// path, // directory to watch
// FALSE, // do not watch subtree
// FILE_NOTIFY_CHANGE_LAST_WRITE);
//
// if(m_dir == INVALID_HANDLE_VALUE){
// m_error = true;
// m_dir = nullptr;
// }
// WaitForSingleObject(m_dir, INFINITE);
//#endif
//
//WM_LBUTTONDOWN fwKeys: 0000 xPos: 86 yPos 57
//WM_KEYDOWN nVirtKey: VK_MEDIA_NEXT_TRACK cRepeat: 1 ScanCode: 00f Extended: 1 fAltDown: 0 fRepeat: 0 fUp:
//auto xmlElem = doc.FirstChildElement();
//auto xmlElem = doc.RootElement();
//auto xmlDoc = xmlElem->GetDocument();
//auto e2 = xmlDoc->FirstChildElement();
//auto txt1 = e2->ToText();
//
//auto xmlDoc = doc.FirstChildElement();
//auto txt1 = xmlDoc->ToText();
//printf("\n %s \n", txt1? txt1->Value() : "NULL");
//
//auto chld = doc.FirstChild();
//auto txt2 = chld->ToText();
////auto a = chld->Accept( &v );
//printf("\n %s \n", txt2? txt2->Value() : "NULL");
//
//e2->NextSiblingElement();
//auto txt = xmlDoc->ToText();
//
//printf("\n\n %s %s \n\n", xmlElem->ToText()->Value(), xmlDoc->ToText()->Value() );
//tbl url = LavaMakeTbl(lp);
//str urlStr = url.data<const char>();
//
//str urlStr = "216.58.216.110";
//u32 i=0;
//while( LavaNxtPckt(in, &i) )
//{
// tbl inputTbl( (void*)(in->packets[i-1].val.value) );
// //for(auto& kv : inputTbl){ // this loop demonstrates how to iterate through non-empty map elements
// //}
//}
| [
"lava@shinespark.io"
] | lava@shinespark.io |
49ed3118a320af2bab0c73faa913f46490643424 | f5dc059a4311bc542af480aa8e8784965d78c6e7 | /images/Images.h | afd326604f0279160be0d9cf6d50018bae29958d | [] | no_license | astro-informatics/casacore-1.7.0_patched | ec166dc4a13a34ed433dd799393e407d077a8599 | 8a7cbf4aa79937fba132cf36fea98f448cc230ea | refs/heads/master | 2021-01-17T05:26:35.733411 | 2015-03-24T11:08:55 | 2015-03-24T11:08:55 | 32,793,738 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,048 | h | //# Images.h: N-dimensional astronomical images
//# Copyright (C) 1998,1999
//# Associated Universities, Inc. Washington DC, USA.
//#
//# This library is free software; you can redistribute it and/or modify it
//# under the terms of the GNU Library General Public License as published by
//# the Free Software Foundation; either version 2 of the License, or (at your
//# option) any later version.
//#
//# This library is distributed in the hope that it will be useful, but WITHOUT
//# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
//# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
//# License for more details.
//#
//# You should have received a copy of the GNU Library General Public License
//# along with this library; if not, write to the Free Software Foundation,
//# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA.
//#
//# Correspondence concerning AIPS++ should be addressed as follows:
//# Internet email: aips2-request@nrao.edu.
//# Postal address: AIPS++ Project Office
//# National Radio Astronomy Observatory
//# 520 Edgemont Road
//# Charlottesville, VA 22903-2475 USA
//#
//# $Id: Images.h 20691 2009-07-14 03:13:54Z Malte.Marquarding $
#ifndef IMAGES_IMAGES_H
#define IMAGES_IMAGES_H
#include <casa/Arrays/IPosition.h>
#include <casa/Arrays/Slice.h>
#include <casa/Arrays/Slicer.h>
namespace casa { //# NAMESPACE CASA - BEGIN
//#include <casa/Arrays/ArrayLattice.h>
//#include <casa/Arrays/PagedArray.h>
//#include <casa/Arrays/TempLattice.h>
//#include <casa/Arrays/TiledShape.h>
//#include <casa/Arrays/LatticeIterator.h>
//#include <casa/Arrays/LatticeStepper.h>
//#include <casa/Arrays/TileStepper.h>
//#include <casa/Arrays/TiledLineStepper.h>
//#include <lattices/Lattices/SubLattice.h>
//#include <lattices/Lattices/LatticeExpr.h>
//#include <lattices/Lattices/LatticeRegion.h>
//#include <lattices/Lattices/LCSlicer.h>
//#include <lattices/Lattices/LCBox.h>
//#include <lattices/Lattices/LCEllipsoid.h>
//#include <lattices/Lattices/LCPolygon.h>
//#include <lattices/Lattices/LCUnion.h>
//#include <lattices/Lattices/LCIntersection.h>
//#include <lattices/Lattices/LCDifference.h>
//#include <lattices/Lattices/LCConcatenation.h>
//#include <lattices/Lattices/LCComplement.h>
//#include <lattices/Lattices/LCExtension.h>
// <module>
// <summary>
// N-dimensional astronomical images
// </summary>
// <prerequisite>
// <li> Programmers of new Image classes should understand Inheritance
// <li> Users of the Image classes should understand Polymorphism.
// <li> class <linkto class=Lattice>Lattice</linkto>
// <li> class <linkto class=CoordinateSystem>CoordinateSystem</linkto>
// </prerequisite>
// <reviewed reviewer="UNKNOWN" date="before2004/08/25" demos="">
// </reviewed>
// <etymology>
// </etymology>
// <synopsis>
// </synopsis>
// <motivation>
// </motivation>
//# <todo asof="1998/11/02">
//# </todo>
// </module>
} //# NAMESPACE CASA - END
#endif
| [
"jason.mcewen@ucl.ac.uk"
] | jason.mcewen@ucl.ac.uk |
fd8fe62b361ac2bfb8e689b41e1cb9830cafdce8 | e33b790ec7b22a4c2cfc470d46794e954a2e4a7d | /lib/WaveformTracer.cpp | cee15b85cf490c368a7d8651aaef94dce4d9ba60 | [
"LicenseRef-scancode-other-permissive"
] | permissive | caizikun/tool_axe | 0ae4abf3e7d5feb6280f37bbafe0f5b4bf1d8d9a | c1d7c0ad8095abc6733eb8df3bc0f4f72b3852d6 | refs/heads/master | 2020-03-20T10:40:53.686373 | 2018-05-30T13:46:20 | 2018-05-30T13:46:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,195 | cpp | // Copyright (c) 2011, Richard Osborne, All rights reserved
// This software is freely distributable under a derivative of the
// University of Illinois/NCSA Open Source License posted in
// LICENSE.txt and at <http://github.xcore.com/>
#include "WaveformTracer.h"
#include "Port.h"
#include "BitManip.h"
#include <ctime>
using namespace axe;
WaveformTracer::WaveformTracer(const std::string &name) :
out(name.c_str(), std::fstream::out),
portsFinalized(false),
currentTime(0) {}
void WaveformTracerPort::update(ticks_t newTime)
{
if (!prev.isClock())
return;
EdgeIterator it = prev.getEdgeIterator(time);
while (it->time <= newTime) {
uint32_t value = it->type == Edge::RISING ? 1 : 0;
parent->seePinsChange(this, value, it->time);
++it;
}
time = newTime;
parent->schedule(this, it->time);
}
void WaveformTracerPort::seePinsChange(const Signal &value, ticks_t newTime)
{
if (value == prev)
return;
parent->runUntil(newTime);
uint32_t prevValue = prev.getValue(newTime);
uint32_t newValue = value.getValue(newTime);
if (prevValue != newValue)
parent->seePinsChange(this, newValue, newTime);
time = newTime;
prev = value;
if (value.isClock()) {
parent->schedule(this, value.getNextEdge(newTime).time);
}
}
void WaveformTracer::add(const std::string &name, Port *port)
{
assert(!portsFinalized);
modules[name].push_back(ports.size());
ports.push_back(WaveformTracerPort(this, port,
makeIdentifier(ports.size())));
}
std::string WaveformTracer::makeIdentifier(unsigned index)
{
std::string identifier;
unsigned offset = '!';
unsigned base = '~' - '!' + 1;
if (index) {
while (index) {
identifier.push_back(offset + (index % base));
index /= base;
}
} else {
identifier.push_back(offset);
}
return identifier;
}
void WaveformTracer::emitDate()
{
time_t rawTime = std::time(0);
if (rawTime == -1)
return;
struct tm *timeinfo = localtime(&rawTime);
char buf[256];
if (std::strftime(buf, 256, "%B %d, %Y %X", timeinfo) == 0)
return;
out << "$date\n";
out << " " << buf << '\n';
out << "$end\n";
}
void WaveformTracer::emitDeclarations()
{
emitDate();
out << "$version\n";
out << " AXE (An XCore Emulator)\n";
out << "$end\n";
out << "$timescale\n";
out << " 100 ps\n";
out << "$end\n";
}
void WaveformTracer::
dumpPortValue(const std::string &identifier, Port *port, uint32_t value)
{
if (port->getPortWidth() == 1) {
// Dumps of value changes to scalar variables shall not have any white space
// between the value and the identifier code.
out << (value & 1);
} else {
// Dumps of value changes to vectors shall not have any white space between
// the base letter and the value digits, but they shall have one white space
// between the value digits and the identifier code.
// The output format for each value is right-justified. Vector values appear
// in the shortest form possible: redundant bit values which result from
// left-extending values to fill a particular vector size are eliminated.
out << 'b';
if (value) {
for (int i = 31 - countLeadingZeros(value); i >= 0; i--) {
out << ((value & (1 << i)) ? '1' : '0');
}
} else {
out << '0';
}
out << ' ';
}
out << identifier;
out << '\n';
}
void WaveformTracer::dumpInitialValues()
{
out << "$dumpvars\n";
for (WaveformTracerPort &port : ports) {
dumpPortValue(port.getIdentifier(), port.getPort(), 0);
}
out << "$end\n";
}
void WaveformTracer::finalizePorts()
{
assert(!portsFinalized);
portsFinalized = true;
emitDeclarations();
for (auto &entry : modules) {
const std::string &moduleName = entry.first;
if (!moduleName.empty()) {
out << "$scope\n";
out << " module " << moduleName << '\n';
out << "$end\n";
}
const std::vector<unsigned> &modulePorts = entry.second;
for (unsigned index : modulePorts) {
WaveformTracerPort &waveformTracerPort = ports[index];
Port *port = waveformTracerPort.getPort();
port->setTracer(&waveformTracerPort);
out << "$var\n";
out << " wire";
out << ' ' << std::dec << port->getID().width();
out << ' ' << waveformTracerPort.getIdentifier();
out << ' ' << port->getName();
out << '\n';
out << "$end\n";
}
if (!moduleName.empty()) {
out << "$upscope $end\n";
}
}
out << "$enddefinitions $end\n";
dumpInitialValues();
}
void WaveformTracer::schedule(WaveformTracerPort *port, ticks_t time)
{
queue.push(Event(port, time));
}
void WaveformTracer::runUntil(ticks_t time)
{
if (!queue.empty()) {
while (queue.top().time < time) {
Event event = queue.top();
event.port->update(event.time);
queue.pop();
}
}
}
void WaveformTracer::
seePinsChange(WaveformTracerPort *port, uint32_t value, ticks_t time)
{
ticks_t translatedTime = time * (100 / CYCLES_PER_TICK);
if (translatedTime != currentTime) {
out << '#' << translatedTime << '\n';
currentTime = translatedTime;
}
dumpPortValue(port->getIdentifier(), port->getPort(), value);
}
| [
"richard@xmos.com"
] | richard@xmos.com |
a0d697a8acc676bf5e41725434112019ee884155 | 15b0158640e19807b04449243e0214d956804817 | /userlib/test/simpleDigitizer.cpp | 6371507fdefaaa62311d5057a0258c2793013d9b | [] | no_license | mia635/updatepfcal | 203c8a993472624796f4a55582d7d38ba691f916 | df0d573bf2c9bada97cd528107e97f858db69614 | refs/heads/master | 2021-01-20T21:03:14.184799 | 2016-08-08T21:03:44 | 2016-08-08T21:03:44 | 65,239,057 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,402 | cpp | #include<string>
#include<set>
#include<iostream>
#include<fstream>
#include<sstream>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <random>
#include "TFile.h"
#include "TTree.h"
#include "TChain.h"
#include "TNtuple.h"
#include "TH2D.h"
#include "TH2Poly.h"
#include "TH1F.h"
#include "TCanvas.h"
#include "TStyle.h"
#include "TRandom3.h"
#include "TVector3.h"
#include "Math/Vector4D.h"
#include "HGCSSEvent.hh"
#include "HGCSSInfo.hh"
#include "HGCSSSimHit.hh"
#include "HGCSSRecoHit.hh"
#include "HGCSSGenParticle.hh"
#include "HGCSSRecoJet.hh"
#include "HGCSSCalibration.hh"
#include "HGCSSDigitisation.hh"
#include "HGCSSDetector.hh"
#include "HGCSSGeometryConversion.hh"
#include "HGCSSSamplingSection.hh"
#ifdef __MAKECINT__
#pragma link C++ class vector<float>+;
#endif
int main(int argc, char** argv) {
std::cout << "argc: " << argc << std::endl;
std::cout << "TChain files: " << argv[1] << std::endl;
std::cout << "Output file tag: " << argv[2] << std::endl;
TChain* tree = new TChain("HGCSSTree");
tree->Add(argv[1]);
std::vector<HGCSSSamplingSection> * samplingVec = 0;
tree->SetBranchAddress("HGCSSSamplingSectionVec", &samplingVec);
unsigned nEvts = tree->GetEntries();
char outFileName[256];
sprintf(outFileName,"simpleHCalDigis_%s.root",argv[2]);
TFile hfile(outFileName,"RECREATE");
TTree t1("hcal_digi", "");
Int_t nLayers,layerPEs[15],layerNum[15];
t1.Branch("nLayers", &nLayers, "nLayers/I");
t1.Branch("layerPEs", &layerPEs, "layerPEs[nLayers]/I");
t1.Branch("layerNum", &layerNum, "layerNum[nLayers]/I");
for (unsigned ievt(0); ievt < nEvts; ++ievt) { //loop on entries
tree->GetEntry(ievt);
nLayers = 15;
for (Int_t j = 43; j < 58 ; j++) {
HGCSSSamplingSection& sec = (*samplingVec)[j];
float MeVperMIP = 1.40;
float PEperMIP = 13.5*6./4.;
float depEnergy = sec.sensDep();
float meanPE = depEnergy/MeVperMIP*PEperMIP;
std::default_random_engine generator;
std::poisson_distribution<int> distribution(meanPE);
layerPEs[j-43] = distribution(generator);
layerNum[j-43] = j-43;
/*
std::cout << "- - - - - " << j-42 << " - - - - - - - " << std::endl;
std::cout << "depEnergy: " << depEnergy << std::endl;
std::cout << "meanPE: " << meanPE << std::endl;
std::cout << "PE: " << layerPEs[j-43] << std::endl;
*/
}
t1.Fill();
}
t1.Write();
hfile.Close();
return 1;
}
| [
"sanghamitra@169-231-145-3.wireless.ucsb.edu"
] | sanghamitra@169-231-145-3.wireless.ucsb.edu |
f4f49f27a24be09b2676f86a239e3b388f0aa82f | 606a7c30d7e3f10ea42f908c57105f99bdbbc105 | /IQmeasure/IQmeasure_IQapi_SCPI/iqmeasure.cpp | ca285a75227f4127ea760cfb12dfc9a7a74cc5cd | [
"MIT"
] | permissive | roccozhang/IQ_DualHead | bd0c96ae12ff73c28a54b9ebf9f9fc4564f8965a | 350fa1774ca21fa64587a444261d9c54ef53d262 | refs/heads/master | 2021-01-18T15:52:07.327213 | 2014-11-21T06:39:48 | 2014-11-21T06:39:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 314,053 | cpp | // IQmeasure Library in IQlite
#include "stdafx.h"
//Move to stdafx.h
//#include "lp_stdio.h"
#include "iqapi.h"
#include "iqapiCommon.h"
#include "..\IQmeasure.h"
//#include "..\DebugAlloc.h"
#include "IQlite_Timer.h"
#include "IQlite_Logger.h"
#include "StringUtil.h"
#include "IQ2010Ext.h"
#ifdef WIN32
#include "aimcontrol.h"
#endif
//Move to stdafx.h
//#include "lp_string.h"
#include <float.h> // DBL_MAX on Mac
#include "Version.h"
#include "iqapi11ac.h"
/*
#pragma comment(lib, "iqapi.lib")
#pragma comment(lib, "IQlite_Timer.lib")
#pragma comment(lib, "IQlite_Logger.lib")
#pragma comment(lib, "Util.lib")
#pragma comment(lib, "IQ2010Ext.lib")
*/
#ifndef WIN32
inline double abs(double x)
{ return (fabs(x)); }
#endif
// BEGIN GLOBALS
char *IQmeasure_Version = IQMEASURE_VERSION;
iqapiHndl *hndl = NULL;
int timerIQmeasure = -1;
int loggerIQmeasure = -1;
highrestimer::lp_time_t timeStart, timeStop;
//double timeStart, timeStop;
double timeDuration;
double g_testerHwVersion = 0;
bool g_bDisableFreqFilter = true;
iqapiAnalysis80216 *analysis80216 = NULL;
iqapiAnalysisMimo *analysisMimo = NULL;
iqapiAnalysisOFDM *analysisOfdm = NULL;
iqapiAnalysis11b *analysis11b = NULL;
iqapiAnalysisPowerRamp *analysisPowerRampOfdm = NULL;
iqapiAnalysisPowerRamp *analysisPowerRamp11b = NULL;
iqapiAnalysisCW *analysisCW = NULL;
iqapiAnalysisWave *analysisWave = NULL;
iqapiAnalysisSidelobe *analysisSidelobe = NULL;
iqapiAnalysisCCDF *analysisCCDF = NULL;
iqapiAnalysisFFT *analysisFFT = NULL;
iqapiAnalysisPower *analysisPower = NULL;
iqapiAnalysisBluetooth *analysisBluetooth = NULL;
iqapiAnalysisZigbee *analysisZigbee = NULL;
#if !defined(IQAPI_1_5_X)
// iqapiAnalysisHT40 is supported in IQapi 1.6.x and beyond
iqapiAnalysisHT40 *analysisHT40 = NULL;
#endif
iqapiAnalysisWifiOfdm *analysisWifiOfdm = NULL;
//iqapiAnalysis11ac *analysis11ac = NULL;
iqapiAnalysisVHT80WideBand *analysisVHT80 = NULL;
//FM Analysis
iqapiAnalysisAudioStereo *analysisAudioStereo = NULL;
iqapiAnalysisAudioMono *analysisAudioMono = NULL;
iqapiAnalysisFmAudioBase *analysisFmAudioBase = NULL;
iqapiAnalysisFmRf *analysisFmRf = NULL;
iqapiAnalysisFmDemodSpectrum *analysisFmDemodSpectrum = NULL;
iqapiAnalysisFmMono *analysisFmMono = NULL;
iqapiAnalysisFmStereo *analysisFmStereo = NULL;
iqapiAnalysisFmAuto *analysisFmAuto = NULL;
iqapiAnalysisRds *analysisRds = NULL;
iqapiAnalysisRdsMono *analysisRdsMono = NULL;
iqapiAnalysisRdsStereo *analysisRdsStereo = NULL;
iqapiAnalysisRdsAuto *analysisRdsAuto = NULL;
iqapiResult80216 *result80216 = NULL;
iqapiResultMimo *resultMimo = NULL;
iqapiResultOFDM *resultOfdm = NULL;
iqapiResult11b *result11b = NULL;
iqapiResultPowerRamp *resultPowerRamp = NULL;
iqapiResultSidelobe *resultSidelobe = NULL;
iqapiResultCW *resultCW = NULL;
iqapiResultWave *resultwave = NULL;
iqapiResultCCDF *resultCCDF = NULL;
iqapiResultFFT *resultFFT = NULL;
iqapiResultPower *resultPower = NULL;
iqapiResultBluetooth *resultBluetooth = NULL;
iqapiResultZigbee *resultZigbee = NULL;
//Z-99
//iqapiResult11ac *result11ac = NULL;
iqapiResultWifiOfdm *result11ac = NULL;
iqapiResultVHT80WideBand *resultVHT80Wideband = NULL;
//
// FM Results
iqapiResultAudioStereo *resultAudioStereo = NULL;
iqapiResultAudioMono *resultAudioMono = NULL;
iqapiResultFmRf *resultFmRf = NULL;
iqapiResultFmDemodSpectrum *resultFmDemodSpectrum = NULL;
iqapiResultFmMono *resultFmMono = NULL;
iqapiResultFmStereo *resultFmStereo = NULL;
iqapiResultFmAuto *resultFmAuto = NULL;
iqapiResultRds *resultRds = NULL;
iqapiResultRdsMono *resultRdsMono = NULL;
iqapiResultRdsStereo *resultRdsStereo = NULL;
iqapiResultRdsAuto *resultRdsAuto = NULL;
// FM Scalar Results container
map<string, double> g_FmRfScalarResults;
map<string, double> g_FmMonoScalarResults;
map<string, double> g_FmStereoScalarResults;
// FM Vector Results container
map<string, vector <double> > g_FmRfVectorResults;
map<string, vector <double> > g_FmMonoVectorResults;
map<string, vector <double> > g_FmStereoVectorResults;
#if !defined(IQAPI_1_5_X)
// iqapiResultHT40 is supported in IQapi 1.6.x and beyond
iqapiResultHT40 *resultHT40 = NULL;
#endif
#ifndef MAX_TESTER_NUM
#define MAX_TESTER_NUM 4
#endif
iqapiCapture *capture = NULL;
bool g_audioCaptureOnly = false;
bool LibsInitialized = false;
bool setDefaultCalled = false;
int nTesters = 0;
bool bIQ201xFound = false;
bool bIQxsFound = false;
bool bIQxelFound = false;
// FM Initialization
bool FmInitialized = false;
// int g_fast_buffSize = 0;
// double *g_fast_Real_Ptr = NULL;
// double *g_fast_Imag_Ptr = NULL;
//static double *g_fastcal_pwr_i = NULL;
//static double *g_fastcal_pwr_q = NULL;
//static unsigned int g_fastcal_length_i;
//static unsigned int g_fastcal_length_q;
// This global variable indicates either a single waveform MOD file, or multi-segment MOD file
// has been loaded to the VSG memory.
enum LP_MEASUREMENT_VSG_MODE g_vsgMode; //0-no MOD file loaded; 1-single MOD file; 2-multi-segment MOD file
// This variable remembers the last performed analysis
enum LP_ANALYSIS_TYPE_ENUM g_lastPerformedAnalysisType = ANALYSIS_MAX_NUM;
//TODO: The variable below is for working aroung the problem that
// TX stopped working on IQnxn after RX
// The root cause needs to be sorted out, and then remove this global variable
bool g_previousOperationIsRX = false;
//This variable remebers whethere NxN function is called or not, used by:
// LP_SetVsgNxN(), LP_SetVsaNxN(), LP_EnableVsgRFNxN()
bool g_nxnFunctionCalled = false;
// The structure below is used internally, and for IQnxn only
struct _tagIQnxnSettings
{
double vsaAmplDBm;
double vsgPowerDBm;
enum IQV_PORT_ENUM vsaPort;
enum IQV_PORT_ENUM vsgPort;
int vsgRFEnabled;
} g_IQnxnSettings[N_MAX_TESTERS];
//This variable indicate whether the SCPI command is used to control the tester
bool g_useScpi = false;
//This variable indicate whether the IQapi is used to control the tester
bool g_useIQapi = false;
#ifndef MAX_BUFFER_LEN
#define MAX_BUFFER_LEN 4096
#endif
#ifndef BT_SHIFT_HZ
/***** workaround temporary for BT TX capture issue Jim *****/
#define BT_SHIFT_HZ 0e6
/*
#define BT_SHIFT_HZ 7e6
/************************************************************/
#endif
double g_amplitudeToleranceDb = 3;
// This global variable is needed for selecting partial capture for analysis
// LP_SelectCaptureRangeForAnalysis() will set this variable
// LP_VsaDataCapture() will reset this variable to NULL
// Note: g_userData does not allocate memory at all. It points to a portion of hndl->data
iqapiCapture *g_userData = NULL;
// Internal functions
// Functions declared below are not supposed to go in IQmeasure.h
void InstantiateAnalysisClasses();
int LP_Analyze(void);
void InitializeTesterSettings(void);
// End of Internal functions
namespace {
struct IQMeasureInit
{
IQMeasureInit() { LP_StartIQmeasureTimer(); }
~IQMeasureInit() { LP_FreeMemory(); }
} measInit;
}
IQMEASURE_API char *LP_GetErrorString(int err)
{
::TIMER_StartTimer(timerIQmeasure, "LP_GetErrorString", &timeStart);
switch(err)
{
case ERR_OK: return "No errors";
case ERR_NO_CONNECTION: return "No connection to tester.";
case ERR_NOT_INITIALIZED: return "Library is not initialized. Call Init first.";
case ERR_SAVE_WAVE_FAILED: return "SaveWave failed. Check filename and/or path.";
case ERR_LOAD_WAVE_FAILED: return "LoadWave failed. Check filename and/or path.";
case ERR_SET_TX_FAILED: return "SetTx failed. Check tx input parameters.";
case ERR_SET_WAVE_FAILED: return "SetWave failed. Check filename and/or path.";
case ERR_SET_RX_FAILED: return "SetRx failed. Check rx input parameters.";
case ERR_CAPTURE_FAILED: return "Data capture failed.";
case ERR_NO_CAPTURE_DATA: return "No data to analyze in buffer.";
case ERR_VSA_NUM_OUT_OF_RANGE: return "VSA number is out of range. Try 1-4.";
case ERR_ANALYSIS_FAILED: return "Analysis failed.";
case ERR_NO_VALID_ANALYSIS: return "No valid analysis results.";
case ERR_GENERAL_ERR: return "A general error occurred.";
case ERR_VSG_PORT_IS_OFF: return "VSG port is turned off";
case ERR_NO_MOD_FILE_LOADED: return "No MOD file is loaded";
case ERR_NO_CONT_FOR_MULTI_SEGMENT: return "Multi-segment MOD cannot be in continuous play";
case ERR_MEASUREMENT_NAME_NOT_FOUND: return "The specified measurement name if not defined";
case ERR_INVALID_ANALYSIS_TYPE: return "Invalid analysis type";
case ERR_NO_ANALYSIS_RESULT_AVAILABLE: return "No Analysis results available";
case ERR_NO_MEASUREMENT_RESULT: return "No result for the specified measurement name";
case ERR_SET_TOKEN_FAILED: return "SetTokenID failed";
case ERR_TOKEN_RETRIEVAL_TIMEDOUT: return "TokenRetrieveTimeout timed out";
case ERR_ANALYSIS_NULL_POINTER: return "Analysis pointer is null";
case ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME: return "Analysis param name is not supported";
case ERR_ANALYSIS_INVALID_PARAM_VALUE: return "Analysis value is invalid";
case ERR_INVALID_DATA_CAPTURE_RANGE: return "Capture range slection is beyond valid range";
//FM Error codes
case ERR_FM_NOT_INITIALIZED: return "FM Technology is not initialized. FM Handle is not available.";
case ERR_FM_SET_TX_FAILED: return "Failed to set the FM VSG Parameters. Please check the input parameters";
case ERR_FM_GET_TX_FAILED: return "Failed to query the tester for FM VSG Parameters";
case ERR_FM_SET_AUDIO_TONE_FAILED: return "Failed to set the VSG Audio Tone. Please check the input parameters";
case ERR_FM_GET_AUDIO_TONE_FAILED: return "Failed to get the VSG Audio Tones.";
case ERR_FM_NO_CAPTURE_DATA: return "Failed to read Capture Data";
case ERR_FM_VSA_CAPTURE_FAILED: return "VSA failed to capture signal.";
case ERR_FM_SET_RX_FAILED: return "Failed to set the FM VSA parameters. Please check the input parameters";
case ERR_FM_GET_RX_FAILED: return "Failed to query the tester for FM VSA Parameters";
case ERR_FM_ANALYSIS_FAILED: return "FM Analysis failed";
case ERR_FM_CAPTURE_AUDIO_FAILED: return "Failed to capture Audio using AIM Device";
case ERR_FM_GENERATE_AUDIO_FAILED: return "Failed to generate Audio";
case ERR_FM_QUERY_AIM_FAILED: return "Failed to Query AIM Device";
case ERR_FM_SAVE_WAV_AUDIO_FAILED: return "Falied to Save Audio";
case ERR_FM_PLAY_AUDIO_FAILED: return "Failed to Play Audio using AIM Device";
case ERR_FM_LOAD_AUDIO_FAILED: return "Failed to Load Audio";
case ERR_FM_STOP_AUDIO_PLAY_FAILED: return "Failed to stop Audio Play";
default: return "Unknown error condition.";
}
// ::TIMER_StopTimer(timerIQmeasure, "LP_GetErrorString", &timeDuration, &timeStop);
// ::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_GetErrorString", timeDuration);
}
extern "C" __declspec(dllimport) int iqapiSetAnalysisMode(const char *lock_unlock_key); //!< Internal use only
IQMEASURE_API int SetTesterHwVersion(double hwVersion)
{
int err = ERR_OK;
g_testerHwVersion = hwVersion;
return err;
}
IQMEASURE_API int GetTesterHwVersion(double *hwVersion)
{
int err = ERR_OK;
*hwVersion = g_testerHwVersion;
return err;
}
int LP_Analyze(void)
{
int err = 0;
//::TIMER_StartTimer(timerIQmeasure, "LP_SetAnalysisMode", &timeStart);
//if ( iqapiSetAnalysisMode("UNLOCK_KEY_1147014E-95E0-440d-A752-5F7C08A2FEE9") != IQAPI_ERR_OK )
//{
// throw hndl->lastErr;
//}
//::TIMER_StopTimer(timerIQmeasure, "LP_SetAnalysisMode", &timeDuration, &timeStop);
// printf("\nTime to unlock analysis in LP_Analyze is %0.3f ms\n", timeDuration);
// g_userData takes priority
if( g_userData!=NULL )
{
err = hndl->Analyze( g_userData );
if( ERR_OK!=err )
{
err = ERR_ANALYSIS_FAILED;
}
else
{
// nothing
}
}
else if( hndl->data != NULL )
{
err = hndl->Analyze();
if( ERR_OK!=err )
{
err = ERR_ANALYSIS_FAILED;
}
else
{
// nothing
}
}
else
{
err = ERR_NO_CAPTURE_DATA;
}
//if ( iqapiSetAnalysisMode("LOCK_KEY_431A4A5B-90A1-499c-B70F-11078C7C5954") != IQAPI_ERR_OK )
//{
// throw hndl->lastErr;
//}
return err;
}
// FM Analyze hndl
int LP_Analyze_FM_Hndl(void)
{
int err = 0;
if( hndl->hndlFm->dataFm != NULL )
{
err = hndl->hndlFm->Analyze();
if( ERR_OK != err)
{
err = ERR_ANALYSIS_FAILED;
}
else
{
// nothing
}
}
else
{
err = ERR_NO_CAPTURE_DATA;
}
return err;
}
int LP_FreeMemory(void)
{
int err = 0;
::TIMER_StartTimer(timerIQmeasure, "LP_FreeMemory", &timeStart);
if (NULL != hndl) { hndl->analysis = NULL; }
if (analysis80216) {delete analysis80216; analysis80216 = NULL; }
if (analysisMimo) {delete analysisMimo; analysisMimo = NULL; }
if (analysisOfdm) {delete analysisOfdm; analysisOfdm = NULL; }
if (analysis11b) {delete analysis11b; analysis11b = NULL; }
if (analysisPowerRampOfdm) {delete analysisPowerRampOfdm; analysisPowerRampOfdm = NULL; }
if (analysisPowerRamp11b) {delete analysisPowerRamp11b; analysisPowerRamp11b = NULL; }
if (analysisCW) {delete analysisCW; analysisCW = NULL; }
if (analysisSidelobe) {delete analysisSidelobe; analysisSidelobe = NULL; }
if (analysisWave) {delete analysisWave; analysisWave = NULL;}
if (analysisCCDF) {delete analysisCCDF; analysisCCDF = NULL; }
if (analysisFFT) {delete analysisFFT; analysisFFT = NULL; }
if (analysisPower) {delete analysisPower; analysisPower = NULL; }
if (analysisBluetooth) {delete analysisBluetooth; analysisBluetooth = NULL; }
if (analysisZigbee) {delete analysisZigbee; analysisZigbee = NULL; }
#if !defined(IQAPI_1_5_X)
// iqapiResultHT40 is supported in IQapi 1.6.x and beyond
if (analysisHT40) {delete analysisHT40; analysisHT40 = NULL; }
#endif
if (analysisWifiOfdm) {delete analysisWifiOfdm; analysisWifiOfdm = NULL; }
if (analysisVHT80) {delete analysisVHT80; analysisVHT80 = NULL; }
//if (FmInitialized == true)
// if (hndl->hndlFm) {hndl->hndlFm->analysis = NULL;}
//free FM
if (analysisAudioStereo) {delete analysisAudioStereo; analysisAudioStereo = NULL; }
if (analysisAudioMono) {delete analysisAudioMono; analysisAudioMono = NULL; }
if (analysisFmAudioBase) {delete analysisFmAudioBase; analysisFmAudioBase = NULL; }
if (analysisFmRf) {delete analysisFmRf; analysisFmRf = NULL; }
if (analysisFmDemodSpectrum) {delete analysisFmDemodSpectrum; analysisFmDemodSpectrum = NULL; }
if (analysisFmMono) {delete analysisFmMono; analysisFmMono = NULL; }
if (analysisFmStereo) {delete analysisFmStereo; analysisFmStereo = NULL; }
if (analysisFmAuto) {delete analysisFmAuto; analysisFmAuto = NULL; }
if (analysisRds) {delete analysisRds; analysisRds = NULL; }
if (analysisRdsMono) {delete analysisRdsMono; analysisRdsMono = NULL; }
if (analysisRdsStereo) {delete analysisRdsStereo; analysisRdsStereo = NULL; }
if (analysisRdsAuto) {delete analysisRdsAuto; analysisRdsAuto = NULL; }
if (hndl) { delete hndl; hndl = NULL; }
::TIMER_StopTimer(timerIQmeasure, "LP_FreeMemory", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FreeMemory", timeDuration);
return err;
}
IQMEASURE_API char *LP_GetIQapiHndlLastErrMsg()
{
return hndl->lastErr;
}
IQMEASURE_API int LP_Init(int IQtype, int testControlMethod)
{
int err = ERR_OK;
string objName = "";
switch(testControlMethod) //choose tester control method
{
case 0:
g_useIQapi = true;
break;
case 1:
g_useScpi = true;
break;
default:
g_useIQapi = true;
}
FmInitialized = false;
LibsInitialized = false;
::TIMER_StartTimer(timerIQmeasure, "LP_Init", &timeStart);
if(true == g_useIQapi)
{
#ifndef WIN32
err = iqapiInit((bool)FALSE);
#else
err = iqapiInit((bool)TRUE); //to enable plotting figure in Windows
#endif
if (hndl) { delete hndl; hndl = NULL; }
hndl = new iqapiHndl();
if(err == ERR_OK)
{
LibsInitialized = true;
}
}
else if(true == g_useScpi)
{
LibsInitialized = true;
}
::TIMER_StopTimer(timerIQmeasure, "LP_Init", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_Init", timeDuration);
return err;
}
IQMEASURE_API bool LP_GetVersion(char *buffer, int buf_size)
{
bool err = true;
char ver[MAX_BUFFER_LEN], specifiedVer[MAX_BUFFER_LEN], str[MAX_BUFFER_LEN] = "IQmeasure: ";
string tmpStr1 = "", tmpStr2 = "";
//char strDelimit[] = "\r\t\n";
//char *token = NULL, *nextToken = NULL;
::TIMER_StartTimer(timerIQmeasure, "LP_GetVersion", &timeStart);
// Append the IQmeasure version
tmpStr1 = IQmeasure_Version;
tmpStr1 += " ";
tmpStr1 += SVN_REVISION;
tmpStr1 += "\n";
strcat_s(str, MAX_BUFFER_LEN, tmpStr1.c_str());
//In IQAPI 1.8.x, if use GetAllVersions, will crash while tesers >=3
//TODO:
if (hndl)
{
hndl->GetAllVersions(&ver[0], MAX_BUFFER_LEN);
}
else
{
if(LibsInitialized)
iqapiVersion(&ver[0], MAX_BUFFER_LEN);
else
/*sprintf_s(buffer, MAX_BUFFER_LEN, "LP_Dut.dll");*/
memset(buffer, '\0', buf_size);
return err;
}
//iqapiVersion(&ver[0], MAX_BUFFER_LEN);
strcat_s(str, MAX_BUFFER_LEN, ver);
strcpy_s(ver, MAX_BUFFER_LEN, "");
//Get Version:
// 1. FM Version
// 2. FPGA Version
for(int testerNumber = 1; testerNumber <= nTesters;testerNumber++)
{
hndl->GetFirmwareVersion(&ver[0], MAX_BUFFER_LEN, testerNumber);
sprintf_s(specifiedVer, "Tester %d FW:\t%s\n", testerNumber, ver);
strcat_s(str, MAX_BUFFER_LEN, specifiedVer);
strcpy_s(ver, MAX_BUFFER_LEN, "");
hndl->GetFpgaVersion(&ver[0], MAX_BUFFER_LEN, IQV_FPGA_VSA, testerNumber);
sprintf_s(specifiedVer, "Tester %d VSAFPGA:\t%s\n", testerNumber, ver);
strcat_s(str, MAX_BUFFER_LEN, specifiedVer);
strcpy_s(ver, MAX_BUFFER_LEN, "");
hndl->GetFpgaVersion(&ver[0], MAX_BUFFER_LEN, IQV_FPGA_VSG, testerNumber);
sprintf_s(specifiedVer, "Tester %d VSGFPGA:\t%s\n", testerNumber, ver);
strcat_s(str, MAX_BUFFER_LEN, specifiedVer);
strcpy_s(ver, MAX_BUFFER_LEN, "");
hndl->GetHardwareVersion(&ver[0], MAX_BUFFER_LEN, testerNumber);
//if(strlen(&ver[0])==0)strcpy_s(ver,"0.0.0.0"); // to adapt for daytona box
sprintf_s(specifiedVer, "Tester %d hardware version:\t%s\n", testerNumber, ver);
strcat_s(str, MAX_BUFFER_LEN, specifiedVer);
strcpy_s(ver, MAX_BUFFER_LEN, "");
////work around as the getallversions does not report the SN now
hndl->GetSerialNumber(&ver[0], MAX_BUFFER_LEN, testerNumber);
sprintf_s(specifiedVer, "Tester %d SN:\t%s\n", testerNumber, ver);
//sprintf_s(specifiedVer, "Tester%d SN:\t\t%s", testerNumber, ver);
strcat_s(str, MAX_BUFFER_LEN, specifiedVer);
strcpy_s(ver, MAX_BUFFER_LEN, "");
}
//For IQ201X Tester, bIQ201xFound = true , in order to set trigger type = 13.
//IQ201X Serial Number: IQP-----
tmpStr1 = str;
if(string::npos != tmpStr1.find("SN: IQP"))
{
bIQ201xFound = true;
bIQxelFound = false;
bIQxsFound = false;
}
else
{
bIQ201xFound = false;
}
//for future use.
if(string::npos != tmpStr1.find("SN: IQXS")) //Prototype tester.
{
bIQxsFound = true;
bIQxelFound = false;
bIQ201xFound = false;
}
else
{
bIQxsFound = false;
}
if(string::npos != tmpStr1.find("IQXEL") || string::npos != tmpStr1.find("DTNA") || string::npos != tmpStr1.find("IQXL")) //DTNA 11ac tester.
{
bIQxelFound = true;
bIQxsFound = false;
bIQ201xFound = false;
}
else
{
bIQxelFound = false;
}
int len = (int) strlen(str);
memset(buffer, '\0', buf_size);
if ( len > buf_size )
{
strncpy_s(buffer, buf_size, str, buf_size-1);
err = false;
}
else
{
strncpy_s(buffer, buf_size, str, len);
}
::TIMER_StopTimer(timerIQmeasure, "LP_GetVersion", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_GetVersion", timeDuration);
return err;
}
IQMEASURE_API int LP_GetIQapiHndl(void **getHndl, bool *testerInitialized)
{
*getHndl = (void *)hndl;
*testerInitialized = LibsInitialized;
return ERR_OK;
}
IQMEASURE_API int LP_Term(void)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_Term", &timeStart);
if( LibsInitialized )
{
//For dynamic-link usage, check handl is null or not
if( hndl == NULL)
{
return err;
}
else
{
//do nothing
}
hndl->analysis = NULL;
// if (hndl->ConValid()) ConValid was for IQ2010 tester, not applicable for DTNA
hndl->ConClose();
LP_FreeMemory();
nTesters = 0;
if (hndl) { delete hndl; hndl = NULL; }
/// iqapiTerm();
LibsInitialized = false;
FmInitialized = false;
}
::TIMER_StopTimer(timerIQmeasure, "LP_Term", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_Term", timeDuration);
return err;
}
IQMEASURE_API int LP_InitTester(char *ipAddress)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_InitTester", &timeStart);
if (LibsInitialized)
{
//2010-04-15: when connecting to IQ2010, ipAddress has one of the two formats:
// 1. 127.0.0.1 - connecting to the first one, or the only one IQ2010
// using port 4000
// 2. 127.0.0.1:<port_number>:<serial_number> - connecting to the IQ2010
// with specified serial_number and specified port_number
string serialNumber = "";
string ipAddressAndPort = "";
vector<string> splits;
splits.clear();
SplitString(ipAddress, splits, ":");
if( splits.size()==3 )
{
// both Serial# and Port# are specified
serialNumber = Trim( splits[2] );
ipAddressAndPort = Trim( splits[0] ) + ":" + Trim( splits[1] );
err = hndl->ConInitBySerialNumber((char*)ipAddressAndPort.c_str(), (char*)serialNumber.c_str());
}
else
{
err = hndl->ConInit(ipAddress, IQV_CONNECTION_DAYTONA);
//err = hndl->ConInit(ipAddress,IQV_CONNECTION_IQ201X);
//to do, it is a hack now, how to determine the tester/connection type?
// char ver[MAX_BUFFER_LEN];
//if ( hndl->GetSerialNumber(ver, MAX_BUFFER_LEN) != IQAPI_ERR_OK )
// throw hndl->lastErr;
//else
// printf("Serial number : %s\n", ver);
}
if ( 0 < err )
{
err = ERR_NO_CONNECTION;
}
else
{
nTesters = 1;
InstantiateAnalysisClasses();
InitializeTesterSettings();
if(NULL != hndl->hndlFm)
{
FmInitialized = true;
}
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_InitTester", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_InitTester", timeDuration);
return err;
}
IQMEASURE_API int LP_InitTester2(char *ipAddress1, char *ipAddress2)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_InitTester2", &timeStart);
if (LibsInitialized)
{
if(hndl->ConInit(ipAddress1, ipAddress2, IQV_CONNECTION_DAYTONA)) //to do, it is a hack now, how to determine the tester/connection type?
{
err = ERR_NO_CONNECTION;
}
else
{
nTesters = 2;
InstantiateAnalysisClasses();
InitializeTesterSettings();
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_InitTester2", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_InitTester2", timeDuration);
return err;
}
IQMEASURE_API int LP_InitTester3(char *ipAddress1, char *ipAddress2, char *ipAddress3)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_InitTester3", &timeStart);
if (LibsInitialized)
{
if (hndl->ConInit(ipAddress1, ipAddress2, ipAddress3, NULL, IQV_CONNECTION_DAYTONA))//to do, it is a hack now, how to determine the tester/connection type?
{
err = ERR_NO_CONNECTION;
}
else
{
nTesters = 3;
InstantiateAnalysisClasses();
InitializeTesterSettings();
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_InitTester3", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_InitTester3", timeDuration);
return err;
}
IQMEASURE_API int LP_InitTester4(char *ipAddress1, char *ipAddress2, char *ipAddress3, char *ipAddress4)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_InitTester4", &timeStart);
if (LibsInitialized)
{
if (hndl->ConInit(ipAddress1, ipAddress2, ipAddress3, ipAddress4,IQV_CONNECTION_DAYTONA))//to do, it is a hack now, how to determine the tester/connection type?
{
err = ERR_NO_CONNECTION;
}
else
{
nTesters = 4;
InstantiateAnalysisClasses();
InitializeTesterSettings();
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_InitTester4", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_InitTester4", timeDuration);
return err;
}
IQMEASURE_API int LP_ConClose(void)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_ConClose", &timeStart);
if (LibsInitialized)
{
int iqapiError = hndl->ConClose();
if (iqapiError)
{
err = ERR_GENERAL_ERR;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_ConClose", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_ConClose", timeDuration);
return err;
}
IQMEASURE_API int LP_ConOpen(void)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_ConOpen", &timeStart);
if (LibsInitialized)
{
if (hndl->ConOpen())
{
err = ERR_GENERAL_ERR;
}
else
{
}
}
else
err = ERR_NOT_INITIALIZED;
::TIMER_StopTimer(timerIQmeasure, "LP_ConOpen", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_ConOpen", timeDuration);
return err;
}
IQMEASURE_API int LP_Agc(double *rfAmplDb, bool allTesters)
{
int err = ERR_OK;
//bool setupChanged = false;
::TIMER_StartTimer(timerIQmeasure, "LP_Agc", &timeStart);
if (LibsInitialized)
{
hndl->Agc(allTesters);
*rfAmplDb = hndl->rx->vsa[0]->rfAmplDb;
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_Agc", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_Agc", timeDuration);
return err;
}
IQMEASURE_API int LP_SetFrameCnt(int frameCnt)
{
int err = ERR_OK;
//bool setupChanged = false;
::TIMER_StartTimer(timerIQmeasure, "LP_SetFrameCnt", &timeStart);
if (LibsInitialized)
{
hndl->FrameTx(frameCnt);
//TODO: to work arount the problem that TX stopped working on IQnxn after RX
g_previousOperationIsRX = true;
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_SetFrameCnt", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SetFrameCnt", timeDuration);
return err;
}
IQMEASURE_API int LP_SetDefault(void)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_SetDefault", &timeStart);
if (LibsInitialized)
{
err = hndl->SetDefault();
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_SetDefault", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SetDefault", timeDuration);
return err;
}
IQMEASURE_API int LP_ScpiCommandSet(char *scpiCommand)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_ScpiCommandSet", &timeStart);
if (LibsInitialized)
{
err = hndl->ScpiCommandSet(scpiCommand);
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_ScpiCommandSet", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_ScpiCommandSet", timeDuration);
return err;
}
IQMEASURE_API int LP_ScpiCommandQuery(char query[], unsigned int max_size, char response[], unsigned int *actual_size)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_ScpiCommandQuery", &timeStart);
if (LibsInitialized)
{
err = hndl->ScpiCommandQuery(query,max_size,response,actual_size);
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_ScpiCommandQuery", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_ScpiCommandQuery", timeDuration);
return err;
}
IQMEASURE_API int LP_TxDone(void)
{
int err = ERR_OK;
int err_code;
::TIMER_StartTimer(timerIQmeasure, "LP_TxDone", &timeStart);
if (LibsInitialized)
{
if( hndl->TxDone(&err_code) )
{
err = ERR_OK;
}
else
{
err = ERR_TX_NOT_DONE;
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_TxDone", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_TxDone", timeDuration);
return err;
}
/*! @defgroup group_vector_measurement Available Measurement Names for LP_GetStringMeasurement()
*
* Available measurement names vary for various analysis. After an analysis has been performed successfully, by calling
* one of the following functions:
* - LP_Analyze80211ag();
* - LP_AnalyzeMimo();
* - LP_Analyze80211b();
* - LP_Analyze80216d();
* - LP_Analyze80216e();
* - LP_AnalyzePower();
* - LP_AnalyzeFFT();
* - LP_AnalyzeCCDF();
* - LP_AnalyzeCW();
* - LP_AnalysisWave();
* - LP_AnalyzeSidelobe();
* - LP_AnalyzePowerRampOFDM();
* - LP_AnalyzePowerRamp80211b();
* - LP_AnalyzeBluetooth();
* - LP_AnalyzeZigbee();
*/
IQMEASURE_API int LP_GetStringMeasurement_NoTimer(char *measurement, char bufferChar[], int bufferLength)
{
if (LibsInitialized)
{
if (!hndl->results || !bufferChar)
{
return 0;
}
else
{
//Z-99
//if (dynamic_cast<iqapiResult11ac *>(hndl->results))
if (dynamic_cast<iqapiResultWifiOfdm *>(hndl->results))
{
//Z-99
//result11ac = dynamic_cast<iqapiResult11ac *>(hndl->results);
result11ac = dynamic_cast<iqapiResultWifiOfdm *>(hndl->results);
if (!strcmp(measurement, "rateInfo_modulation"))
{
if (result11ac->rateInfo_modulation)
{
int numberOfCharToCopy = 0;
int tempLen = (int)strlen(result11ac->rateInfo_modulation);
if ( bufferLength > tempLen )
numberOfCharToCopy = tempLen;
else
numberOfCharToCopy = bufferLength-1;
strncpy_s(bufferChar, bufferLength, result11ac->rateInfo_modulation, numberOfCharToCopy);
return(numberOfCharToCopy);
}
else
{
return 0;
}
}
else if (!strcmp(measurement, "rateInfo_codingRate"))
{
if (result11ac->rateInfo_codingRate)
{
int numberOfCharToCopy = 0;
int tempLen = (int)strlen(result11ac->rateInfo_codingRate);
if ( bufferLength > tempLen )
numberOfCharToCopy = tempLen;
else
numberOfCharToCopy = bufferLength-1;
strncpy_s(bufferChar, bufferLength, result11ac->rateInfo_codingRate, numberOfCharToCopy);
return(numberOfCharToCopy);
}
else
{
return 0;
}
}
}
if (dynamic_cast<iqapiResultMimo *>(hndl->results))
{
resultMimo = dynamic_cast<iqapiResultMimo *>(hndl->results);
if (!strcmp(measurement, "rateInfo_modulation"))
{
if (resultMimo->rateInfo_modulation)
{
int numberOfCharToCopy = 0;
int tempLen = (int)strlen(resultMimo->rateInfo_modulation);
if ( bufferLength > tempLen )
numberOfCharToCopy = tempLen;
else
numberOfCharToCopy = bufferLength-1;
strncpy_s(bufferChar, bufferLength, resultMimo->rateInfo_modulation, numberOfCharToCopy);
return(numberOfCharToCopy);
}
else
{
return 0;
}
}
else if (!strcmp(measurement, "rateInfo_codingRate"))
{
if (resultMimo->rateInfo_codingRate)
{
int numberOfCharToCopy = 0;
int tempLen = (int)strlen(resultMimo->rateInfo_codingRate);
if ( bufferLength > tempLen )
numberOfCharToCopy = tempLen;
else
numberOfCharToCopy = bufferLength-1;
strncpy_s(bufferChar, bufferLength, resultMimo->rateInfo_codingRate, numberOfCharToCopy);
return(numberOfCharToCopy);
}
else
{
return 0;
}
}
}
if (dynamic_cast<iqapiResultBluetooth *>(hndl->results))
{
resultBluetooth = dynamic_cast<iqapiResultBluetooth*>(hndl->results);
if (!strcmp(measurement, "analysisType"))
{
if (resultBluetooth->analysisType)
{
int numberOfCharToCopy = 0;
int tempLen = (int)strlen(resultBluetooth->analysisType);
if ( bufferLength > tempLen )
numberOfCharToCopy = tempLen;
else
numberOfCharToCopy = bufferLength-1;
strncpy_s(bufferChar, bufferLength, resultBluetooth->analysisType, numberOfCharToCopy);
return(numberOfCharToCopy);
}
else
{
return 0;
}
}
else if (!strcmp(measurement, "versionString"))
{
if (resultBluetooth->versionString)
{
int numberOfCharToCopy = 0;
int tempLen = (int)strlen(resultBluetooth->versionString);
if ( bufferLength > tempLen )
numberOfCharToCopy = tempLen;
else
numberOfCharToCopy = bufferLength-1;
strncpy_s(bufferChar, bufferLength, resultBluetooth->versionString, numberOfCharToCopy);
return(numberOfCharToCopy);
}
else
{
return 0;
}
}
else if (!strcmp(measurement, "acpErrMsg"))
{
if (resultBluetooth->acpErrMsg)
{
int numberOfCharToCopy = 0;
int tempLen = (int)strlen(resultBluetooth->acpErrMsg);
if ( bufferLength > tempLen )
numberOfCharToCopy = tempLen;
else
numberOfCharToCopy = bufferLength-1;
strncpy_s(bufferChar, bufferLength, resultBluetooth->acpErrMsg, numberOfCharToCopy);
return(numberOfCharToCopy);
}
else
{
return 0;
}
}
else if (!strcmp(measurement, "leMsg"))
{
if (resultBluetooth->leMsg)
{
int numberOfCharToCopy = 0;
int tempLen = (int)strlen(resultBluetooth->leMsg);
if ( bufferLength > tempLen )
numberOfCharToCopy = tempLen;
else
numberOfCharToCopy = bufferLength-1;
strncpy_s(bufferChar, bufferLength, resultBluetooth->leMsg, numberOfCharToCopy);
return(numberOfCharToCopy);
}
else
{
return 0;
}
}
}
}
}
return 0;
}
// Keep this function with typo for backward compatibility
IQMEASURE_API int LP_GetStringMeasurment(char *measurement, char bufferChar[], int bufferLength)
{
return LP_GetStringMeasurement(measurement, bufferChar, bufferLength);
}
IQMEASURE_API int LP_GetStringMeasurement(char *measurement, char bufferChar[], int bufferLength)
{
::TIMER_StartTimer(timerIQmeasure, "LP_GetStringMeasurement", &timeStart);
int ret = LP_GetStringMeasurement_NoTimer(measurement, bufferChar, bufferLength);
::TIMER_StopTimer(timerIQmeasure, "LP_GetStringMeasurement", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_GetStringMeasurement", timeDuration);
return ret;
}
IQMEASURE_API int LP_EnableVsgRFNxN(int vsg1Enabled, int vsg2Enabled, int vsg3Enabled, int vsg4Enabled)
{
g_IQnxnSettings[0].vsgRFEnabled = vsg1Enabled;
g_IQnxnSettings[1].vsgRFEnabled = vsg2Enabled;
g_IQnxnSettings[2].vsgRFEnabled = vsg3Enabled;
g_IQnxnSettings[3].vsgRFEnabled = vsg4Enabled;
//Remembers NxN function is called
g_nxnFunctionCalled = true;
return LP_EnableVsgRF(vsg1Enabled);
}
IQMEASURE_API int LP_EnableVsgRF(int enabled)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_EnableVsgRF", &timeStart);
IQV_RF_ENABLE_ENUM rfEnabled;
if (LibsInitialized)
{
for(int i=0; i<nTesters; i++)
{
// For rest testers of IQnxn
if( i>0 )
{
//If NxN function is called, apply g_IQnxnSettings to testers.
//If NxN function is not called, apply 1st tester setting to all testers
if (g_nxnFunctionCalled)
{
enabled = g_IQnxnSettings[i].vsgRFEnabled;
}
else
{
//apply 1st tester setting to all testers
}
}
rfEnabled = (enabled==0?IQV_RF_DISABLED:IQV_RF_ENABLED);
if( hndl->tx->vsg[i]->enabled != rfEnabled)
{
hndl->tx->vsg[i]->enabled = rfEnabled;
if (hndl->SetTx())
{
err = ERR_SET_WAVE_FAILED;
}
else
{
hndl->tx->vsg[i]->enabled = IQV_RF_DISABLED;
}
//if (hndl->SetTxRx())
//{
// err = ERR_SET_WAVE_FAILED;
//}
}
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
//After dealing with NxN function, restore g_nxnFunctionCalled to false
g_nxnFunctionCalled = false;
::TIMER_StopTimer(timerIQmeasure, "LP_EnableVsgRF", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_EnableVsgRF", timeDuration);
return err;
}
IQMEASURE_API int LP_EnableSpecifiedVsgRF(int enabled, int vsgNumber)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_EnableSpecifiedVsgRF", &timeStart);
IQV_RF_ENABLE_ENUM rfEnabled = (enabled==0?IQV_RF_DISABLED:IQV_RF_ENABLED);
if (LibsInitialized)
{
hndl->tx->vsg[vsgNumber]->enabled = rfEnabled;
if (hndl->SetTx())
{
err = ERR_SET_WAVE_FAILED;
}
else
{
err = ERR_OK;
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_EnableSpecifiedVsgRF", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_EnableSpecifiedVsgRF", timeDuration);
return err;
}
IQMEASURE_API int LP_EnableSpecifiedVsaRF(int enabled, int vsaNumber)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_EnableSpecifiedVsaRF", &timeStart);
IQV_RF_ENABLE_ENUM rfEnabled = (enabled==0?IQV_RF_DISABLED:IQV_RF_ENABLED);
if (LibsInitialized)
{
hndl->rx->vsa[vsaNumber]->enabled = rfEnabled;
if (hndl->SetRx())
{
err = ERR_SET_WAVE_FAILED;
}
else
{
err = ERR_OK;
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_EnableSpecifiedVsaRF", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_EnableSpecifiedVsaRF", timeDuration);
return err;
}
IQMEASURE_API int LP_GetVsaSettings(double *freqHz, double *ampl, IQAPI_PORT_ENUM *port, int *rfEnabled, double *triggerLevel)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_GetVsaSettings", &timeStart);
if (LibsInitialized)
{
*freqHz = hndl->rx->rfFreqHz;
*ampl = hndl->rx->vsa[0]->rfAmplDb;
if( hndl->rx->rxMode == IQV_INPUT_ADC_BB )
{
*port = PORT_BB;
}
else
{
*port = (IQAPI_PORT_ENUM)hndl->rx->vsa[0]->port;
}
*rfEnabled = hndl->rx->vsa[0]->enabled;
*triggerLevel = hndl->rx->triggerLevelDb;
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_GetVsaSettings", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_GetVsaSettings", timeDuration);
return err;
}
IQMEASURE_API int LP_SetVsgCw(double rfFreqHz, double offsetFrequencyMHz, double rfPowerLeveldBm, int port)
{
int err = ERR_OK;
bool setupChanged = false;
bool offsetChanged = false;
bool RFused = true;
::TIMER_StartTimer(timerIQmeasure, "LP_SetVsgCw", &timeStart);
if (LibsInitialized)
{
for (int i=0; i<nTesters; i++)
{
if (hndl->tx->vsg[i]->source != IQV_SOURCE_SIGNAL_GENERATOR)
{
hndl->tx->vsg[i]->source = IQV_SOURCE_SIGNAL_GENERATOR;
setupChanged = true;
}
if (hndl->tx->rfFreqHz != rfFreqHz || hndl->tx->vsg[i]->sineFreqHz!=offsetFrequencyMHz*1e6 || hndl->tx->freqShiftHz != 0 || g_bDisableFreqFilter == true)
{
hndl->tx->rfFreqHz = rfFreqHz;
hndl->rx->rfFreqHz = rfFreqHz;
hndl->tx->freqShiftHz = 0;
hndl->rx->freqShiftHz = 0;
hndl->tx->vsg[i]->sineFreqHz = offsetFrequencyMHz*1e6;
hndl->tx->sampleFreqHz = 80.0e6;
hndl->tx->modulationMode = IQV_WAVE_DL_MOD_ENABLE;
hndl->tx->gapPowerOff = IQV_DISABLE_MARKER_SIGNAL;
setupChanged = true;
g_bDisableFreqFilter = false;
}
if (RFused && hndl->tx->vsg[i]->port != (IQV_PORT_ENUM)port)
{
if ((IQV_PORT_ENUM)port == IQV_PORT_LEFT)
{
hndl->tx->vsg[i]->port = IQV_PORT_LEFT;
hndl->rx->vsa[i]->port = IQV_PORT_RIGHT;
setupChanged = true;
}
else if ((IQV_PORT_ENUM)port == IQV_PORT_RIGHT)
{
hndl->tx->vsg[i]->port = IQV_PORT_RIGHT;
hndl->rx->vsa[i]->port = IQV_PORT_LEFT;
setupChanged = true;
}
else
{
hndl->tx->vsg[i]->port = (IQV_PORT_ENUM)port;
setupChanged = true;
}
}
if(RFused)
hndl->tx->vsg[i]->rfGainDb = rfPowerLeveldBm;
else
{
hndl->tx->vsg[i]->bbGainDb = rfPowerLeveldBm;
}
hndl->tx->vsg[0]->enabled = IQV_RF_ENABLED;
setupChanged = true;
}
if (setupChanged)
{
if (hndl->SetTxRx())
err = ERR_SET_TX_FAILED;
}
// Since there is a bug inside IQapi, the CW signal always shift -1 MHz offset only.
// Or we need to set VSG twice to fix this issue.
for (int i=0; i<nTesters; i++)
{
if ( hndl->tx->vsg[i]->sineFreqHz!=offsetFrequencyMHz*1e6 )
{
hndl->tx->vsg[i]->sineFreqHz = offsetFrequencyMHz*1e6;
offsetChanged = true;
}
else
{
// do nothing
}
}
if ( offsetChanged )
{
if (hndl->SetTxRx())
err = ERR_SET_TX_FAILED;
}
else
{
// do nothing
}
}
else
err = ERR_NOT_INITIALIZED;
::TIMER_StopTimer(timerIQmeasure, "LP_SetVsgCw", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SetVsgCw", timeDuration);
return err;
}
IQMEASURE_API int LP_SetVsgNxN(double rfFreqHz, double rfPowerLeveldBm[], int port[], double dFreqShiftHz)
{
for( int i=0; i<N_MAX_TESTERS; i++)
{
g_IQnxnSettings[i].vsgPort = (IQV_PORT_ENUM)port[i];
g_IQnxnSettings[i].vsgPowerDBm = rfPowerLeveldBm[i];
}
//Remembers NxN function is called
g_nxnFunctionCalled = true;
return LP_SetVsg(rfFreqHz, rfPowerLeveldBm[0], port[0], true, dFreqShiftHz);
}
IQMEASURE_API int LP_SetVsg(double rfFreqHz, double rfPowerLeveldBm, int port, bool setGapPowerOff, double dFreqShiftHz)
{
int err = ERR_OK;
bool setupChanged = false;
bool RFused = true;
::TIMER_StartTimer(timerIQmeasure, "LP_SetVsg", &timeStart);
if (LibsInitialized)
{
if ( (hndl->tx->rfFreqHz!=rfFreqHz)||(hndl->tx->freqShiftHz!=dFreqShiftHz) || g_bDisableFreqFilter == true )
{
hndl->tx->rfFreqHz = rfFreqHz;
hndl->rx->rfFreqHz = rfFreqHz;
hndl->tx->freqShiftHz = dFreqShiftHz;
hndl->rx->freqShiftHz = dFreqShiftHz;
setupChanged = true;
g_bDisableFreqFilter = false;
}
if (hndl->tx->txMode == IQV_INPUT_MOD_DAC_BB && port != PORT_BB)
{
hndl->tx->txMode = IQV_INPUT_MOD_DAC_RF;
RFused = true;
setupChanged = true;
}
if (hndl->tx->txMode == IQV_INPUT_MOD_DAC_RF && port == PORT_BB)
{
hndl->tx->txMode = IQV_INPUT_MOD_DAC_BB;
//port = (int)PORT_RIGHT;
RFused = false;
setupChanged = true;
}
if (setGapPowerOff == true)
{
if (hndl->tx->gapPowerOff == IQV_GAP_POWER_ON)
{
hndl->tx->gapPowerOff = IQV_GAP_POWER_OFF;
setupChanged = true;
}
}
else
{
if (hndl->tx->gapPowerOff == IQV_GAP_POWER_OFF)
{
hndl->tx->gapPowerOff = IQV_GAP_POWER_ON;
setupChanged = true;
}
}
for (int i=0; i<nTesters; i++)
{
// if (hndl->tx->txMode == IQV_INPUT_MOD_DAC_BB && port != PORT_BB)
// {
// hndl->tx->txMode = IQV_INPUT_MOD_DAC_RF;
// RFused = true;
// setupChanged = true;
// }
// if (hndl->tx->txMode == IQV_INPUT_MOD_DAC_RF && port == PORT_BB)
// {
// hndl->tx->txMode = IQV_INPUT_MOD_DAC_BB;
// //port = (int)PORT_RIGHT;
// RFused = false;
// setupChanged = true;
// }
// For rest testers of IQnxn
if( i>0 )
{
//If NxN function is called, apply g_IQnxnSettings to testers.
//If NxN function is not called, apply 1st tester setting to all testers
if(g_nxnFunctionCalled)
{
port = g_IQnxnSettings[i].vsgPort;
rfPowerLeveldBm = g_IQnxnSettings[i].vsgPowerDBm;
}
else
{
//apply 1st tester setting to all testers
}
}
if( VERY_LOW_VSG_POWER_DBM < rfPowerLeveldBm )
{
if(hndl->tx->vsg[i]->enabled != (IQV_RF_ENABLE_ENUM)IQV_RF_ENABLED)
{
hndl->tx->vsg[i]->enabled = IQV_RF_ENABLED;
setupChanged = true;
}
}
else
{
if (hndl->tx->vsg[i]->enabled != (IQV_RF_ENABLE_ENUM)IQV_RF_DISABLED)
{
hndl->tx->vsg[i]->enabled = IQV_RF_DISABLED;
setupChanged = true;
}
else
{
//do nothing
}
}
if (RFused && hndl->tx->vsg[i]->port != (IQV_PORT_ENUM)port)
{
if ((IQV_PORT_ENUM)port == IQV_PORT_LEFT)
{
hndl->tx->vsg[i]->port = IQV_PORT_LEFT;
hndl->rx->vsa[i]->port = IQV_PORT_RIGHT;
setupChanged = true;
}
else if ((IQV_PORT_ENUM)port == IQV_PORT_RIGHT)
{
hndl->tx->vsg[i]->port = IQV_PORT_RIGHT;
hndl->rx->vsa[i]->port = IQV_PORT_LEFT;
setupChanged = true;
}
else
{
hndl->tx->vsg[i]->port = (IQV_PORT_ENUM)port;
setupChanged = true;
}
}
if (hndl->tx->vsg[i]->rfGainDb != rfPowerLeveldBm)
{
if(RFused)
hndl->tx->vsg[i]->rfGainDb = rfPowerLeveldBm;
else
hndl->tx->vsg[i]->bbGainDb = rfPowerLeveldBm;
setupChanged = true;
}
}
if (setupChanged)
{
if (hndl->SetTxRx())
{
err = ERR_SET_TX_FAILED;
throw hndl->lastErr; //Zhiyong debug here
}
}
}
else
err = ERR_NOT_INITIALIZED;
//After dealing with NxN function, restore g_nxnFunctionCalled to false
g_nxnFunctionCalled = false;
::TIMER_StopTimer(timerIQmeasure, "LP_SetVsg", &timeDuration, &timeStop);
char temp[MAX_BUFFER_SIZE];
sprintf_s(temp, "LP_SetVsg %4.0f %6.2f", rfFreqHz/1e6, rfPowerLeveldBm);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", temp, timeDuration);
return err;
}
IQMEASURE_API int LP_SetVsg_triggerType(double rfFreqHz, double rfPowerLeveldBm, int port, int triggerType)
{
int err = ERR_OK;
bool setupChanged = false;
bool RFused = true;
::TIMER_StartTimer(timerIQmeasure, "LP_SetVsg", &timeStart);
if (LibsInitialized)
{
if ( (hndl->tx->rfFreqHz!=rfFreqHz)||(hndl->tx->freqShiftHz!=0) || g_bDisableFreqFilter == true)
{
hndl->tx->rfFreqHz = rfFreqHz;
hndl->rx->rfFreqHz = rfFreqHz;
hndl->tx->freqShiftHz = 0;
hndl->rx->freqShiftHz = 0;
setupChanged = true;
g_bDisableFreqFilter = false;
}
if (hndl->tx->txMode == IQV_INPUT_MOD_DAC_BB && port != PORT_BB)
{
hndl->tx->txMode = IQV_INPUT_MOD_DAC_RF;
RFused = true;
setupChanged = true;
}
if (hndl->tx->txMode == IQV_INPUT_MOD_DAC_RF && port == PORT_BB)
{
hndl->tx->txMode = IQV_INPUT_MOD_DAC_BB;
//port = (int)PORT_RIGHT;
RFused = false;
setupChanged = true;
}
if (hndl->tx->gapPowerOff == IQV_GAP_POWER_ON)
{
hndl->tx->gapPowerOff = IQV_GAP_POWER_OFF;
setupChanged = true;
}
if(hndl->tx->triggerType != (IQV_VSG_TRIG)triggerType)
{
hndl->tx->triggerType = (IQV_VSG_TRIG)triggerType;
setupChanged = true;
}
for (int i=0; i<nTesters; i++)
{
// if (hndl->tx->txMode == IQV_INPUT_MOD_DAC_BB && port != PORT_BB)
// {
// hndl->tx->txMode = IQV_INPUT_MOD_DAC_RF;
// RFused = true;
// setupChanged = true;
// }
// if (hndl->tx->txMode == IQV_INPUT_MOD_DAC_RF && port == PORT_BB)
// {
// hndl->tx->txMode = IQV_INPUT_MOD_DAC_BB;
// //port = (int)PORT_RIGHT;
// RFused = false;
// setupChanged = true;
// }
// For rest testers of IQnxn
if( i>0 )
{
//If NxN function is called, apply g_IQnxnSettings to testers.
//If NxN function is not called, apply 1st tester setting to all testers
if(g_nxnFunctionCalled)
{
port = g_IQnxnSettings[i].vsgPort;
rfPowerLeveldBm = g_IQnxnSettings[i].vsgPowerDBm;
}
else
{
//apply 1st tester setting to all testers
}
}
if( VERY_LOW_VSG_POWER_DBM < rfPowerLeveldBm )
{
if(hndl->tx->vsg[i]->enabled != (IQV_RF_ENABLE_ENUM)IQV_RF_ENABLED)
{
hndl->tx->vsg[i]->enabled = IQV_RF_ENABLED;
setupChanged = true;
}
}
else
{
if (hndl->tx->vsg[i]->enabled != (IQV_RF_ENABLE_ENUM)IQV_RF_DISABLED)
{
hndl->tx->vsg[i]->enabled = IQV_RF_DISABLED;
setupChanged = true;
}
else
{
//do nothing
}
}
if (RFused && hndl->tx->vsg[i]->port != (IQV_PORT_ENUM)port)
{
if ((IQV_PORT_ENUM)port == IQV_PORT_LEFT)
{
hndl->tx->vsg[i]->port = IQV_PORT_LEFT;
hndl->rx->vsa[i]->port = IQV_PORT_RIGHT;
setupChanged = true;
}
else if ((IQV_PORT_ENUM)port == IQV_PORT_RIGHT)
{
hndl->tx->vsg[i]->port = IQV_PORT_RIGHT;
hndl->rx->vsa[i]->port = IQV_PORT_LEFT;
setupChanged = true;
}
else
{
hndl->tx->vsg[i]->port = (IQV_PORT_ENUM)port;
setupChanged = true;
}
}
if (hndl->tx->vsg[i]->rfGainDb != rfPowerLeveldBm)
{
if(RFused)
hndl->tx->vsg[i]->rfGainDb = rfPowerLeveldBm;
else
hndl->tx->vsg[i]->bbGainDb = rfPowerLeveldBm;
setupChanged = true;
}
}
if (setupChanged)
{
if (hndl->SetTxRx())
err = ERR_SET_TX_FAILED;
}
}
else
err = ERR_NOT_INITIALIZED;
//After dealing with NxN function, restore g_nxnFunctionCalled to false
g_nxnFunctionCalled = false;
::TIMER_StopTimer(timerIQmeasure, "LP_SetVsg", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SetVsg", timeDuration);
return err;
}
IQMEASURE_API int LP_SetVsg_GapPower(double rfFreqHz, double rfPowerLeveldBm, int port, int gapPowerOff)
{
int err = ERR_OK;
bool setupChanged = false;
bool RFused = true;
::TIMER_StartTimer(timerIQmeasure, "LP_SetVsg", &timeStart);
if (LibsInitialized)
{
if ( (hndl->tx->rfFreqHz!=rfFreqHz)||(hndl->tx->freqShiftHz!=0)||g_bDisableFreqFilter == true )
{
hndl->tx->rfFreqHz = rfFreqHz;
hndl->rx->rfFreqHz = rfFreqHz;
hndl->tx->freqShiftHz = 0;
hndl->rx->freqShiftHz = 0;
setupChanged = true;
g_bDisableFreqFilter = false;
}
if (hndl->tx->txMode == IQV_INPUT_MOD_DAC_BB && port != PORT_BB)
{
hndl->tx->txMode = IQV_INPUT_MOD_DAC_RF;
RFused = true;
setupChanged = true;
}
if (hndl->tx->txMode == IQV_INPUT_MOD_DAC_RF && port == PORT_BB)
{
hndl->tx->txMode = IQV_INPUT_MOD_DAC_BB;
//port = (int)PORT_RIGHT;
RFused = false;
setupChanged = true;
}
if(IQV_GAP_POWER_ON == (IQV_GAP_POWER)gapPowerOff)
{
if (hndl->tx->gapPowerOff == IQV_GAP_POWER_ON)
{
//do nothing
setupChanged = false;
}
else
{
hndl->tx->gapPowerOff = IQV_GAP_POWER_ON;
setupChanged = true;
}
}
else
{
if (hndl->tx->gapPowerOff == IQV_GAP_POWER_ON)
{
hndl->tx->gapPowerOff = IQV_GAP_POWER_OFF;
setupChanged = true;
}
else
{
//do nothing
setupChanged = false;
}
}
for (int i=0; i<nTesters; i++)
{
// if (hndl->tx->txMode == IQV_INPUT_MOD_DAC_BB && port != PORT_BB)
// {
// hndl->tx->txMode = IQV_INPUT_MOD_DAC_RF;
// RFused = true;
// setupChanged = true;
// }
// if (hndl->tx->txMode == IQV_INPUT_MOD_DAC_RF && port == PORT_BB)
// {
// hndl->tx->txMode = IQV_INPUT_MOD_DAC_BB;
// //port = (int)PORT_RIGHT;
// RFused = false;
// setupChanged = true;
// }
// For rest testers of IQnxn
if( i>0 )
{
//If NxN function is called, apply g_IQnxnSettings to testers.
//If NxN function is not called, apply 1st tester setting to all testers
if(g_nxnFunctionCalled)
{
port = g_IQnxnSettings[i].vsgPort;
rfPowerLeveldBm = g_IQnxnSettings[i].vsgPowerDBm;
}
else
{
//apply 1st tester setting to all testers
}
}
if( VERY_LOW_VSG_POWER_DBM < rfPowerLeveldBm )
{
if(hndl->tx->vsg[i]->enabled != (IQV_RF_ENABLE_ENUM)IQV_RF_ENABLED)
{
hndl->tx->vsg[i]->enabled = IQV_RF_ENABLED;
setupChanged = true;
}
}
else
{
if (hndl->tx->vsg[i]->enabled != (IQV_RF_ENABLE_ENUM)IQV_RF_DISABLED)
{
hndl->tx->vsg[i]->enabled = IQV_RF_DISABLED;
setupChanged = true;
}
else
{
//do nothing
}
}
if (RFused && hndl->tx->vsg[i]->port != (IQV_PORT_ENUM)port)
{
if ((IQV_PORT_ENUM)port == IQV_PORT_LEFT)
{
hndl->tx->vsg[i]->port = IQV_PORT_LEFT;
hndl->rx->vsa[i]->port = IQV_PORT_RIGHT;
setupChanged = true;
}
else if ((IQV_PORT_ENUM)port == IQV_PORT_RIGHT)
{
hndl->tx->vsg[i]->port = IQV_PORT_RIGHT;
hndl->rx->vsa[i]->port = IQV_PORT_LEFT;
setupChanged = true;
}
else
{
hndl->tx->vsg[i]->port = (IQV_PORT_ENUM)port;
setupChanged = true;
}
}
if (hndl->tx->vsg[i]->rfGainDb != rfPowerLeveldBm)
{
if(RFused)
hndl->tx->vsg[i]->rfGainDb = rfPowerLeveldBm;
else
hndl->tx->vsg[i]->bbGainDb = rfPowerLeveldBm;
setupChanged = true;
}
}
if (setupChanged)
{
if (hndl->SetTxRx())
err = ERR_SET_TX_FAILED;
}
}
else
err = ERR_NOT_INITIALIZED;
//After dealing with NxN function, restore g_nxnFunctionCalled to false
g_nxnFunctionCalled = false;
::TIMER_StopTimer(timerIQmeasure, "LP_SetVsg", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SetVsg", timeDuration);
return err;
}
IQMEASURE_API int LP_SetVsgModulation(char *modFileName, int loadInternalWaveform)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_SetVsgModulation", &timeStart);
//change file extension from .mod to .iqvsg
char *pch = NULL;
pch = strstr(modFileName,".mod\0");
if(pch!= NULL)
strncpy (pch,".iqvsg\0",7);
if (LibsInitialized)
{
if(loadInternalWaveform == 0)
{
if (hndl->SetWave(modFileName))
{
err = ERR_SET_WAVE_FAILED;
//throw hndl->lastErr; //Zhiyong debug
}
else
{
// Mark as single MOD file mod
g_vsgMode = ::VSG_SINGLE_MOD_FILE;
}
}
else
{
if (hndl->SetWaveScpi(modFileName))
{
err = ERR_SET_WAVE_FAILED;
//throw hndl->lastErr; //Zhiyong debug
}
else
{
// Mark as single MOD file mod
g_vsgMode = ::VSG_SINGLE_MOD_FILE;
}
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_SetVsgModulation", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SetVsgModulation", timeDuration);
return err;
}
IQMEASURE_API int LP_SetVsgModulation_SetPlayCondition(char *modFileName, bool autoPlay, int loadInternalWaveform)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_SetVsgModulation_SetPlayCondition", &timeStart);
//change file extension from .mod to .iqvsg
char *pch = NULL;
pch = strstr(modFileName,".mod\0");
if(pch!= NULL)
strncpy (pch,".iqvsg\0",7);
if (LibsInitialized)
{
if(loadInternalWaveform == 0)
{
if (hndl->SetWave(modFileName, autoPlay))
{
err = ERR_SET_WAVE_FAILED;
//throw hndl->lastErr; //Zhiyong debug
}
else
{
// Mark as single MOD file mod
g_vsgMode = ::VSG_SINGLE_MOD_FILE;
}
}
else
{
if (hndl->SetWaveScpi(modFileName, autoPlay))
{
err = ERR_SET_WAVE_FAILED;
//throw hndl->lastErr; //Zhiyong debug
}
else
{
// Mark as single MOD file mod
g_vsgMode = ::VSG_SINGLE_MOD_FILE;
}
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_SetVsgModulation_SetPlayCondition", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SetVsgModulation_SetPlayCondition", timeDuration);
return err;
}
/*! @defgroup group_analysis_name Available Analysis Name for LP_SetAnalysisParameterInteger()
*
* Available analysis name vary for various analysis. Before doing analysis action, by calling
* one of the following functions:
* - LP_AnalyzeMimo();
* - LP_Analyze80211b();
* - LP_Analyze80211ag();
* - LP_AnalyzePower();
* - LP_AnalyzeFFT();
* - LP_AnalyzeCCDF();
*
*/
IQMEASURE_API int LP_SetAnalysisParameterInteger(char *measurement, char *parameter, int value)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_SetAnalysisParameterInteger", &timeStart);
if (LibsInitialized)
{
if (NULL==analysis80216 &&
NULL==analysisMimo &&
NULL==analysisOfdm &&
NULL==analysis11b &&
NULL==analysisPowerRampOfdm &&
NULL==analysisPowerRamp11b &&
NULL==analysisCW &&
NULL==analysisWave &&
NULL==analysisSidelobe &&
NULL==analysisCCDF &&
NULL==analysisFFT &&
NULL==analysisPower &&
NULL==analysisBluetooth &&
NULL==analysisZigbee &&
NULL==analysisHT40&&
NULL==analysisWifiOfdm&& //need to implement 11AC specific parameters, might be close to MIMO
NULL==analysisVHT80)
{
err = ERR_ANALYSIS_NULL_POINTER;
}
else
{
if(!strcmp(measurement, "AnalyzePower"))
{
if(!strcmp(parameter, "vsaNum"))
{
if( (IQV_VSA_NUM_ENUM)value >= IQV_VSA_NUM_1 &&
(IQV_VSA_NUM_ENUM)value <= IQV_VSA_NUM_4)
{
analysisPower->vsaNum = (IQV_VSA_NUM_ENUM)value;
}
else
{
err = ERR_ANALYSIS_INVALID_PARAM_VALUE;
}
}
else
{
err = ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME;
}
}
else if(!strcmp(measurement, "Analyze11b"))
{
if(!strcmp(parameter, "vsaNum"))
{
if( (IQV_VSA_NUM_ENUM)value >= IQV_VSA_NUM_1 &&
(IQV_VSA_NUM_ENUM)value <= IQV_VSA_NUM_4)
{
analysis11b->vsaNum = (IQV_VSA_NUM_ENUM)value;
}
else
{
err = ERR_ANALYSIS_INVALID_PARAM_VALUE;
}
}
else
{
err = ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME;
}
}
else if(!strcmp(measurement, "AnalyzeOFDM"))
{
if(!strcmp(parameter, "vsaNum"))
{
if( (IQV_VSA_NUM_ENUM)value >= IQV_VSA_NUM_1 &&
(IQV_VSA_NUM_ENUM)value <= IQV_VSA_NUM_4)
{
analysisOfdm->vsaNum = (IQV_VSA_NUM_ENUM)value;
}
else
{
err = ERR_ANALYSIS_INVALID_PARAM_VALUE;
}
}
else
{
err = ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME;
}
}
else if(!strcmp(measurement, "AnalyzeFFT"))
{
if(!strcmp(parameter, "vsaNum"))
{
if( (IQV_VSA_NUM_ENUM)value >= IQV_VSA_NUM_1 &&
(IQV_VSA_NUM_ENUM)value <= IQV_VSA_NUM_4)
{
analysisFFT->vsaNum = (IQV_VSA_NUM_ENUM)value;
}
else
{
err = ERR_ANALYSIS_INVALID_PARAM_VALUE;
}
}
else
{
err = ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME;
}
}
//iqapiAnalysisHT40
else if(!strcmp(measurement, "AnalyzeHT40"))
{
if(!strcmp(parameter, "vsaNum"))
{
if( (IQV_VSA_NUM_ENUM)value >= IQV_VSA_NUM_1 &&
(IQV_VSA_NUM_ENUM)value <= IQV_VSA_NUM_4)
{
analysisHT40->vsaNum = (IQV_VSA_NUM_ENUM)value;
}
else
{
err = ERR_ANALYSIS_INVALID_PARAM_VALUE;
}
}
else
{
err = ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME;
}
}
//iqapiAnalysisVHT80WideBand
else if(!strcmp(measurement, "AnalyzeVHT80Mask"))
{
if(!strcmp(parameter, "vsaNum"))
{
if( (IQV_VSA_NUM_ENUM)value >= IQV_VSA_NUM_1 &&
(IQV_VSA_NUM_ENUM)value <= IQV_VSA_NUM_4)
{
analysisVHT80->vsaNum = (IQV_VSA_NUM_ENUM)value;
}
else
{
err = ERR_ANALYSIS_INVALID_PARAM_VALUE;
}
}
else
{
err = ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME;
}
}
else if(!strcmp(measurement, "AnalyzeCCDF"))
{
if(!strcmp(parameter, "vsaNum"))
{
if( (IQV_VSA_NUM_ENUM)value >= IQV_VSA_NUM_1 &&
(IQV_VSA_NUM_ENUM)value <= IQV_VSA_NUM_4)
{
analysisCCDF->vsaNum = (IQV_VSA_NUM_ENUM)value;
}
else
{
err = ERR_ANALYSIS_INVALID_PARAM_VALUE;
}
}
else
{
err = ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME;
}
}
else if(!strcmp(measurement, "Analyze80211n"))
{
if(!strcmp(parameter, "useAllSignals"))
{
if(0!= value && 1!= value)
{
err = ERR_ANALYSIS_INVALID_PARAM_VALUE;
}
else
{
analysisMimo->useAllSignals = (int)value;
}
}
else if(!strcmp(parameter, "frequencyCorr"))
{
if(2!= value && 3!= value && 4!= value)
{
err = ERR_ANALYSIS_INVALID_PARAM_VALUE;
}
else
{
analysisMimo->frequencyCorr = (int)value;
}
}
else
{
err = ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME;
}
}
else if(!strcmp(measurement, "Analyze80211ac"))
{
if(!strcmp(parameter, "useAllSignals"))
{
if(0!= value && 1!= value)
{
err = ERR_ANALYSIS_INVALID_PARAM_VALUE;
}
else
{
//temp, Z-99
//analysisWifiOfdm->useAllSignals = (int)value;
}
}
else if(!strcmp(parameter, "frequencyCorr"))
{
if(2!= value && 3!= value && 4!= value)
{
err = ERR_ANALYSIS_INVALID_PARAM_VALUE;
}
else
{
//analysis11ac->frequencyCorr = (int)value;
analysisWifiOfdm->frequencyCorr = (IQV_FREQUENCY_CORR)value;
}
}
else
{
err = ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME;
}
}
else
{
err = ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME; //??
}
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_SetAnalysisParameterInteger", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SetAnalysisParameterInteger", timeDuration);
return err;
}
/*! @defgroup group_analysis_name Available Analysis Name for LP_SetAnalysisParameterIntegerArray()
*
* Available analysis name vary for various analysis. Before doing analysis action, by calling
* one of the following functions:
* - LP_AnalyzeMimo();
* - LP_AnalyzePower();
* - LP_AnalyzeFFT();
* - LP_AnalyzeCCDF();
*
*/
IQMEASURE_API int LP_SetAnalysisParameterIntegerArray(char *measurement, char *parameter, int *value, int valuesize)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_SetAnalysisParameterIntegerArray", &timeStart);
if (LibsInitialized)
{
if (NULL==analysis80216 &&
NULL==analysisMimo &&
NULL==analysisOfdm &&
NULL==analysis11b &&
NULL==analysisPowerRampOfdm &&
NULL==analysisPowerRamp11b &&
NULL==analysisCW &&
NULL==analysisWave &&
NULL==analysisSidelobe &&
NULL==analysisCCDF &&
NULL==analysisFFT &&
NULL==analysisPower &&
NULL==analysisBluetooth &&
NULL==analysisZigbee)
{
err = ERR_ANALYSIS_NULL_POINTER;
}
else
{
if(!strcmp(measurement, "Analyze80211n"))
{
if(!strcmp(parameter, "prefOrderSignals"))
{
for(int i=0;i<valuesize;i++)
{
analysisMimo->prefOrderSignals[i] = value[i];
}
}
else
{
err = ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME;
}
}
else if(!strcmp(measurement, "Analyze80211ac"))
{
if(!strcmp(parameter, "prefOrderSignals"))
{
for(int i=0;i<valuesize;i++)
{
//temp, Z-99
//analysisWifiOfdm->prefOrderSignals[i] = value[i];
}
}
else
{
err = ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME;
}
}
else
{
err = ERR_ANALYSIS_UNSUPPORTED_PARAM_NAME; //??
}
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_SetAnalysisParameterIntegerArray", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SetAnalysisParameterIntegerArray", timeDuration);
return err;
}
IQMEASURE_API int LP_CopyVsaCaptureData(int fromVsaNum, int toVsaNum)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_CopyVsaCaptureData", &timeStart);
if (LibsInitialized)
{
if( (IQV_VSA_NUM_ENUM)fromVsaNum >= IQV_VSA_NUM_1 &&
(IQV_VSA_NUM_ENUM)fromVsaNum <= IQV_VSA_NUM_4 &&
(IQV_VSA_NUM_ENUM)toVsaNum >= IQV_VSA_NUM_1 &&
(IQV_VSA_NUM_ENUM)toVsaNum <= IQV_VSA_NUM_4)
{
if( NULL!=hndl->data &&
hndl->data->length[toVsaNum-1]>0 &&
hndl->data->length[toVsaNum-1]==hndl->data->length[fromVsaNum-1])
{
memcpy(hndl->data->real[toVsaNum-1], hndl->data->real[fromVsaNum-1], hndl->data->length[fromVsaNum-1]*sizeof(double));
}
else
{
err = ERR_NO_CAPTURE_DATA;
}
}
else
{
err = ERR_VSA_NUM_OUT_OF_RANGE;
}
}
else
err = ERR_NOT_INITIALIZED;
::TIMER_StopTimer(timerIQmeasure, "LP_CopyVsaCaptureData", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_CopyVsaCaptureData", timeDuration);
return err;
}
IQMEASURE_API int LP_SaveSignalArrays(double *real[N_MAX_TESTERS],
double *imag[N_MAX_TESTERS],
int length[N_MAX_TESTERS],
double sampleFreqHz[N_MAX_TESTERS],
char *fileNameToSave)
{
int err = ERR_OK;
iqapiCapture *capture = new iqapiCapture();
for(int i=0; i<N_MAX_TESTERS; i++)
{
capture->real[i] = real[i];
capture->imag[i] = imag[i];
capture->length[i] = length[i];
capture->sampleFreqHz[i] = sampleFreqHz[i];
}
// Just load to iqapiHandle if the file name is null
if(fileNameToSave == NULL)
{
if(hndl->data != NULL)
{
delete hndl->data;
}
hndl->data = capture;
}
// If file name is there, save it to the file
else
{
if(capture->Save(fileNameToSave))
{
err = ERR_SAVE_WAVE_FAILED;
}
}
return err;
}
IQMEASURE_API int LP_SaveIQDataToModulationFile(double *real,
double *imag,
int length[N_MAX_TESTERS],
char *modFileName,
int normalization,
int loadIQDataToVsg)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_SaveIQDataToModulationFile", &timeStart);
if (LibsInitialized)
{
// iqData is used for its SaveNormalize()
// iqWave is used for setting the IQ data to VSG memory
iqapiCapture *iqData = new iqapiCapture();
iqapiModulationWave *iqWave = new iqapiModulationWave();
int offset = 0;
for(int i=0; i<N_MAX_TESTERS; i++)
{
if(length[i]>0)
{
iqData->real[i] = real + offset;
iqData->imag[i] = imag + offset;
iqWave->real[i] = real + offset;
iqWave->imag[i] = imag + offset;
}
else
{
iqData->real[i] = NULL;
iqData->imag[i] = NULL;
iqWave->real[i] = NULL;
iqWave->imag[i] = NULL;
}
iqData->length[i] = length[i];
iqWave->length[i] = length[i];
iqData->sampleFreqHz[i] = 80e6;
iqWave->sampleFreqHz[i] = 80e6;
offset += length[i];
}
if( NULL!=modFileName && strlen(modFileName)>0 )
{
if(0==normalization)
{
err = iqData->Save( modFileName );
}
else
{
err = iqData->SaveNormalize( modFileName );
}
if(ERR_OK!=err)
{
err = ERR_SAVE_WAVE_FAILED;
}
else
{
// nothing to be done
}
}
else
{
// nothing to be done
}
if( 0!=loadIQDataToVsg )
{
err = hndl->SetWave( iqWave );
if(ERR_OK!=err)
{
err = ERR_SET_WAVE_FAILED;
}
else
{
// nothing to be done
}
}
else
{
// nothing to be done
}
// We have to set all pointers back to NULL, otherwise the destructor will try to
// free the memory which does not belong to it.
for(int i=0; i<N_MAX_TESTERS; i++)
{
iqData->real[i] = NULL;
iqData->imag[i] = NULL;
iqData->length[i] = 0;
iqWave->real[i] = NULL;
iqWave->imag[i] = NULL;
iqWave->length[i] = 0;
}
delete iqData;
delete iqWave;
iqData = NULL;
iqWave = NULL;
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_SaveIQDataToModulationFile", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SaveIQDataToModulationFile", timeDuration);
return err;
}
IQMEASURE_API int LP_SaveVsaSignalFile(char *sigFileName)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_SaveVsaSignalFile", &timeStart);
if (LibsInitialized)
{
if(NULL!=hndl->data)
{
//z-99 no data filed in IQapi now. need to improve
//if (hndl->data->Save(sigFileName))
if (hndl->SaveSignalFile(sigFileName))
err = ERR_SAVE_WAVE_FAILED;
}
else
{
err = ERR_NO_CAPTURE_DATA;
}
}
else
err = ERR_NOT_INITIALIZED;
::TIMER_StopTimer(timerIQmeasure, "LP_SaveVsaSignalFile", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SaveVsaSignalFile", timeDuration);
return err;
}
IQMEASURE_API int LP_SaveVsaSignalFileText(char *txtFileName)
{
int err = ERR_OK;
char tmpbuff[MAX_PATH];
FILE *fp;
TIMER_StartTimer(timerIQmeasure, "LP_SaveVsaSignalFileText", &timeStart);
if (LibsInitialized)
{
if(NULL!=hndl->data)
{
sprintf_s(tmpbuff, MAX_PATH, "%s", txtFileName);
err = fopen_s(&fp, tmpbuff, "w");
if (err == 0)
{
for(int i = 0; i < hndl->data->length[0]; i++)
{
fprintf(fp, "%15e %15e\n", hndl->data->real[0][i], hndl->data->imag[0][i]); // print to debug log file
}
fclose(fp);
}
else
{
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_ERROR, "[IQMEASURE],[%s],\nfopen_s \"%s\" erred with code: %i\n", "LP_SaveVsaSignalFileText", tmpbuff, err);
err = ERR_SAVE_WAVE_FAILED;
}
}
else
{
err = ERR_NO_CAPTURE_DATA;
}
}
else
err = ERR_NOT_INITIALIZED;
::TIMER_StopTimer(timerIQmeasure, "LP_SaveVsaSignalFileText", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SaveVsaSignalFileText", timeDuration);
return err;
}
IQMEASURE_API int LP_PlotDataCapture()
{
int err = ERR_OK;
int i;
::TIMER_StartTimer(timerIQmeasure, "LP_PlotDataCapture", &timeStart);
if (LibsInitialized)
{
for(i=0; i<hndl->nTesters; i++)
{
hndl->data->PlotPower(i+1, "", i);
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_PlotDataCapture", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_PlotDataCapture", timeDuration);
return err;
}
IQMEASURE_API int LP_Plot(int figNum, double *x, double *y, int length, char *plotArgs, char *title, char *xtitle, char *ytitle, int keepPlot)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_Plot", &timeStart);
if (LibsInitialized)
{
iqapiPlot(figNum, x, y, length, plotArgs, title, xtitle, ytitle, keepPlot);
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_Plot", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_Plot", timeDuration);
return err;
}
IQMEASURE_API int LP_SaveVsaGeneratorFile(char *modFileName)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_SaveVsaGeneratorFile", &timeStart);
if (LibsInitialized)
{
if (hndl->data->SaveNormalize(modFileName))
err = ERR_SAVE_WAVE_FAILED;
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_SaveVsaGeneratorFile", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SaveVsaGeneratorFile", timeDuration);
return err;
}
IQMEASURE_API int LP_LoadVsaSignalFile(char *sigFileName)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_LoadVsaSignalFile", &timeStart);
if (LibsInitialized)
{
if (hndl->LoadSignalFile(sigFileName))
err = ERR_LOAD_WAVE_FAILED;
//either work around or change the structure of IQmeasure, don't check data length anymore, put weird value to stand out from now capture, Z-99
else
{
hndl->data->length[0]=99;
hndl->data->length[1]=99;
hndl->data->length[2]=99;
hndl->data->length[3]=99;
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_LoadVsaSignalFile", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_LoadVsaSignalFile", timeDuration);
return err;
}
IQMEASURE_API int LP_SetVsaBluetooth(double rfFreqHz, double rfAmplDb, int port, double triggerLevelDb, double triggerPreTime)
{
int err = ERR_OK;
bool setupChanged = false;
bool RFused = true;
double extAttenDb = 0;
::TIMER_StartTimer(timerIQmeasure, "LP_SetVsaBluetooth", &timeStart);
if (LibsInitialized)
{
if (hndl->rx->rfFreqHz != (rfFreqHz+BT_SHIFT_HZ) || (hndl->tx->rfFreqHz != (rfFreqHz + BT_SHIFT_HZ))
|| (hndl->rx->freqShiftHz != BT_SHIFT_HZ) || (hndl->tx->freqShiftHz != -BT_SHIFT_HZ)
|| g_bDisableFreqFilter == true )
{
hndl->rx->rfFreqHz = rfFreqHz + BT_SHIFT_HZ;
hndl->tx->rfFreqHz = rfFreqHz + BT_SHIFT_HZ;
hndl->rx->freqShiftHz = BT_SHIFT_HZ;
hndl->tx->freqShiftHz = -BT_SHIFT_HZ;
//hndl->rx->rfFreqHz = rfFreqHz;
//hndl->tx->rfFreqHz = rfFreqHz;
//hndl->rx->freqShiftHz = 0;
//hndl->tx->freqShiftHz = 0;
setupChanged = true;
g_bDisableFreqFilter = false;
}
if (hndl->rx->triggerPreTime != triggerPreTime)
{
hndl->rx->triggerPreTime = triggerPreTime;
setupChanged = true;
}
if (hndl->rx->triggerLevelDb != triggerLevelDb)
{
hndl->rx->triggerLevelDb = triggerLevelDb;
setupChanged = true;
}
if (hndl->rx->rxMode == IQV_INPUT_ADC_BB && port != PORT_BB)
{
hndl->rx->rxMode = IQV_INPUT_ADC_RF;
RFused = true;
setupChanged = true;
}
if (hndl->rx->rxMode != IQV_INPUT_ADC_BB && port == PORT_BB)
{
hndl->rx->rxMode = IQV_INPUT_ADC_BB;
// port = (int)PORT_LEFT;
RFused = false;
setupChanged = true;
}
for (int i=0; i<nTesters; i++)
{
// if (hndl->rx->rxMode == IQV_INPUT_ADC_BB && port != PORT_BB)
// {
// hndl->rx->rxMode = IQV_INPUT_ADC_RF;
// RFused = true;
// setupChanged = true;
// }
// if (hndl->rx->rxMode != IQV_INPUT_ADC_BB && port == PORT_BB)
// {
// hndl->rx->rxMode = IQV_INPUT_ADC_BB;
// port = (int)PORT_LEFT;
// RFused = false;
// setupChanged = true;
// }
if (RFused && hndl->rx->vsa[i]->port != (IQV_PORT_ENUM)port)
{
if ((IQV_PORT_ENUM)port == IQV_PORT_LEFT)
{
hndl->rx->vsa[i]->port = IQV_PORT_LEFT;
hndl->tx->vsg[i]->port = IQV_PORT_RIGHT;
setupChanged = true;
}
else if ((IQV_PORT_ENUM)port == IQV_PORT_RIGHT)
{
hndl->rx->vsa[i]->port = IQV_PORT_RIGHT;
hndl->tx->vsg[i]->port = IQV_PORT_LEFT;
setupChanged = true;
}
else
{
hndl->rx->vsa[i]->port = (IQV_PORT_ENUM)port;
setupChanged = true;
}
}
if (hndl->rx->vsa[i]->extAttenDb != extAttenDb)
{
hndl->rx->vsa[i]->extAttenDb = extAttenDb;
setupChanged = true;
}
// Workaround due to IQxel can not set reference level lower than -20 dBm
if (rfAmplDb < -20)
rfAmplDb = -20;
if ( abs(hndl->rx->vsa[i]->rfAmplDb-rfAmplDb)>abs(g_amplitudeToleranceDb) )
//if (hndl->rx->vsa[i]->rfAmplDb != rfAmplDb)
{
if(RFused)
hndl->rx->vsa[i]->rfAmplDb = rfAmplDb;
else
{
hndl->rx->vsa[i]->bbAmplDbv = rfAmplDb;
hndl->rx->vsa[i]->bbGainDb = -1 * rfAmplDb;
}
setupChanged = true;
}
}
if (setupChanged)
{
if (hndl->SetTxRx())
err = ERR_SET_RX_FAILED;
}
}
else
err = ERR_NOT_INITIALIZED;
::TIMER_StopTimer(timerIQmeasure, "LP_SetVsaBluetooth", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SetVsaBluetooth", timeDuration);
return err;
}
IQMEASURE_API int LP_SetVsaNxN(double rfFreqHz,
double rfAmplDb[],
int port[],
double extAttenDb,
double triggerLevelDb,
double triggerPreTime,
double dFreqShiftHz)
{
for( int i=0; i<N_MAX_TESTERS; i++)
{
g_IQnxnSettings[i].vsaAmplDBm = rfAmplDb[i];
g_IQnxnSettings[i].vsaPort = (IQV_PORT_ENUM)port[i];
}
//Remembers NxN function is called
g_nxnFunctionCalled = true;
return LP_SetVsa(rfFreqHz, rfAmplDb[0], port[0], extAttenDb, triggerLevelDb, triggerPreTime, dFreqShiftHz);
}
IQMEASURE_API int LP_SetVsa(double rfFreqHz, double rfAmplDb, int port, double extAttenDb, double triggerLevelDb, double triggerPreTime, double dFreqShiftHz)
{
int err = ERR_OK;
bool setupChanged = false;
bool RFused = true;
::TIMER_StartTimer(timerIQmeasure, "LP_SetVsa", &timeStart);
if (LibsInitialized)
{
if( g_previousOperationIsRX && nTesters>1 && bIQxsFound == false && bIQxelFound == false )
{
//TODO: this is to work around the problem on IQnxn that TX stops working after RX
hndl->SetDefault();
g_previousOperationIsRX = false;
}
if ( (hndl->rx->rfFreqHz!=rfFreqHz)||(hndl->rx->freqShiftHz!=dFreqShiftHz)||(hndl->tx->rfFreqHz!=rfFreqHz) || g_bDisableFreqFilter == true)
{
hndl->rx->rfFreqHz = rfFreqHz;
hndl->tx->rfFreqHz = rfFreqHz;
hndl->rx->freqShiftHz = dFreqShiftHz;
hndl->tx->freqShiftHz = dFreqShiftHz;
setupChanged = true;
g_bDisableFreqFilter = false;
}
if (hndl->rx->triggerPreTime != triggerPreTime)
{
hndl->rx->triggerPreTime = triggerPreTime;
setupChanged = true;
}
if (hndl->rx->triggerLevelDb != triggerLevelDb)
{
hndl->rx->triggerLevelDb = triggerLevelDb;
setupChanged = true;
}
if (hndl->rx->rxMode == IQV_INPUT_ADC_BB && port != PORT_BB)
{
hndl->rx->rxMode = IQV_INPUT_ADC_RF;
RFused = true;
setupChanged = true;
}
if (hndl->rx->rxMode != IQV_INPUT_ADC_BB && port == PORT_BB)
{
hndl->rx->rxMode = IQV_INPUT_ADC_BB;
// port = (int)PORT_LEFT;
RFused = false;
setupChanged = true;
}
for (int i=0; i<nTesters; i++)
{
// if (hndl->rx->rxMode == IQV_INPUT_ADC_BB && port != PORT_BB)
// {
// hndl->rx->rxMode = IQV_INPUT_ADC_RF;
// RFused = true;
// setupChanged = true;
// }
// if (hndl->rx->rxMode != IQV_INPUT_ADC_BB && port == PORT_BB)
// {
// hndl->rx->rxMode = IQV_INPUT_ADC_BB;
// port = (int)PORT_LEFT;
// RFused = false;
// setupChanged = true;
// }
// For rest testers of IQnxn
if( i>0 )
{
//If NxN function is called, apply g_IQnxnSettings to testers.
//If NxN function is not called, apply 1st tester setting to all testers
if(g_nxnFunctionCalled)
{
port = g_IQnxnSettings[i].vsaPort;
rfAmplDb = g_IQnxnSettings[i].vsaAmplDBm;
}
else
{
//apply 1st tester setting to all testers
}
}
if (RFused && hndl->rx->vsa[i]->port != (IQV_PORT_ENUM)port)
{
if ((IQV_PORT_ENUM)port == IQV_PORT_LEFT)
{
hndl->rx->vsa[i]->port = IQV_PORT_LEFT;
hndl->tx->vsg[i]->port = IQV_PORT_RIGHT;
setupChanged = true;
}
else if ((IQV_PORT_ENUM)port == IQV_PORT_RIGHT)
{
hndl->rx->vsa[i]->port = IQV_PORT_RIGHT;
hndl->tx->vsg[i]->port = IQV_PORT_LEFT;
setupChanged = true;
}
else
{
hndl->rx->vsa[i]->port = (IQV_PORT_ENUM)port;
setupChanged = true;
}
}
if (hndl->rx->vsa[i]->extAttenDb != extAttenDb)
{
hndl->rx->vsa[i]->extAttenDb = extAttenDb;
setupChanged = true;
}
bool rfAmplChanged = false;
// Workaround due to IQxel can not set reference level lower than -20 dBm
if (rfAmplDb < -20)
rfAmplDb = -20;
if (g_amplitudeToleranceDb>=0)
{
if (hndl->rx->vsa[i]->rfAmplDb-rfAmplDb > g_amplitudeToleranceDb || hndl->rx->vsa[i]->rfAmplDb < rfAmplDb )
{
rfAmplChanged = true;
}else
{
rfAmplChanged = false;
}
}else //this should not happen but our software allow customer to enter negative values
{
if (hndl->rx->vsa[i]->rfAmplDb-rfAmplDb < g_amplitudeToleranceDb || hndl->rx->vsa[i]->rfAmplDb > rfAmplDb )
{
rfAmplChanged = true;
}else
{
rfAmplChanged = false;
}
}
if (true == rfAmplChanged)
{
if(RFused)
hndl->rx->vsa[i]->rfAmplDb = rfAmplDb;
else
{
hndl->rx->vsa[i]->bbAmplDbv = rfAmplDb;
hndl->rx->vsa[i]->bbGainDb = -1 * rfAmplDb;
}
setupChanged = true;
}
// hndl->tx->vsg[i]->source = IQV_SOURCE_WAVE;
}
if (setupChanged)
{
if (hndl->SetTxRx())
{
err = ERR_SET_RX_FAILED;
//throw hndl->lastErr;
}
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
//After dealing with NxN function, restore g_nxnFunctionCalled to false
g_nxnFunctionCalled = false;
::TIMER_StopTimer(timerIQmeasure, "LP_SetVsa", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SetVsa", timeDuration);
return err;
}
IQMEASURE_API int LP_SetVsaTriggerTimeout(double triggerTimeoutSec)
{
int err = ERR_OK;
TIMER_StartTimer(timerIQmeasure, "LP_SetVsaTriggerTimeout", &timeStart);
if (LibsInitialized)
{
hndl->rx->triggerTimeOut = triggerTimeoutSec;
if (hndl->SetTxRx())
{
err = ERR_SET_RX_FAILED;
}
else
{
err = ERR_OK;
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_SetVsaTriggerTimeout", &timeDuration, &timeStop);
return err;
}
IQMEASURE_API int LP_SetVsaAmplitudeTolerance(double amplitudeToleranceDb)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_SetVsaAmplitudeTolerance", &timeStart);
g_amplitudeToleranceDb = amplitudeToleranceDb;
::TIMER_StopTimer(timerIQmeasure, "LP_SetVsaAmplitudeTolerance", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SetVsaAmplitudeTolerance", timeDuration);
return err;
}
IQMEASURE_API int LP_VsaDataCapture(double samplingTimeSecs, int triggerType, double sampleFreqHz,
int captureType,IQMEASURE_CAPTURE_NONBLOCKING_STATES nonBlockingState)
{
//ht40Mode meaning is changed as VHT80, VHT160 and CVHT80 mode is added.
int err = ERR_OK;
bool setupChanged = false;
int finalTriggerType = 0;
::TIMER_StartTimer(timerIQmeasure, "LP_VsaDataCapture", &timeStart);
//might need to specify the right one for bIQxsFound in the future.
/* if (triggerType == IQV_TRIG_TYPE_IF2_NO_CAL && bIQ201xFound == true) // if it is a IQ201x, then use IQ201x trigger
{
finalTriggerType = IQV_TRIG_TYPE_FOR_IQ2010_DIG;
}
else if (triggerType == IQV_TRIG_TYPE_FOR_IQ2010_DIG && bIQ201xFound == false) // if it is not a 201x, then use back IQview trigger
{
finalTriggerType = IQV_TRIG_TYPE_IF2_NO_CAL;
}
else
{
finalTriggerType = triggerType;
}*/
//Tracy Yu; 2012-03-22; For IQXel capture
if (triggerType == IQV_TRIG_TYPE_IF2_NO_CAL && (bIQ201xFound == true || bIQxelFound == true)) // if it is a IQ201x, then use IQ201x trigger
{
finalTriggerType = IQV_TRIG_TYPE_FOR_IQ2010_DIG;
}
else if (triggerType == IQV_TRIG_TYPE_FOR_IQ2010_DIG && bIQ201xFound == false && bIQxelFound == false) // if it is not a 201x, then use back IQview trigger
{
finalTriggerType = IQV_TRIG_TYPE_IF2_NO_CAL;
}
else
{
finalTriggerType = triggerType;
}
if ( LibsInitialized )
{
// This capture uses hndl->data
if (hndl->rx->samplingTimeSecs != samplingTimeSecs)
{
hndl->rx->samplingTimeSecs = samplingTimeSecs;
setupChanged = true;
}
if (hndl->rx->triggerType != (IQV_TRIG_TYPE_ENUM)finalTriggerType)
{
hndl->rx->triggerType = (IQV_TRIG_TYPE_ENUM)finalTriggerType;
setupChanged = true;
}
//work around to handle 80MHz sampling rate.
//force the sampling frequency to the right one in HT40 wideband to make sure that backward compatible.
/*if( IQV_HT_40_CAPTURE_TYPE==captureType ||IQV_HT_40_WIDE_BAND_HI_ACCURACY_CAPTURE_TYPE==captureType || IQV_HT_40_WIDE_BAND_LO_ACCURACY_CAPTURE_TYPE == captureType)
{*/
if (bIQxelFound==true )
{
sampleFreqHz=160e6;
}else if (bIQxsFound==true)
{
sampleFreqHz=150e6;
}
else
{
//do nothing
}
//}
if (hndl->rx->sampleFreqHz != sampleFreqHz)
{
hndl->rx->sampleFreqHz = sampleFreqHz;
setupChanged = true;
}
if (setupChanged)
{
if (hndl->SetTxRx())
err = ERR_SET_TX_FAILED;
}
if(hndl->GetCaptureDataHandling()!=IQV_DATA_IN_IQAPI) //there should be a smarter way to do this, revisit this later Z-99, March 23, 2012
{
hndl->SetCaptureDataHandling(IQV_DATA_IN_IQAPI);
}
// g_userData is used for selecting a portion of capture for analysis
// Any new capture will reset this variable to NULL
if( NULL!=g_userData )
{
for(int j = 0 ; j < MAX_TESTER_NUM ; j++){
g_userData->real[j] = NULL;
g_userData->imag[j] = NULL;
}
delete g_userData;
g_userData = NULL;
}
//if( ON==captureType ) //need to add support for the other capture type when it is ready.
if( IQV_HT_40_CAPTURE_TYPE==captureType )
{
if(bIQxsFound==true || bIQxelFound==true )
{
err = hndl->Capture();
}
else
{
err = hndl->Capture( IQV_HT_40_CAPTURE_TYPE );
}
}
else
{
//if (ON_VHT80 == captureType )
if (IQV_VHT_80_WIDE_BAND_CAPTURE_TYPE == captureType )
{
err = hndl->Capture(IQV_VHT_80_WIDE_BAND_CAPTURE_TYPE);
}
else
{
err = hndl->Capture();
}
}
if (0!=err)
{
err = ERR_CAPTURE_FAILED;
}
else // Copy hndl->data
{
// do nothing
}
if( IQV_HT_40_CAPTURE_TYPE==captureType || IQV_VHT_80_WIDE_BAND_CAPTURE_TYPE==captureType ) //actually all capture don't have real data field for Daytona
{
//TODO: HT40 capture does not use hndl->data
//if (!hndl->data)
// err = ERR_CAPTURE_FAILED;
//else
//{
// if (!hndl->data->length[0])
// err = ERR_CAPTURE_FAILED;
//}
}
else
{
if (!hndl->data)
err = ERR_CAPTURE_FAILED;
else
{
if (!hndl->data->length[0])
err = ERR_CAPTURE_FAILED;
}
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_VsaDataCapture", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_VsaDataCapture", timeDuration);
return err;
}
IQMEASURE_API int LP_GetSampleData(int vsaNum, double bufferReal[], double bufferImag[], int bufferLength)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_GetSampleData", &timeStart);
if (vsaNum < 0 || vsaNum > 3)
{
return ERR_VSA_NUM_OUT_OF_RANGE;
}
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[vsaNum])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
if (bufferLength > hndl->data->length[vsaNum])
bufferLength = hndl->data->length[vsaNum];
if (bufferLength >= 1)
{
memcpy(bufferReal, hndl->data->real[vsaNum], (sizeof(double)*bufferLength));
memcpy(bufferImag, hndl->data->imag[vsaNum], (sizeof(double)*bufferLength));
}
else
{
err = ERR_GENERAL_ERR;
}
}
else
err = ERR_NOT_INITIALIZED;
::TIMER_StopTimer(timerIQmeasure, "LP_GetSampleData", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_GetSampleData", timeDuration);
return err;
}
IQMEASURE_API int LP_SelectCaptureRangeForAnalysis(double startPositionUs, double lengthUs,
int packetsOffset, int packetsLength)
{
// note: packetsOffset and packetsLength are ignored for IQ2010/IQapi
int err = ERR_OK;
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
}
else
{
int j = 0;
if( NULL!=g_userData )
{
for(j = 0 ; j < MAX_TESTER_NUM ; j++){
g_userData->real[j] = NULL;
g_userData->imag[j] = NULL;
}
delete g_userData;
g_userData = NULL;
}
g_userData = new iqapiCapture();
int i = 0;
int startOffsetArray[MAX_TESTER_NUM] = {0};
int lengthArray[MAX_TESTER_NUM] = {0};
for(i = 0 ; i < MAX_TESTER_NUM ; i++){
if(!hndl->data->length[i]){
err = ERR_NO_CAPTURE_DATA;
}else{
g_userData->sampleFreqHz[i] = hndl->data->sampleFreqHz[i];
startOffsetArray[i] = (int)(g_userData->sampleFreqHz[i]*1.0e-6*startPositionUs);
lengthArray[i] = (int)(g_userData->sampleFreqHz[i]*1.0e-6*lengthUs);
if( startOffsetArray[i] >= hndl->data->length[i] || (startOffsetArray[i]+lengthArray[i]) > hndl->data->length[i] )
{
err = ERR_INVALID_DATA_CAPTURE_RANGE;
}
else
{
g_userData->real[i] = hndl->data->real[i] + startOffsetArray[i];
g_userData->imag[i] = hndl->data->imag[i] + startOffsetArray[i];
g_userData->length[i] = lengthArray[i];
}
}
}
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
return err;
}
IQMEASURE_API int LP_SaveTruncateCapture(char *sigFileName)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_SaveTruncateCapture", &timeStart);
if (LibsInitialized)
{
if(0 != g_userData)
{
if(0 !=g_userData->length[0])
{
if (g_userData->Save(sigFileName))
err = ERR_SAVE_WAVE_FAILED;
}
else
{
err = ERR_NO_CAPTURE_DATA;
}
}
}
else
err = ERR_NOT_INITIALIZED;
::TIMER_StopTimer(timerIQmeasure, "LP_SaveTruncateCapture", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_SaveTruncateCapture", timeDuration);
return err;
}
IQMEASURE_API int LP_Analyze80216e( double sigType ,
double bandwidthHz ,
double cyclicPrefix ,
double rateId ,
double numSymbols ,
int ph_corr ,
int ch_corr ,
int freq_corr ,
int timing_corr ,
int ampl_track ,
double decode ,
char *map_conf_file
)
{
int err = ERR_OK;
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
analysis80216->type = "80216e-2005";
analysis80216->mode = "80216e-2005";
analysis80216->mapConfigFile = map_conf_file;
}
return LP_Analyze80216d(sigType, bandwidthHz, cyclicPrefix, rateId, numSymbols, ph_corr, ch_corr, freq_corr, timing_corr, ampl_track, decode);
}
IQMEASURE_API int LP_Analyze80216d( double sigType ,
double bandwidthHz ,
double cyclicPrefix ,
double rateId ,
double numSymbols ,
int ph_corr ,
int ch_corr ,
int freq_corr ,
int timing_corr ,
int ampl_track ,
double decode
)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_Analyze80216", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
analysis80216->Phy.sigType = sigType;
analysis80216->Phy.bandwidthHz = bandwidthHz;
analysis80216->Phy.cyclicPrefix = cyclicPrefix;
analysis80216->Phy.rateId = rateId;
analysis80216->Phy.numSymbols = numSymbols;
analysis80216->loggingMode = 0; // disable message from analysis API
analysis80216->Acq.phaseCorrect = (IQV_PH_CORR_ENUM) ph_corr;
analysis80216->Acq.channelCorrect = (IQV_CH_EST_ENUM) ch_corr;
analysis80216->Acq.freqCorrect = (IQV_FREQ_SYNC_ENUM) freq_corr;
analysis80216->Acq.timingCorrect = (IQV_SYM_TIM_ENUM) timing_corr;
analysis80216->Acq.amplitudeTrack = (IQV_AMPL_TRACK_ENUM) ampl_track;
analysis80216->Dec.decode = decode;
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysis80216);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_Analyze80216", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_Analyze80216", timeDuration);
return err;
}
IQMEASURE_API int LP_Analyze80211p(int ph_corr_mode, int ch_estimate, int sym_tim_corr, int freq_sync, int ampl_track, int ofdm_mode)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_Analyze80211p", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
analysisOfdm->ph_corr_mode = (IQV_PH_CORR_ENUM) ph_corr_mode;
analysisOfdm->ch_estimate = (IQV_CH_EST_ENUM) ch_estimate;
analysisOfdm->sym_tim_corr = (IQV_SYM_TIM_ENUM) sym_tim_corr;
analysisOfdm->freq_sync = (IQV_FREQ_SYNC_ENUM) freq_sync;
analysisOfdm->ampl_track = (IQV_AMPL_TRACK_ENUM) ampl_track;
analysisOfdm->OFDM_mode = (IQV_OFDM_MODE_ENUM)ofdm_mode;
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisOfdm);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_Analyze80211p", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_Analyze80211p", timeDuration);
return err;
}
IQMEASURE_API int LP_Analyze80211ag(int ph_corr_mode, int ch_estimate, int sym_tim_corr, int freq_sync, int ampl_track,double prePowStartSec,
double prePowStopSec)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_Analyze80211ag", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
analysisOfdm->ph_corr_mode = (IQV_PH_CORR_ENUM) ph_corr_mode;
analysisOfdm->ch_estimate = (IQV_CH_EST_ENUM) ch_estimate;
analysisOfdm->sym_tim_corr = (IQV_SYM_TIM_ENUM) sym_tim_corr;
analysisOfdm->freq_sync = (IQV_FREQ_SYNC_ENUM) freq_sync;
analysisOfdm->ampl_track = (IQV_AMPL_TRACK_ENUM) ampl_track;
analysisOfdm->prePowStartSec = prePowStartSec;
analysisOfdm->prePowStopSec = prePowStopSec;
//Workaround due to IQapi bug
hndl->ScpiCommandSet("WIFI;Clear:All");
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisOfdm);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_Analyze80211ag", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_Analyze80211ag", timeDuration);
return err;
}
// LP_AnalyzeMimo kept for backward compability
IQMEASURE_API int LP_AnalyzeMimo(char *type,
char *mode,
int enablePhaseCorr,
int enableSymTimingCorr,
int enableAmplitudeTracking,
int decodePSDU,
int enableFullPacketChannelEst,
char *referenceFile)
{
return LP_Analyze80211n(type,
mode,
enablePhaseCorr,
enableSymTimingCorr,
enableAmplitudeTracking,
decodePSDU,
enableFullPacketChannelEst,
referenceFile);
}
IQMEASURE_API int LP_Analyze80211n(char *type,
char *mode,
int enablePhaseCorr,
int enableSymTimingCorr,
int enableAmplitudeTracking,
int decodePSDU,
int enableFullPacketChannelEst,
char *referenceFile,
int packetFormat,
int frequencyCorr,
double prePowStartSec,
double prePowStopSec)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_AnalyzeMimo", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
if( NULL==analysisMimo )
{
InstantiateAnalysisClasses();
}
//analysisMimo->type = type; //temporarily unsupported, IQapi should fix this.
analysisMimo->mode = mode;
analysisMimo->enablePhaseCorr = enablePhaseCorr;
analysisMimo->enableSymTimingCorr = enableSymTimingCorr;
analysisMimo->enableAmplitudeTracking = enableAmplitudeTracking;
analysisMimo->decodePSDU = decodePSDU;
analysisMimo->enableFullPacketChannelEst = enableFullPacketChannelEst;
analysisMimo->frequencyCorr = frequencyCorr;
analysisMimo->referenceFile = referenceFile;
analysisMimo->packetFormat = packetFormat;
analysisMimo->prePowStartSec = prePowStartSec;
analysisMimo->prePowStopSec = prePowStopSec;
//debug z-99, work around
//analysisMimo->packetFormat = IQV_PACKET_FORMAT_AUTO;
//if( 0==strcmp("sequential_mimo",mode) )
//{
// analysisMimo->SequentialMimo.numSections = g_numSections;
// analysisMimo->SequentialMimo.sectionLenSec = g_sectionLenSec;
// analysisMimo->SequentialMimo.interSectionGapSec = 0;
//}
//Workaround due to IQapi bug
hndl->ScpiCommandSet("WIFI;Clear:All");
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisMimo);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
// MIMO analysis succeeded
resultMimo = dynamic_cast<iqapiResultMimo *>(hndl->results);
if( NULL!=resultMimo )
{
g_lastPerformedAnalysisType = ANALYSIS_MIMO;
// Measurement results are ready for retrieval
}
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_AnalyzeMimo", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_AnalyzeMimo", timeDuration);
return err;
}
IQMEASURE_API int LP_Analyze80211ac(char *mode,
int enablePhaseCorr,
int enableSymTimingCorr,
int enableAmplitudeTracking,
int decodePSDU,
int enableFullPacketChannelEst,
int frequencyCorr,
char *referenceFile,
int packetFormat,
int numberOfPacketToAnalysis,
double prePowStartSec,
double prePowStopSec)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_Analyze80211ac", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
if( NULL==analysisWifiOfdm )
{
InstantiateAnalysisClasses();
}
// no need to set the type anymore as 11ac only has one type.
//analysisWifiOfdm->type = type;
analysisWifiOfdm->mode = mode;
analysisWifiOfdm->enablePhaseCorr = (IQV_ON_OFF) enablePhaseCorr;
analysisWifiOfdm->enableSymTimingCorr = (IQV_ON_OFF) enableSymTimingCorr;
analysisWifiOfdm->enableAmplitudeTracking = (IQV_ON_OFF)enableAmplitudeTracking;
analysisWifiOfdm->numberOfPacketToAnalysis = numberOfPacketToAnalysis;
//temp, Z-99
//analysisWifiOfdm->decodePSDU = decodePSDU;
analysisWifiOfdm->enableFullPacketChannelEst = (IQV_CHAN_ESTIMATION) enableFullPacketChannelEst;
// Work around for Freq Corr Enum
if(frequencyCorr == 1)
analysisWifiOfdm->frequencyCorr = (IQV_FREQUENCY_CORR)(0);
if(frequencyCorr == 2)
analysisWifiOfdm->frequencyCorr = (IQV_FREQUENCY_CORR)(1);
if(frequencyCorr == 3)
analysisWifiOfdm->frequencyCorr = (IQV_FREQUENCY_CORR)(3);
if(frequencyCorr == 4)
analysisWifiOfdm->frequencyCorr = (IQV_FREQUENCY_CORR)(2);
//analysisWifiOfdm->frequencyCorr = (IQV_FREQUENCY_CORR)(frequencyCorr);
analysisWifiOfdm->referenceFile = referenceFile;
analysisWifiOfdm->packetFormat = (IQV_PACKET_FORMAT)packetFormat;
analysisWifiOfdm->prePowStartSec = prePowStartSec;
analysisWifiOfdm->prePowStopSec = prePowStopSec;
//if( 0==strcmp("sequential_mimo",mode) )
//{
// analysisWifiOfdm->SequentialMimo.numSections = g_numSections;
// analysisWifiOfdm->SequentialMimo.sectionLenSec = g_sectionLenSec;
// analysisWifiOfdm->SequentialMimo.interSectionGapSec = 0;
//}
//err=hndl->LoadSignalFile("./log/FastTrack_Capture-WIFI_AC_BW80_SS1_MCS4_BCC_Fs160M-1.iqvsa");
//Workaround due to IQapi bug
hndl->ScpiCommandSet("WIFI;Clear:All");
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisWifiOfdm);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
// 11ac analysis succeeded
//Z-99
//result11ac = dynamic_cast<iqapiResult11ac *>(hndl->results);
result11ac = dynamic_cast<iqapiResultWifiOfdm *>(hndl->results);
if( NULL!=result11ac )
{
g_lastPerformedAnalysisType = ANALYSIS_80211AC;
// Measurement results are ready for retrieval
}
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_Analyze80211ac", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_Analyze80211ac", timeDuration);
return err;
}
IQMEASURE_API int LP_Analyze80211b(int eq_taps, int DCremove11b_flag, int method_11b, double prePowStartSec,
double prePowStopSec)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_Analyze80211b", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
if (!analysis11b) {
return ERR_ANALYSIS_FAILED;
}
analysis11b->eq_taps = (IQV_EQ_ENUM) eq_taps;
analysis11b->DCremove11b_flag = (IQV_DC_REMOVAL_ENUM) DCremove11b_flag;
analysis11b->method_11b = (IQV_11B_METHOD_ENUM) method_11b;
analysis11b->prePowStartSec = prePowStartSec;
analysis11b->prePowStopSec = prePowStopSec;
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysis11b);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_Analyze80211b", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_Analyze80211b", timeDuration);
return err;
}
IQMEASURE_API int LP_AnalyzePower(double T_interval, double max_pow_diff_dB)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_AnalyzePower", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
//analysisPower->T_interval = T_interval;
//analysisPower->max_pow_diff_dB = max_pow_diff_dB;
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisPower);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_AnalyzePower", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_AnalyzePower", timeDuration);
return err;
}
IQMEASURE_API int LP_AnalyzeFFT(double NFFT, double res_bw, char *window_type)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_AnalyzeFFT", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
//analysisFFT->F_sample = hndl->rx->sampleFreqHz;
analysisFFT->NFFT = NFFT;
analysisFFT->res_bw = res_bw;
analysisFFT->window_type = window_type;
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisFFT);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
g_lastPerformedAnalysisType = ANALYSIS_FFT;
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_AnalyzeFFT", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_AnalyzeFFT", timeDuration);
return err;
}
IQMEASURE_API int LP_AnalyzeCCDF()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_AnalyzeCCDF", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisCCDF);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_AnalyzeCCDF", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_AnalyzeCCDF", timeDuration);
return err;
}
// Kept for backward compability
IQMEASURE_API int LP_AnalyzeCW()
{
return LP_AnalyzeCWFreq();
}
IQMEASURE_API int LP_AnalyzeCWFreq()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_AnalyzeCW", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisCW);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_AnalyzeCW", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_AnalyzeCW", timeDuration);
return err;
}
IQMEASURE_API int LP_AnalyzePowerRamp80211b()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_AnalyzePowerRamp80211b", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisPowerRamp11b);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_AnalyzePowerRamp80211b", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_AnalyzePowerRamp80211b", timeDuration);
return err;
}
IQMEASURE_API int LP_AnalyzePowerRampOFDM()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_AnalyzePowerRampOFDM", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisPowerRampOfdm);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_AnalyzePowerRampOFDM", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_AnalyzePowerRampOFDM", timeDuration);
return err;
}
IQMEASURE_API int LP_AnalyzeSidelobe()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_AnalyzeSidelobe", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisSidelobe);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_AnalyzeSidelobe", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_AnalyzeSidelobe", timeDuration);
return err;
}
IQMEASURE_API int LP_AnalysisWave()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_AnalysisWave", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisWave);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_AnalysisWave", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_AnalysisWave", timeDuration);
return err;
}
IQMEASURE_API int LP_AnalyzeBluetooth( double data_rate, char *analysis_type )
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_AnalyzeBluetooth", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
analysisBluetooth->dataRate = data_rate;
analysisBluetooth->analysis_type = analysis_type;
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisBluetooth);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_AnalyzeBluetooth", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_AnalyzeBluetooth", timeDuration);
return err;
}
IQMEASURE_API int LP_AnalyzeZigbee()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_AnalyzeZigbee", &timeStart);
if (LibsInitialized)
{
if (!hndl->data)
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->data->length[0])
{
err = ERR_NO_CAPTURE_DATA;
return err;
}
}
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisZigbee);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_AnalyzeZigbee", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_AnalyzeZigbee", timeDuration);
return err;
}
IQMEASURE_API int LP_AnalyzeVHT80Mask()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_AnalyzeVHT80Mask", &timeStart);
if (LibsInitialized)
{
if(true == bIQxsFound || true == bIQxelFound)
{
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisVHT80);
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_ANALYSIS_FAILED; //only IQxs/IQxel can support 80MHz
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_AnalyzeVHT80Mask", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_AnalyzeVHT0Mask", timeDuration);
return err;
}
IQMEASURE_API int LP_AnalyzeHT40Mask()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_AnalyzeHT40Mask", &timeStart);
if (LibsInitialized)
{
//if (!hndl->data)
//{
// err = ERR_NO_CAPTURE_DATA;
// return err;
//}
//else
//{
// if (!hndl->data->length[0])
// {
// err = ERR_NO_CAPTURE_DATA;
// return err;
// }
//}
#if !defined(IQAPI_1_5_X)
// iqapiResultHT40 is supported in IQapi 1.6.x and beyond
hndl->analysis = dynamic_cast<iqapiAnalysis *>(analysisHT40);
#endif
if (LP_Analyze())
{
err = ERR_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_AnalyzeHT40Mask", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_AnalyzeHT40Mask", timeDuration);
return err;
}
// Keep this function with typo for backward compatibility
IQMEASURE_API double LP_GetScalarMeasurment(char *measurement, int index)
{
return LP_GetScalarMeasurement(measurement, index);
}
/*! @defgroup group_scalar_measurement Available Measurement Names for LP_GetScalarMeasurement()
*
* Available measurement names vary for various analysis. After an analysis has been performed successfully, by calling
* one of the following functions:
* - LP_Analyze80211ag();
* - LP_AnalyzeMimo();
* - LP_Analyze80211b();
* - LP_Analyze80216d();
* - LP_Analyze80216e();
* - LP_AnalyzePower();
* - LP_AnalyzeFFT();
* - LP_AnalyzeCCDF();
* - LP_AnalyzeCW();
* - LP_AnalysisWave();
* - LP_AnalyzeSidelobe();
* - LP_AnalyzePowerRampOFDM();
* - LP_AnalyzePowerRamp80211b();
* - LP_AnalyzeBluetooth();
* - LP_AnalyzeZigbee();
*
* \section analysis_80211ag Measurement Names for LP_Analyze80211ag()
* - evmAll: EVM of all symbols in the capture. index value: 0
*
* \section analysis_mimo Measurement Names for LP_AnalyzeMimo()
* - evmAvgAll: EVM of all symbols in the capture. Each stream will have a corresponding value, so index value: [0 - (StreamNum-1)]
*/
IQMEASURE_API double LP_GetScalarMeasurement_NoTimer(char *measurement, int index)
{
if (LibsInitialized)
{
if (!hndl->results)
{
return NA_NUMBER;
}
else
{
if (dynamic_cast<iqapiResultOFDM *>(hndl->results))
{
resultOfdm = dynamic_cast<iqapiResultOFDM *>(hndl->results);
if (!strcmp(measurement, "psduCrcFail"))
{
return((double)resultOfdm->psduCrcFail);
}
else if (!strcmp(measurement, "plcpCrcPass"))
{
return((double)resultOfdm->plcpCrcPass);
}
else if (!strcmp(measurement, "dataRate"))
{
return((double)resultOfdm->dataRate);
}
else if (!strcmp(measurement, "numSymbols"))
{
return((double)resultOfdm->numSymbols);
}
else if (!strcmp(measurement, "numPsduBytes"))
{
return((double)resultOfdm->numPsduBytes);
}
else if (!strcmp(measurement, "evmAll"))
{
if (resultOfdm->evmAll && resultOfdm->evmAll->length > index)
return(resultOfdm->evmAll->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "evmData"))
{
if (resultOfdm->evmData && resultOfdm->evmData->length > index)
return(resultOfdm->evmData->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "evmPilot"))
{
if (resultOfdm->evmPilot && resultOfdm->evmPilot->length > index)
return(resultOfdm->evmPilot->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "codingRate"))
{
if (resultOfdm->codingRate && resultOfdm->codingRate->length > index)
return(resultOfdm->codingRate->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "freqErr"))
{
if (resultOfdm->freqErr && resultOfdm->freqErr->length > index)
return(resultOfdm->freqErr->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "clockErr"))
{
if (resultOfdm->clockErr && resultOfdm->clockErr->length > index)
return(resultOfdm->clockErr->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "ampErr"))
{
if (resultOfdm->ampErr && resultOfdm->ampErr->length > index)
return(resultOfdm->ampErr->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "ampErrDb"))
{
if (resultOfdm->ampErrDb && resultOfdm->ampErrDb->length > index)
return(resultOfdm->ampErrDb->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "phaseErr"))
{
if (resultOfdm->phaseErr && resultOfdm->phaseErr->length > index)
return(resultOfdm->phaseErr->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "clockErr"))
{
if (resultOfdm->clockErr && resultOfdm->clockErr->length > index)
return(resultOfdm->clockErr->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rmsPhaseNoise"))
{
if (resultOfdm->rmsPhaseNoise && resultOfdm->rmsPhaseNoise->length > index)
return(resultOfdm->rmsPhaseNoise->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "powerPreambleDbm"))
{
if (resultOfdm->powerPreambleDbm && resultOfdm->powerPreambleDbm->length > index)
return(resultOfdm->powerPreambleDbm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rmsPowerNoGap"))
{
if (resultOfdm->rmsPowerNoGap && resultOfdm->rmsPowerNoGap->length > index)
return(resultOfdm->rmsPowerNoGap->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rmsPower"))
{
if (resultOfdm->rmsPower && resultOfdm->rmsPower->length > index)
return(resultOfdm->rmsPower->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "pkPower")) // OFDM
{
if (resultOfdm->pkPower && resultOfdm->pkPower->length > index)
return(resultOfdm->pkPower->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rmsMaxAvgPower"))
{
if (resultOfdm->rmsMaxAvgPower && resultOfdm->rmsMaxAvgPower->length > index)
return(resultOfdm->rmsMaxAvgPower->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "dcLeakageDbc"))
{
if (resultOfdm->dcLeakageDbc && resultOfdm->dcLeakageDbc->length > index)
return (resultOfdm->dcLeakageDbc->real[index]);
else
return NA_NUMBER;
}
else
{
return NA_NUMBER;
}
}
else if (dynamic_cast<iqapiResult80216 *>(hndl->results))
{
result80216 = dynamic_cast<iqapiResult80216 *>(hndl->results);
if(!strcmp(measurement,"packetDetection"))
{
return ((double) result80216->packetDetection);
}
else if (!strcmp(measurement, "acquisition"))
{
return((double) result80216->acquisition);
}
else if (!strcmp(measurement, "demodulation"))
{
return((double)result80216->demodulation);
}
else if (!strcmp(measurement, "completePacket"))
{
return((double)result80216->completePacket);
}
else if (!strcmp(measurement, "fchHcs"))
{
return((double)result80216->fchHcs);
}
else if (!strcmp(measurement, "numberOfZone"))
{
return((double)result80216->numberOfZone);
}
else if (!strcmp(measurement, "sigType"))
{
if (result80216->sigType && result80216->sigType->length > index)
return (result80216->sigType->real[index]);
else
return NA_NUMBER;
}
// else if (!strcmp(measurement, "numSymbols"))
// {
// if (result80216->numSymbols && result80216->numSymbols->length > index)
// return (result80216->numSymbols->real[index]);
// else
// return NA_NUMBER;
// }
else if (!strcmp(measurement, "bandwidthHz"))
{
if (result80216->bandwidthHz && result80216->bandwidthHz->length > index)
return (result80216->bandwidthHz->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "cyclicPrefix"))
{
if (result80216->cyclicPrefix && result80216->cyclicPrefix->length > index)
return (result80216->cyclicPrefix->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "evmAvgAll"))
{
if (result80216->evmAvgAll && result80216->evmAvgAll->length > index)
return (result80216->evmAvgAll->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "evmAvgData"))
{
if (result80216->evmAvgData && result80216->evmAvgData->length > index)
return (result80216->evmAvgData->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "evmAvgPilot"))
{
if (result80216->evmAvgPilot && result80216->evmAvgPilot->length > index)
return (result80216->evmAvgPilot->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "evmCinrDb"))
{
if (result80216->evmCinrDb && result80216->evmCinrDb->length > index)
return (result80216->evmCinrDb->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "avgUnmodData"))
{
if (result80216->avgUnmodData && result80216->avgUnmodData->length > index)
return (result80216->avgUnmodData->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "dcLeakageDbc"))
{
if (result80216->dcLeakageDbc && result80216->dcLeakageDbc->length > index)
return (result80216->dcLeakageDbc->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "avgPowerNoGapDb"))
{
if (result80216->avgPowerNoGapDb && result80216->avgPowerNoGapDb->length > index)
return (result80216->avgPowerNoGapDb->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rxPreambleRmsPowerDb"))
{
if (result80216->rxPreambleRmsPowerDb && result80216->rxPreambleRmsPowerDb->length > index)
return (result80216->rxPreambleRmsPowerDb->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "freqErrorHz"))
{
if (result80216->freqErrorHz && result80216->freqErrorHz->length > index)
return(result80216->freqErrorHz->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "freqOffsetTotalHz"))
{
if (result80216->freqOffsetTotalHz && result80216->freqOffsetTotalHz->length > index)
return(result80216->freqOffsetTotalHz->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "symClockErrorPpm"))
{
if (result80216->symClockErrorPpm && result80216->symClockErrorPpm->length > index)
return(result80216->symClockErrorPpm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "phaseNoiseDegRmsAll"))
{
if (result80216->phaseNoiseDegRmsAll && result80216->phaseNoiseDegRmsAll->length > index)
return(result80216->phaseNoiseDegRmsAll->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "iqImbalAmplDb"))
{
if (result80216->iqImbalAmplDb && result80216->iqImbalAmplDb->length > index)
return(result80216->iqImbalAmplDb->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "iqImbalPhaseDeg"))
{
if (result80216->iqImbalPhaseDeg && result80216->iqImbalPhaseDeg->length > index)
return(result80216->iqImbalPhaseDeg->real[index]);
else
return NA_NUMBER;
}
else
{
return NA_NUMBER;
}
}
//since the 11AC and MIMO structure is so close, it is better to put 11AC in front of MIMO, there might be a better way, Zhiyong On Aug 14, 2011
//else if (dynamic_cast<iqapiResult11ac *>(hndl->results))
else if (dynamic_cast<iqapiResultWifiOfdm *>(hndl->results))
{
double attn[4]={0.0};//, attnError[4]={0.0};
//result11ac = dynamic_cast<iqapiResult11ac *>(hndl->results);
result11ac = dynamic_cast<iqapiResultWifiOfdm *>(hndl->results);
//not supported until customer really need this info
//if (!strcmp(measurement, "VHTSigA1Bits"))
//{
//}
if (!strcmp(measurement, "VHTSigA1Bandwidth") || !strcmp(measurement, "vhtSigA1Bandwidth")) //for backward compatible
{
if (result11ac->vhtSigA1Bandwidth && result11ac->vhtSigA1Bandwidth->length > index)
return(result11ac->vhtSigA1Bandwidth->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "VHTSigA1Stbc") || !strcmp(measurement, "vhtSigA1Stbc") )
{
if (result11ac->vhtSigA1Stbc && result11ac->vhtSigA1Stbc->length > index)
return(result11ac->vhtSigA1Stbc->real[index]);
else
return NA_NUMBER;
}
// For VHTSigA2
//not supported until customer really need this info
//if (!strcmp(measurement, "VHTSigA2Bits"))
//{
//}
else if (!strcmp(measurement, "VHTSigA2ShortGI") || !strcmp(measurement, "vhtSigA2ShortGI") )
{
if (result11ac->vhtSigA2ShortGI && result11ac->vhtSigA2ShortGI->length > index)
return(result11ac->vhtSigA2ShortGI->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "VHTSigA2AdvancedCoding") || !strcmp(measurement, "vhtSigA2AdvancedCoding"))
{
if (result11ac->vhtSigA2AdvancedCoding && result11ac->vhtSigA2AdvancedCoding->length > index)
return(result11ac->vhtSigA2AdvancedCoding->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "VHTSigA2McsIndex") || !strcmp(measurement, "vhtSigA2McsIndex"))
{
if (result11ac->vhtSigA2McsIndex && result11ac->vhtSigA2McsIndex->length > index)
return(result11ac->vhtSigA2McsIndex->real[index]);
else
return NA_NUMBER;
}
// For VHTSigB
//not supported until customer really need this info
//if (!strcmp(measurement, "VHTSigBBits"))
//{
//}
else if (!strcmp(measurement, "VHTSigBFieldCRC") || !strcmp(measurement, "vhtSigBFieldCRC"))
{
return((double)result11ac->vhtSigBFieldCRC);
}
else if (!strcmp(measurement, "evmAvgAll"))
{
if (result11ac->evmAvgAll && result11ac->evmAvgAll->length > index)
return(result11ac->evmAvgAll->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "packetDetection"))
{
return((double)result11ac->packetDetection);
}
else if (!strcmp(measurement, "psduCRC"))
{
return((double)result11ac->psduCRC);
}
else if (!strcmp(measurement, "numPsduBytes"))
{
return((double)result11ac->numPsduBytes);
}
else if (!strcmp(measurement, "acquisition"))
{
return((double)result11ac->acquisition);
}
else if (!strcmp(measurement, "demodulation"))
{
return((double)result11ac->demodulation);
}
else if (!strcmp(measurement, "dcLeakageDbc"))
{
if (result11ac->dcLeakageDbc && result11ac->dcLeakageDbc->length > index)
{
//printf("dc_leakage is %0.2f\n", result11ac->dcLeakageDbc->real[index+1]);
//printf("dc_leakage is %0.2f\n", result11ac->dcLeakageDbc->real[index+2]);
return(result11ac->dcLeakageDbc->real[index]);
}
else
return NA_NUMBER;
}
if (!strcmp(measurement, "powerPreambleDbm"))
{
if (result11ac->powerPreambleDbm && result11ac ->powerPreambleDbm->length > index)
{
return(result11ac->powerPreambleDbm->real[index]);
}
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rxRmsPowerDb"))
{
if (result11ac->rxRmsPowerDb && result11ac ->rxRmsPowerDb->length > index)
//no sequential mode any more.
//if( analysisWifiOfdm->SequentialMimo.numSections>0 )
//{
// return(result11ac->rxRmsPowerDb->real[index] +
// attn[index/analysisWifiOfdm->SequentialMimo.numSections] );
//}
//else
{
return(result11ac->rxRmsPowerDb->real[index]);
}
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "isolationDb"))
{
if (result11ac->isolationDb && result11ac->isolationDb->length > index)
{
return(result11ac->isolationDb->real[index]);
}
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "freqErrorHz"))
{
if (result11ac->freqErrorHz && result11ac->freqErrorHz->length > index)
return(result11ac->freqErrorHz->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "symClockErrorPpm"))
{
if (result11ac->symClockErrorPpm && result11ac->symClockErrorPpm->length > index)
return(result11ac->symClockErrorPpm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "PhaseNoiseDeg_RmsAll"))
{
if (result11ac->PhaseNoiseDeg_RmsAll && result11ac->PhaseNoiseDeg_RmsAll->length > index)
return(result11ac->PhaseNoiseDeg_RmsAll->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "IQImbal_amplDb"))
{
if (result11ac->IQImbal_amplDb && result11ac->IQImbal_amplDb->length > index)
return(result11ac->IQImbal_amplDb->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "IQImbal_phaseDeg"))
{
if (result11ac->IQImbal_phaseDeg && result11ac->IQImbal_phaseDeg->length > index)
return(result11ac->IQImbal_phaseDeg->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rateInfo_bandwidthMhz"))
{
if (result11ac->rateInfo_bandwidthMhz && result11ac->rateInfo_bandwidthMhz->length > index)
return(result11ac->rateInfo_bandwidthMhz->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rateInfo_dataRateMbps"))
{
if (result11ac->rateInfo_dataRateMbps && result11ac->rateInfo_dataRateMbps->length > index)
return(result11ac->rateInfo_dataRateMbps->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rateInfo_spatialStreams"))
{
if (result11ac->rateInfo_spatialStreams && result11ac->rateInfo_spatialStreams->length > index)
return(result11ac->rateInfo_spatialStreams->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "analyzedRange"))
{
if (result11ac->analyzedRange && result11ac->analyzedRange->length > index)
return(result11ac->analyzedRange->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rateInfo_spaceTimeStreams"))
{
if (result11ac->rateInfo_spaceTimeStreams && result11ac->rateInfo_spaceTimeStreams->length > index)
return(result11ac->rateInfo_spaceTimeStreams->real[index]);
else
return NA_NUMBER;
}
else
{
return NA_NUMBER;
}
}
else if (dynamic_cast<iqapiResultMimo *>(hndl->results))
{
double attn[4]={0.0};//, attnError[4]={0.0};
resultMimo = dynamic_cast<iqapiResultMimo *>(hndl->results);
if (!strcmp(measurement, "evmAvgAll"))
{
if (resultMimo->evmAvgAll && resultMimo->evmAvgAll->length > index)
return(resultMimo->evmAvgAll->real[index]);
else
return NA_NUMBER;
}
else
if (!strcmp(measurement, "packetDetection"))
{
return((double)resultMimo->packetDetection);
}
else if (!strcmp(measurement, "psduCRC"))
{
return((double)resultMimo->psduCRC);
}
else if (!strcmp(measurement, "acquisition"))
{
return((double)resultMimo->acquisition);
}
else if (!strcmp(measurement, "demodulation"))
{
return((double)resultMimo->demodulation);
}
else if (!strcmp(measurement, "evmAvgAll"))
{
if (resultMimo->evmAvgAll && resultMimo->evmAvgAll->length > index)
return(resultMimo->evmAvgAll->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "dcLeakageDbc"))
{
if (resultMimo->dcLeakageDbc && resultMimo->dcLeakageDbc->length > index)
return(resultMimo->dcLeakageDbc->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "powerPreambleDbm"))
{
if (resultMimo->powerPreambleDbm && resultMimo ->powerPreambleDbm->length > index)
{
return(resultMimo->powerPreambleDbm->real[index]);
}
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rxRmsPowerDb"))
{
if (resultMimo->rxRmsPowerDb && resultMimo ->rxRmsPowerDb->length > index)
if( analysisMimo->SequentialMimo.numSections>0 )
{
return(resultMimo->rxRmsPowerDb->real[index] +
attn[index/analysisMimo->SequentialMimo.numSections] );
}
else
{
return(resultMimo->rxRmsPowerDb->real[index]);
}
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "isolationDb"))
{
if (resultMimo->isolationDb && resultMimo->isolationDb->length > index)
{
return(resultMimo->isolationDb->real[index]);
}
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "freqErrorHz"))
{
if (resultMimo->freqErrorHz && resultMimo->freqErrorHz->length > index)
return(resultMimo->freqErrorHz->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "symClockErrorPpm"))
{
if (resultMimo->symClockErrorPpm && resultMimo->symClockErrorPpm->length > index)
return(resultMimo->symClockErrorPpm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "PhaseNoiseDeg_RmsAll"))
{
if (resultMimo->PhaseNoiseDeg_RmsAll && resultMimo->PhaseNoiseDeg_RmsAll->length > index)
return(resultMimo->PhaseNoiseDeg_RmsAll->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "IQImbal_amplDb"))
{
if (resultMimo->IQImbal_amplDb && resultMimo->IQImbal_amplDb->length > index)
return(resultMimo->IQImbal_amplDb->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "IQImbal_phaseDeg"))
{
if (resultMimo->IQImbal_phaseDeg && resultMimo->IQImbal_phaseDeg->length > index)
return(resultMimo->IQImbal_phaseDeg->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rateInfo_bandwidthMhz"))
{
if (resultMimo->rateInfo_bandwidthMhz && resultMimo->rateInfo_bandwidthMhz->length > index)
return(resultMimo->rateInfo_bandwidthMhz->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rateInfo_dataRateMbps"))
{
if (resultMimo->rateInfo_dataRateMbps && resultMimo->rateInfo_dataRateMbps->length > index)
return(resultMimo->rateInfo_dataRateMbps->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rateInfo_spatialStreams"))
{
if (resultMimo->rateInfo_spatialStreams && resultMimo->rateInfo_spatialStreams->length > index)
return(resultMimo->rateInfo_spatialStreams->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "analyzedRange"))
{
if (resultMimo->analyzedRange && resultMimo->analyzedRange->length > index)
return(resultMimo->analyzedRange->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "htSig1_htLength"))
{
if (resultMimo->htSig1_htLength && resultMimo->htSig1_htLength->length > index)
return(resultMimo->htSig1_htLength->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "htSig1_mcsIndex"))
{
if (resultMimo->htSig1_mcsIndex && resultMimo->htSig1_mcsIndex->length > index)
return(resultMimo->htSig1_mcsIndex->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "htSig1_bandwidth"))
{
if (resultMimo->htSig1_bandwidth && resultMimo->htSig1_bandwidth->length > index)
return(resultMimo->htSig1_bandwidth->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "htSig2_advancedCoding"))
{
if (resultMimo->htSig2_advancedCoding && resultMimo->htSig2_advancedCoding->length > index)
return(resultMimo->htSig2_advancedCoding->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rateInfo_spaceTimeStreams"))
{
if (resultMimo->rateInfo_spaceTimeStreams && resultMimo->rateInfo_spaceTimeStreams->length > index)
return(resultMimo->rateInfo_spaceTimeStreams->real[index]);
else
return NA_NUMBER;
}
else
{
return NA_NUMBER;
}
}
else if (dynamic_cast<iqapiResult11b *>(hndl->results))
{
result11b = dynamic_cast<iqapiResult11b *>(hndl->results);
if (!strcmp(measurement, "lockedClock"))
{
return((double)result11b->lockedClock);
}
else if (!strcmp(measurement, "plcpCrcFail"))
{
return((double)result11b->plcpCrcFail);
}
else if (!strcmp(measurement, "psduCrcFail"))
{
return((double)result11b->psduCrcFail);
}
else if (!strcmp(measurement, "numPsduBytes"))
{
return((double)result11b->numPsduBytes);
}
else if (!strcmp(measurement, "longPreamble"))
{
return((double)result11b->longPreamble);
}
else if (!strcmp(measurement, "bitRateInMHz"))
{
return((double)result11b->bitRateInMHz);
}
else if (!strcmp(measurement, "evmPk"))
{
if (result11b->evmPk && result11b->evmPk->length > index)
return(result11b->evmPk->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "evmAll"))
{
if (result11b->evmAll && result11b->evmAll->length > index)
return(result11b->evmAll->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "evmInPreamble"))
{
if (result11b->evmInPreamble && result11b->evmInPreamble->length > index)
return(result11b->evmInPreamble->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "evmInPsdu"))
{
if (result11b->evmInPsdu && result11b->evmInPsdu->length > index)
return(result11b->evmInPsdu->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "powerPreambleDbm"))//LK
{
if (result11b->powerPreambleDbm && result11b->powerPreambleDbm->length > index)
return(result11b->powerPreambleDbm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "loLeakageDb"))
{
if (result11b->loLeakageDb && result11b->loLeakageDb->length > index)
return(result11b->loLeakageDb->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "freqErr"))
{
if (result11b->freqErr && result11b->freqErr->length > index)
return(result11b->freqErr->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "clockErr"))
{
if (result11b->clockErr && result11b->clockErr->length > index)
return(result11b->clockErr->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "ampErr"))
{
if (result11b->ampErr && result11b->ampErr->length > index)
return(result11b->ampErr->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "ampErrDb"))
{
if (result11b->ampErrDb && result11b->ampErrDb->length > index)
return(result11b->ampErrDb->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "phaseErr"))
{
if (result11b->phaseErr && result11b->phaseErr->length > index)
return(result11b->phaseErr->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rmsPhaseNoise"))
{
if (result11b->rmsPhaseNoise && result11b->rmsPhaseNoise->length > index)
return(result11b->rmsPhaseNoise->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rmsPowerNoGap"))
{
if (result11b->rmsPowerNoGap && result11b->rmsPowerNoGap->length > index)
return(result11b->rmsPowerNoGap->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rmsPower"))
{
if (result11b->rmsPower && result11b->rmsPower->length > index)
return(result11b->rmsPower->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "pkPower")) // 11b
{
if (result11b->pkPower && result11b->pkPower->length > index)
return(result11b->pkPower->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rmsMaxAvgPower"))
{
if (result11b->rmsMaxAvgPower && result11b->rmsMaxAvgPower->length > index)
return(result11b->rmsMaxAvgPower->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "bitRate"))
{
if (result11b->bitRate && result11b->bitRate->length > index)
return(result11b->bitRate->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "modType"))
{
if (result11b->modType && result11b->modType->length > index)
return(result11b->modType->real[index]);
else
return NA_NUMBER;
}
// else if (!strcmp(measurement, "maxFreqErr"))
// {
// if (result11b->maxFreqErr && result11b->maxFreqErr->length > index)
// return(result11b->maxFreqErr->real[index]);
// else
// return NA_NUMBER;
// }
else if (!strcmp(measurement, "rmsMaxAvgPower"))
{
if (result11b->rmsMaxAvgPower && result11b->rmsMaxAvgPower->length > index)
return(result11b->rmsMaxAvgPower->real[index]);
else
return NA_NUMBER;
}
else
{
return NA_NUMBER;
}
}
else if (dynamic_cast<iqapiResultPower *>(hndl->results))
{
resultPower = dynamic_cast<iqapiResultPower *>(hndl->results);
if (!strcmp(measurement, "valid"))
{//temporary work around before IQapi team fix this.
if (resultPower->P_av_each_burst_dBm && resultPower->P_av_each_burst_dBm->length > index)
return 1;
else
return NA_NUMBER;
//return((double)resultPower->valid);
}
else if (!strcmp(measurement, "P_av_each_burst"))
{
if (resultPower->P_av_each_burst && resultPower->P_av_each_burst->length > index)
return(resultPower->P_av_each_burst->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "P_av_each_burst_dBm"))
{
if (resultPower->P_av_each_burst_dBm && resultPower->P_av_each_burst_dBm->length > index)
return(resultPower->P_av_each_burst_dBm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "P_pk_each_burst"))
{
if (resultPower->P_pk_each_burst && resultPower->P_pk_each_burst->length > index)
return(resultPower->P_pk_each_burst->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "P_pk_each_burst_dBm"))
{
if (resultPower->P_pk_each_burst_dBm && resultPower->P_pk_each_burst_dBm->length > index)
return(resultPower->P_pk_each_burst_dBm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "P_av_all"))
{
if (resultPower->P_av_all && resultPower->P_av_all->length > index)
return(resultPower->P_av_all->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "P_av_all_dBm"))
{
if (resultPower->P_av_all_dBm && resultPower->P_av_all_dBm->length > index)
return(resultPower->P_av_all_dBm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "P_peak_all_dBm"))
{
if (resultPower->P_peak_all_dBm && resultPower->P_peak_all_dBm->length > index)
return(resultPower->P_peak_all_dBm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "P_peak_all"))
{
if (resultPower->P_peak_all && resultPower->P_peak_all->length > index)
return(resultPower->P_peak_all->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "P_av_no_gap_all"))
{
if (resultPower->P_av_no_gap_all && resultPower->P_av_no_gap_all->length > index)
return(resultPower->P_av_no_gap_all->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "P_av_no_gap_all_dBm"))
{
if (resultPower->P_av_no_gap_all_dBm && resultPower->P_av_no_gap_all_dBm->length > index)
return(resultPower->P_av_no_gap_all_dBm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "start_sec"))
{
if (resultPower->start_sec && resultPower->start_sec->length > index)
return(resultPower->start_sec->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "stop_sec"))
{
if (resultPower->stop_sec && resultPower->stop_sec->length > index)
return(resultPower->stop_sec->real[index]);
else
return NA_NUMBER;
}
else
{
return NA_NUMBER;
}
}
else if (dynamic_cast<iqapiResultFFT *>(hndl->results))
{
resultFFT = dynamic_cast<iqapiResultFFT *>(hndl->results);
if (!strcmp(measurement, "valid"))
{
return((double)resultFFT->valid);
}
else if (!strcmp(measurement, "length"))
{
if (resultFFT->length && resultFFT->length->length > index)
return(resultFFT->length->real[index]);
else
return NA_NUMBER;
}
else
{
return NA_NUMBER;
}
}
else if (dynamic_cast<iqapiResultCCDF *>(hndl->results))
{
resultCCDF = dynamic_cast<iqapiResultCCDF *>(hndl->results);
if (!strcmp(measurement, "percent_pow"))
{
if (resultCCDF->percent_pow && resultCCDF->percent_pow->length > index)
return(resultCCDF->percent_pow->real[index]);
else
return NA_NUMBER;
}
else
{
return NA_NUMBER;
}
}
else if (dynamic_cast<iqapiResultSidelobe *>(hndl->results))
{
resultSidelobe = dynamic_cast<iqapiResultSidelobe *>(hndl->results);
if (!strcmp(measurement, "res_bw_Hz"))
{
if (resultSidelobe->res_bw_Hz && resultSidelobe->res_bw_Hz->length > index)
return(resultSidelobe->res_bw_Hz->real[index]);
else
return NA_NUMBER;
} else if (!strcmp(measurement, "fft_bin_size_Hz"))
{
if (resultSidelobe->fft_bin_size_Hz && resultSidelobe->fft_bin_size_Hz->length > index)
return(resultSidelobe->fft_bin_size_Hz->real[index]);
else
return NA_NUMBER;
} else if (!strcmp(measurement, "peak_center"))
{
if (resultSidelobe->peak_center && resultSidelobe->peak_center->length > index)
return(resultSidelobe->peak_center->real[index]);
else
return NA_NUMBER;
} else if (!strcmp(measurement, "peak_1_left"))
{
if (resultSidelobe->peak_1_left && resultSidelobe->peak_1_left->length > index)
return(resultSidelobe->peak_1_left->real[index]);
else
return NA_NUMBER;
} else if (!strcmp(measurement, "peak_2_left"))
{
if (resultSidelobe->peak_2_left && resultSidelobe->peak_2_left->length > index)
return(resultSidelobe->peak_2_left->real[index]);
else
return NA_NUMBER;
} else if (!strcmp(measurement, "peak_1_right"))
{
if (resultSidelobe->peak_1_right && resultSidelobe->peak_1_right->length > index)
return(resultSidelobe->peak_1_right->real[index]);
else
return NA_NUMBER;
} else if (!strcmp(measurement, "peak_2_right"))
{
if (resultSidelobe->peak_2_right && resultSidelobe->peak_2_right->length > index)
return(resultSidelobe->peak_2_right->real[index]);
else
return NA_NUMBER;
} else if (!strcmp(measurement, "psd_dB"))
{
if (resultSidelobe->psd_dB && resultSidelobe->psd_dB->length > index)
return(resultSidelobe->psd_dB->real[index]);
else
return NA_NUMBER;
}
else
{
return NA_NUMBER;
}
}
else if (dynamic_cast<iqapiResultPowerRamp *>(hndl->results))
{
resultPowerRamp = dynamic_cast<iqapiResultPowerRamp *>(hndl->results);
if (!strcmp(measurement, "on_time"))
{
if (resultPowerRamp->on_time && resultPowerRamp->on_time->length > index)
return(resultPowerRamp->on_time->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "off_time"))
{
if (resultPowerRamp->off_time && resultPowerRamp->off_time->length > index)
return(resultPowerRamp->off_time->real[index]);
else
return NA_NUMBER;
}
else
{
return NA_NUMBER;
}
}
else if (dynamic_cast<iqapiResultBluetooth *>(hndl->results))
{
resultBluetooth = dynamic_cast<iqapiResultBluetooth *>(hndl->results);
if (!strcmp(measurement, "dataRateDetect"))
{
return((double)resultBluetooth->dataRateDetect);
}
if (!strcmp(measurement, "valid"))
{
if (resultBluetooth->valid && resultBluetooth->valid->length > index)
return(resultBluetooth->valid->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "bandwidth20dB"))
{
if (resultBluetooth->bandwidth20dB && resultBluetooth->bandwidth20dB->length > index)
return(resultBluetooth->bandwidth20dB->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "P_av_each_burst"))
{
if (resultBluetooth->P_av_each_burst && resultBluetooth->P_av_each_burst->length > index)
return(resultBluetooth->P_av_each_burst->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "P_pk_each_burst"))
{
if (resultBluetooth->P_pk_each_burst && resultBluetooth->P_pk_each_burst->length > index)
return(resultBluetooth->P_pk_each_burst->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "freq_est"))
{
if (resultBluetooth->freq_est && resultBluetooth->freq_est->length > index)
return(resultBluetooth->freq_est->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "freq_drift"))
{
if (resultBluetooth->freq_drift && resultBluetooth->freq_drift->length > index)
return(resultBluetooth->freq_drift->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "deltaF1Average"))
{
if (resultBluetooth->deltaF1Average && resultBluetooth->deltaF1Average->length > index)
return(resultBluetooth->deltaF1Average->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "deltaF2Max"))
{
if (resultBluetooth->deltaF2Max && resultBluetooth->deltaF2Max->length > index)
return(resultBluetooth->deltaF2Max->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "deltaF2Average"))
{
if (resultBluetooth->deltaF2Average && resultBluetooth->deltaF2Average->length > index)
return(resultBluetooth->deltaF2Average->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "deltaF2MaxAccess"))
{
if (resultBluetooth->deltaF2MaxAccess && resultBluetooth->deltaF2MaxAccess->length > index)
return(resultBluetooth->deltaF2MaxAccess->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "deltaF2AvAccess"))
{
if (resultBluetooth->deltaF2AvAccess && resultBluetooth->deltaF2AvAccess->length > index)
return(resultBluetooth->deltaF2AvAccess->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "EdrEVMAv"))
{
if (resultBluetooth->EdrEVMAv && resultBluetooth->EdrEVMAv->length > index)
return(resultBluetooth->EdrEVMAv->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "EdrEVMpk"))
{
if (resultBluetooth->EdrEVMpk && resultBluetooth->EdrEVMpk->length > index)
return(resultBluetooth->EdrEVMpk->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "EdrEVMvalid"))
{
if (resultBluetooth->EdrEVMvalid && resultBluetooth->EdrEVMvalid->length > index)
return(resultBluetooth->EdrEVMvalid->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "EdrPowDiffdB"))
{
if (resultBluetooth->EdrPowDiffdB && resultBluetooth->EdrPowDiffdB->length > index)
return(resultBluetooth->EdrPowDiffdB->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "freq_deviation"))
{
if (resultBluetooth->freq_deviation && resultBluetooth->freq_deviation->length > index)
return(resultBluetooth->freq_deviation->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "freq_deviationpktopk"))
{
if (resultBluetooth->freq_deviationpktopk && resultBluetooth->freq_deviationpktopk->length > index)
return(resultBluetooth->freq_deviationpktopk->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "freq_estHeader"))
{
if (resultBluetooth->freq_estHeader && resultBluetooth->freq_estHeader->length > index)
return(resultBluetooth->freq_estHeader->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "EdrFreqExtremeEdronly"))
{
if (resultBluetooth->EdrFreqExtremeEdronly && resultBluetooth->EdrFreqExtremeEdronly->length > index)
return(resultBluetooth->EdrFreqExtremeEdronly->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "EdrprobEVM99pass"))
{
if (resultBluetooth->EdrprobEVM99pass && resultBluetooth->EdrprobEVM99pass->length > index)
return(resultBluetooth->EdrprobEVM99pass->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "EdrEVMvsTime"))
{
if (resultBluetooth->EdrEVMvsTime && resultBluetooth->EdrEVMvsTime->length > index)
return(resultBluetooth->EdrEVMvsTime->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "validInput"))
{
if (resultBluetooth->validInput && resultBluetooth->validInput->length > index)
return(resultBluetooth->validInput->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "maxfreqDriftRate"))
{
if (resultBluetooth->maxfreqDriftRate && resultBluetooth->maxfreqDriftRate->length > index)
return(resultBluetooth->maxfreqDriftRate->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "EdrOmegaI"))
{
if (resultBluetooth->EdrOmegaI && resultBluetooth->EdrOmegaI->length > index)
return(resultBluetooth->EdrOmegaI->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "EdrExtremeOmega0"))
{
if (resultBluetooth->EdrExtremeOmega0 && resultBluetooth->EdrExtremeOmega0->length > index)
return(resultBluetooth->EdrExtremeOmega0->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "EdrExtremeOmegaI0"))
{
if (resultBluetooth->EdrExtremeOmegaI0 && resultBluetooth->EdrExtremeOmegaI0->length > index)
return(resultBluetooth->EdrExtremeOmegaI0->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "payloadErrors"))
{
if (resultBluetooth->payloadErrors && resultBluetooth->payloadErrors->length > index)
return(resultBluetooth->payloadErrors->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "maxPowerAcpDbm"))
{
if (resultBluetooth->maxPowerAcpDbm && resultBluetooth->maxPowerAcpDbm->length > index)
return(resultBluetooth->maxPowerAcpDbm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "maxPowerEdrDbm"))
{
if (resultBluetooth->maxPowerEdrDbm && resultBluetooth->maxPowerEdrDbm->length > index)
return(resultBluetooth->maxPowerEdrDbm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "meanNoGapPowerCenterDbm"))
{
if (resultBluetooth->meanNoGapPowerCenterDbm && resultBluetooth->meanNoGapPowerCenterDbm->length > index)
return(resultBluetooth->meanNoGapPowerCenterDbm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "sequenceDefinition"))
{
if (resultBluetooth->sequenceDefinition && resultBluetooth->sequenceDefinition->length > index)
return(resultBluetooth->sequenceDefinition->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "acpErrValid"))
{
return((int)resultBluetooth->acpErrValid);
}
//BT LE
else if (!strcmp(measurement, "leFreqOffset"))
{
if (resultBluetooth->leFreqOffset && resultBluetooth->leFreqOffset->length > index)
return(resultBluetooth->leFreqOffset->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leDeltaF1Avg"))
{
if (resultBluetooth->leDeltaF1Avg && resultBluetooth->leDeltaF1Avg->length > index)
return(resultBluetooth->leDeltaF1Avg->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leDeltaF2Max"))
{
if (resultBluetooth->leDeltaF2Max && resultBluetooth->leDeltaF2Max->length > index)
{
double dF2temp = -NA_NUMBER; // Delta_F2_Max is changed to report whole vector in the IQapi. Thus, it needs to sort out the min. Zhiyong 3/4/2010
dF2temp = resultBluetooth->leDeltaF2Max->real[0];
for(int dF2Ind=1;dF2Ind<resultBluetooth->leDeltaF2Max->length; dF2Ind++)
{
if (dF2temp > resultBluetooth->leDeltaF2Max->real[dF2Ind])
{
dF2temp=resultBluetooth->leDeltaF2Max->real[dF2Ind];
}
}
return(dF2temp);
//return(resultBluetooth->leDeltaF2Max->real[index]);
}
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leDeltaF2Avg"))
{
if (resultBluetooth->leDeltaF2Avg && resultBluetooth->leDeltaF2Avg->length > index)
return(resultBluetooth->leDeltaF2Avg->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leBelow185F2Max"))
{
if (resultBluetooth->leBelow185F2Max && resultBluetooth->leBelow185F2Max->length > index)
return(resultBluetooth->leBelow185F2Max->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leFn"))
{
if (resultBluetooth->leFn && resultBluetooth->leFn->length > index)
return(resultBluetooth->leFn->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leFnMax"))
{
if (resultBluetooth->leFnMax && resultBluetooth->leFnMax->length > index)
return(resultBluetooth->leFnMax->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leDeltaF0FnMax"))
{
if (resultBluetooth->leDeltaF0FnMax && resultBluetooth->leDeltaF0FnMax->length > index)
return(resultBluetooth->leDeltaF0FnMax->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leDeltaF1F0"))
{
if (resultBluetooth->leDeltaF1F0 && resultBluetooth->leDeltaF1F0->length > index)
return(resultBluetooth->leDeltaF1F0->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leDeltaFnFn_5Max"))
{
if (resultBluetooth->leDeltaFnFn_5Max && resultBluetooth->leDeltaFnFn_5Max->length > index)
return(resultBluetooth->leDeltaFnFn_5Max->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leFreqDevSyncAv"))
{
if (resultBluetooth->leFreqDevSyncAv && resultBluetooth->leFreqDevSyncAv->length > index)
return(resultBluetooth->leFreqDevSyncAv->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "lePduLength"))
{
if (resultBluetooth->lePduLength && resultBluetooth->lePduLength->length > index)
return(resultBluetooth->lePduLength->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leIsCrcOk"))
{
if (resultBluetooth->leIsCrcOk && resultBluetooth->leIsCrcOk->length > index)
return(resultBluetooth->leIsCrcOk->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leValid"))
{
if (resultBluetooth->leValid && resultBluetooth->leValid->length > index)
return(resultBluetooth->leValid->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leMaxPowerDbm"))
{
if (resultBluetooth->leMaxPowerDbm && resultBluetooth->leMaxPowerDbm->length > index)
return(resultBluetooth->leMaxPowerDbm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "lePreambleSeq"))
{
if (resultBluetooth->lePreambleSeq && resultBluetooth->lePreambleSeq->length > index)
return(resultBluetooth->lePreambleSeq->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leSyncWordSeq"))
{
if (resultBluetooth->leSyncWordSeq && resultBluetooth->leSyncWordSeq->length > index)
return(resultBluetooth->leSyncWordSeq->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "lePduHeaderSeq"))
{
if (resultBluetooth->lePduHeaderSeq && resultBluetooth->lePduHeaderSeq->length > index)
return(resultBluetooth->lePduHeaderSeq->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "lePduLengthSeq"))
{
if (resultBluetooth->lePduLengthSeq && resultBluetooth->lePduLengthSeq->length > index)
return(resultBluetooth->lePduLengthSeq->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "lePayloadSeq"))
{
if (resultBluetooth->lePayloadSeq && resultBluetooth->lePayloadSeq->length > index)
return(resultBluetooth->lePayloadSeq->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "leCrcSeq"))
{
if (resultBluetooth->leCrcSeq && resultBluetooth->leCrcSeq->length > index)
return(resultBluetooth->leCrcSeq->real[index]);
else
return NA_NUMBER;
}
else
{
return NA_NUMBER;
}
}
// Zigbee
else if (dynamic_cast<iqapiResultZigbee *>(hndl->results))
{
resultZigbee = dynamic_cast<iqapiResultZigbee *>(hndl->results);
if (!strcmp(measurement, "numSymbols"))
{
return((double)resultZigbee->numSymbols);
}
if (!strcmp(measurement, "bValid"))
{
return((double)resultZigbee->bValid);
}
else if (!strcmp(measurement, "rxPeakPower"))
{
if (resultZigbee->rxPeakPower && resultZigbee->rxPeakPower->length > index)
return(resultZigbee->rxPeakPower->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rxRmsPowerAll"))
{
if (resultZigbee->rxRmsPowerAll && resultZigbee->rxRmsPowerAll->length > index)
return(resultZigbee->rxRmsPowerAll->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rxRmsPowerNoGap"))
{
if (resultZigbee->rxRmsPowerNoGap && resultZigbee->rxRmsPowerNoGap->length > index)
return(resultZigbee->rxRmsPowerNoGap->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rxPeakPowerDbm"))
{
if (resultZigbee->rxPeakPowerDbm && resultZigbee->rxPeakPowerDbm->length > index)
return(resultZigbee->rxPeakPowerDbm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rxRmsPowerAllDbm"))
{
if (resultZigbee->rxRmsPowerAllDbm && resultZigbee->rxRmsPowerAllDbm->length > index)
return(resultZigbee->rxRmsPowerAllDbm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rxRmsPowerNoGapDbm"))
{
if (resultZigbee->rxRmsPowerNoGapDbm && resultZigbee->rxRmsPowerNoGapDbm->length > index)
return(resultZigbee->rxRmsPowerNoGapDbm->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "sigType"))
{
if (resultZigbee->sigType && resultZigbee->sigType->length > index)
return(resultZigbee->sigType->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "fsWaveHz"))
{
if (resultZigbee->fsWaveHz && resultZigbee->fsWaveHz->length > index)
return(resultZigbee->fsWaveHz->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "overSampling"))
{
if (resultZigbee->overSampling && resultZigbee->overSampling->length > index)
return(resultZigbee->overSampling->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "evmAll"))
{
if (resultZigbee->evmAll && resultZigbee->evmAll->length > index)
return(resultZigbee->evmAll->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "evmAllOffset"))
{
if (resultZigbee->evmAllOffset && resultZigbee->evmAllOffset->length > index)
return(resultZigbee->evmAllOffset->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "phaseNoiseDegRmsAll"))
{
if (resultZigbee->phaseNoiseDegRmsAll && resultZigbee->phaseNoiseDegRmsAll->length > index)
return(resultZigbee->phaseNoiseDegRmsAll->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "freqOffsetFineHz"))
{
if (resultZigbee->freqOffsetFineHz && resultZigbee->freqOffsetFineHz->length > index)
return(resultZigbee->freqOffsetFineHz->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "symClockErrorPpm"))
{
if (resultZigbee->symClockErrorPpm && resultZigbee->symClockErrorPpm->length > index)
return(resultZigbee->symClockErrorPpm->real[index]);
else
return NA_NUMBER;
}
#if defined(IQAPI_1_5_X)
else if (!strcmp(measurement, "avgPsdu"))
{
if (resultZigbee->avgPsdu && resultZigbee->avgPsdu->length > index)
return(resultZigbee->avgPsdu->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "avgShrPhr"))
{
if (resultZigbee->avgShrPhr && resultZigbee->avgShrPhr->length > index)
return(resultZigbee->avgShrPhr->real[index]);
else
return NA_NUMBER;
}
#else
//RW 01/14/09: IQapi 1.6.2 changed "avgPsdu" to "evmPsdu", "avgShrPhr" to "evmShrPhr"
else if (!strcmp(measurement, "evmPsdu"))
{
if (resultZigbee->evmPsdu && resultZigbee->evmPsdu->length > index)
return(resultZigbee->evmPsdu->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "evmShrPhr"))
{
if (resultZigbee->evmShrPhr && resultZigbee->evmShrPhr->length > index)
return(resultZigbee->evmShrPhr->real[index]);
else
return NA_NUMBER;
}
#endif
}
else if (dynamic_cast<iqapiResultWave *>(hndl->results))
{
resultwave = dynamic_cast<iqapiResultWave *>(hndl->results);
if (!strcmp(measurement, "dcDc"))
{
if (resultwave->dcDc && resultwave->dcDc->length > index)
return(resultwave->dcDc->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "dcRms"))
{
if (resultwave->dcRms && resultwave->dcRms->length > index)
return(resultwave->dcRms->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "dcMin"))
{
if (resultwave->dcMin && resultwave->dcMin->length > index)
return(resultwave->dcMin->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "dcMax"))
{
if (resultwave->dcMax && resultwave->dcMax->length > index)
return(resultwave->dcMax->real[index]);
else
return NA_NUMBER;
}
// else if (!strcmp(measurement, "dcPkToPk"))
// {
// if (resultwave->dcPkToPk && resultwave->dcPkToPk->length > index)
// return(resultwave->dcPkToPk->real[index]);
// else
// return NA_NUMBER;
// }
// else if (!strcmp(measurement, "dcRmsI"))
// {
// if (resultwave->dcRmsI && resultwave->dcRmsI->length > index)
// return(resultwave->dcRmsI->real[index]);
// else
// return NA_NUMBER;
// }
// else if (!strcmp(measurement, "dcRmsQ"))
// {
// if (resultwave->dcRmsQ && resultwave->dcRmsQ->length > index)
// return(resultwave->dcRmsQ->real[index]);
// else
// return NA_NUMBER;
// }
else if (!strcmp(measurement, "acDc"))
{
if (resultwave->acDc && resultwave->acDc->length > index)
return(resultwave->acDc->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "acRms"))
{
if (resultwave->acRms && resultwave->acRms->length > index)
return(resultwave->acRms->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "acMin"))
{
if (resultwave->acMin && resultwave->acMin->length > index)
return(resultwave->acMin->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "acMax"))
{
if (resultwave->acMax && resultwave->acMax->length > index)
return(resultwave->acMax->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "acPkToPk"))
{
if (resultwave->acPkToPk && resultwave->acPkToPk->length > index)
return(resultwave->acPkToPk->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "acRmsI"))
{
if (resultwave->acRmsI && resultwave->acRmsI->length > index)
return(resultwave->acRmsI->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "acRmsQ"))
{
if (resultwave->acRmsQ && resultwave->acRmsQ->length > index)
return(resultwave->acRmsQ->real[index]);
else
return NA_NUMBER;
}
else if (!strcmp(measurement, "rmsDb"))
{
if (resultwave->rmsDb && resultwave->rmsDb->length > index)
return(resultwave->rmsDb->real[index]);
else
return NA_NUMBER;
}
}
else if (dynamic_cast<iqapiResultCW *>(hndl->results))
{
resultCW = dynamic_cast<iqapiResultCW *>(hndl->results);
if (!strcmp(measurement, "frequency"))
{
return resultCW->frequency;
}
}
else
return NA_NUMBER;
}
}
return NA_NUMBER;
}
IQMEASURE_API double LP_GetScalarMeasurement(char *measurement, int index)
{
::TIMER_StartTimer(timerIQmeasure, "LP_GetScalarMeasurement", &timeStart);
double value = LP_GetScalarMeasurement_NoTimer(measurement, index);
::TIMER_StopTimer(timerIQmeasure, "LP_GetScalarMeasurement", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_GetScalarMeasurement", timeDuration);
return value;
}
// Keep this function with typo for backward compatibility
IQMEASURE_API int LP_GetVectorMeasurment(char *measurement, double bufferReal[], double bufferImag[], int bufferLength)
{
return LP_GetVectorMeasurement(measurement, bufferReal, bufferImag, bufferLength);
}
/*! @defgroup group_vector_measurement Available Measurement Names for LP_GetVectorMeasurement()
*
* Available measurement names vary for various analysis. After an analysis has been performed successfully, by calling
* one of the following functions:
* - LP_Analyze80211ag();
* - LP_AnalyzeMimo();
* - LP_Analyze80211b();
* - LP_Analyze80216d();
* - LP_Analyze80216e();
* - LP_AnalyzePower();
* - LP_AnalyzeFFT();
* - LP_AnalyzeCCDF();
* - LP_AnalyzeCW();
* - LP_AnalysisWave();
* - LP_AnalyzeSidelobe();
* - LP_AnalyzePowerRampOFDM();
* - LP_AnalyzePowerRamp80211b();
* - LP_AnalyzeBluetooth();
* - LP_AnalyzeZigbee();
*/
IQMEASURE_API int LP_GetVectorMeasurement_NoTimer(char *measurement, double bufferReal[], double bufferImag[], int bufferLength)
{
if (LibsInitialized)
{
if (!hndl->results || !bufferReal || !bufferLength)
{
return 0;
}
else
{
if (dynamic_cast<iqapiResultOFDM *>(hndl->results))
{
resultOfdm = dynamic_cast<iqapiResultOFDM *>(hndl->results);
if (!strcmp(measurement, "hhEst"))
{
if (resultOfdm->hhEst && resultOfdm->hhEst->length)
{
if (bufferLength > resultOfdm->hhEst->length)
bufferLength = resultOfdm->hhEst->length;
memcpy(bufferReal, resultOfdm->hhEst->real, (sizeof(double)*bufferLength));
if (resultOfdm->hhEst->imag && bufferImag)
memcpy(bufferImag, resultOfdm->hhEst->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
{
return 0;
}
}
else if (!strcmp(measurement, "spectralFlatness"))
{
if (resultOfdm->spectralFlatness && resultOfdm->spectralFlatness->length)
{
if (bufferLength > resultOfdm->spectralFlatness->length)
bufferLength = resultOfdm->spectralFlatness->length;
memcpy(bufferReal, resultOfdm->spectralFlatness->real, (sizeof(double)*bufferLength));
if (resultOfdm->spectralFlatness->imag && bufferImag)
memcpy(bufferImag, resultOfdm->spectralFlatness->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "spectralFlatnessHighLimit"))
{
if (resultOfdm->spectralFlatnessHighLimit && resultOfdm->spectralFlatnessHighLimit->length)
{
if (bufferLength > resultOfdm->spectralFlatnessHighLimit->length)
bufferLength = resultOfdm->spectralFlatnessHighLimit->length;
memcpy(bufferReal, resultOfdm->spectralFlatnessHighLimit->real, (sizeof(double)*bufferLength));
if (resultOfdm->spectralFlatnessHighLimit->imag && bufferImag)
memcpy(bufferImag, resultOfdm->spectralFlatnessHighLimit->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "spectralFlatnessLowLimit"))
{
if (resultOfdm->spectralFlatnessLowLimit && resultOfdm->spectralFlatnessLowLimit->length)
{
if (bufferLength > resultOfdm->spectralFlatnessLowLimit->length)
bufferLength = resultOfdm->spectralFlatnessLowLimit->length;
memcpy(bufferReal, resultOfdm->spectralFlatnessLowLimit->real, (sizeof(double)*bufferLength));
if (resultOfdm->spectralFlatnessLowLimit->imag && bufferImag)
memcpy(bufferImag, resultOfdm->spectralFlatnessLowLimit->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "psdu"))
{
if (resultOfdm->psdu && resultOfdm->psdu->length)
{
if (bufferLength > resultOfdm->psdu->length)
bufferLength = resultOfdm->psdu->length;
memcpy(bufferReal, resultOfdm->psdu->real, (sizeof(double)*bufferLength));
if (resultOfdm->psdu->imag && bufferImag)
memcpy(bufferImag, resultOfdm->psdu->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
{
return 0;
}
}
else if (!strcmp(measurement, "startPointers"))
{
if (resultOfdm->startPointers && resultOfdm->startPointers->length)
{
if (bufferLength > resultOfdm->startPointers->length)
bufferLength = resultOfdm->startPointers->length;
memcpy(bufferReal, resultOfdm->startPointers->real, (sizeof(double)*bufferLength));
if (resultOfdm->startPointers->imag && bufferImag)
memcpy(bufferImag, resultOfdm->startPointers->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
{
return 0;
}
}
else if (!strcmp(measurement, "plcp"))
{
if (resultOfdm->plcp && resultOfdm->plcp->length)
{
if (bufferLength > resultOfdm->plcp->length)
bufferLength = resultOfdm->plcp->length;
memcpy(bufferReal, resultOfdm->plcp->real, (sizeof(double)*bufferLength));
if (resultOfdm->plcp->imag && bufferImag)
memcpy(bufferImag, resultOfdm->plcp->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
{
return 0;
}
}
}
if (dynamic_cast<iqapiResultWave *>(hndl->results))
{
resultwave = dynamic_cast<iqapiResultWave *>(hndl->results);
if (!strcmp(measurement, "dcPkToPk"))
{
if (resultwave->dcPkToPk && resultwave->dcPkToPk->length)
{
if (bufferLength > resultwave->dcPkToPk->length)
bufferLength = resultwave->dcPkToPk->length;
memcpy(bufferReal, resultwave->dcPkToPk->real, (sizeof(double)*bufferLength));
if (resultwave->dcPkToPk->imag && bufferImag)
memcpy(bufferImag, resultwave->dcPkToPk->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
{
return 0;
}
}
if (!strcmp(measurement, "dcRmsI"))
{
if (resultwave->dcRmsI && resultwave->dcRmsI->length)
{
if (bufferLength > resultwave->dcRmsI->length)
bufferLength = resultwave->dcRmsI->length;
memcpy(bufferReal, resultwave->dcRmsI->real, (sizeof(double)*bufferLength));
if (resultwave->dcRmsI->imag && bufferImag)
memcpy(bufferImag, resultwave->dcRmsI->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
{
return 0;
}
}
if (!strcmp(measurement, "dcRmsQ"))
{
if (resultwave->dcRmsQ && resultwave->dcRmsQ->length)
{
if (bufferLength > resultwave->dcRmsQ->length)
bufferLength = resultwave->dcRmsQ->length;
memcpy(bufferReal, resultwave->dcRmsQ->real, (sizeof(double)*bufferLength));
if (resultwave->dcRmsQ->imag && bufferImag)
memcpy(bufferImag, resultwave->dcRmsQ->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
{
return 0;
}
}
}
if (dynamic_cast<iqapiResult11b *>(hndl->results))
{
result11b = dynamic_cast<iqapiResult11b *>(hndl->results);
if (!strcmp(measurement, "evmInPlcp"))
{
if (result11b->evmInPlcp && result11b->evmInPlcp->length)
{
if (bufferLength > result11b->evmInPlcp->length)
bufferLength = result11b->evmInPlcp->length;
memcpy(bufferReal, result11b->evmInPlcp->real, (sizeof(double)*bufferLength));
if (result11b->evmInPlcp->imag && bufferImag)
memcpy(bufferImag, result11b->evmInPlcp->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
{
return 0;
}
}
else if (!strcmp(measurement, "evmErr"))
{
if (result11b->evmErr && result11b->evmErr->length)
{
if (bufferLength > result11b->evmErr->length)
bufferLength = result11b->evmErr->length;
memcpy(bufferReal, result11b->evmErr->real, (sizeof(double)*bufferLength));
if (result11b->evmErr->imag && bufferImag)
memcpy(bufferImag, result11b->evmErr->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
{
return 0;
}
}
else if (!strcmp(measurement, "loLeakageDb"))
{
if (result11b->loLeakageDb && result11b->loLeakageDb->length)
{
if (bufferLength > result11b->loLeakageDb->length)
bufferLength = result11b->loLeakageDb->length;
memcpy(bufferReal, result11b->loLeakageDb->real, (sizeof(double)*bufferLength));
if (result11b->loLeakageDb->imag && bufferImag)
memcpy(bufferImag, result11b->loLeakageDb->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
{
return 0;
}
}
}
else if (dynamic_cast<iqapiResultFFT *>(hndl->results))
{
resultFFT = dynamic_cast<iqapiResultFFT *>(hndl->results);
if (!strcmp(measurement, "x"))
{
if (resultFFT->x && resultFFT->x->length)
{
if (bufferLength > resultFFT->x->length)
bufferLength = resultFFT->x->length;
memcpy(bufferReal, resultFFT->x->real, (sizeof(double)*bufferLength));
if (resultFFT->x->imag && bufferImag)
memcpy(bufferImag, resultFFT->x->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "y"))
{
if (resultFFT->y && resultFFT->y->length)
{
if (bufferLength > resultFFT->y->length)
bufferLength = resultFFT->y->length;
memcpy(bufferReal, resultFFT->y->real, (sizeof(double)*bufferLength));
if (resultFFT->y->imag && bufferImag)
memcpy(bufferImag, resultFFT->y->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
}
else if (dynamic_cast<iqapiResult80216 *>(hndl->results))
{
result80216 = dynamic_cast<iqapiResult80216 *>(hndl->results);
if (!strcmp(measurement, "channelEst"))
{
if (result80216->channelEst && result80216->channelEst->length)
{
if (bufferLength >result80216->channelEst->length)
bufferLength = result80216->channelEst->length;
memcpy(bufferReal, result80216->channelEst->real, (sizeof(double)*bufferLength));
if (result80216->channelEst->imag && bufferImag)
memcpy(bufferImag, result80216->channelEst->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
if (!strcmp(measurement, "analyzedRange"))
{
if (result80216->analyzedRange && result80216->analyzedRange->length)
{
if (bufferLength >result80216->analyzedRange->length)
bufferLength = result80216->analyzedRange->length;
memcpy(bufferReal, result80216->analyzedRange->real, (sizeof(double)*bufferLength));
if (result80216->channelEst->imag && bufferImag)
memcpy(bufferImag, result80216->analyzedRange->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
// if (!strcmp(measurement, "numSymbols"))
// {
// if (result80216->numSymbols && result80216->numSymbols->length)
// {
// if (bufferLength >result80216->numSymbols->length)
// bufferLength = result80216->numSymbols->length;
// memcpy(bufferReal, result80216->numSymbols->real, (sizeof(double)*bufferLength));
//
// if (result80216->numSymbols->imag && bufferImag)
// memcpy(bufferImag, result80216->numSymbols->imag, (sizeof(double)*bufferLength));
// return(bufferLength);
// }
// else
// return 0;
// }
if (!strcmp(measurement, "rateId"))
{
if (result80216->rateId && result80216->rateId->length)
{
if (bufferLength >result80216->rateId->length)
bufferLength = result80216->rateId->length;
memcpy(bufferReal, result80216->rateId->real, (sizeof(double)*bufferLength));
if (result80216->rateId->imag && bufferImag)
memcpy(bufferImag, result80216->rateId->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
if (!strcmp(measurement, "demodSymbols"))
{
if (result80216->demodSymbols && result80216->demodSymbols->length)
{
if (bufferLength >result80216->demodSymbols->length)
bufferLength = result80216->demodSymbols->length;
memcpy(bufferReal, result80216->demodSymbols->real, (sizeof(double)*bufferLength));
if (result80216->demodSymbols->imag && bufferImag)
memcpy(bufferImag, result80216->demodSymbols->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else
{
return 0;
}
}
//Z-99
//else if (dynamic_cast<iqapiResult11ac *>(hndl->results))
else if (dynamic_cast<iqapiResultWifiOfdm *>(hndl->results))
{
//Z-99
//result11ac = dynamic_cast<iqapiResult11ac *>(hndl->results);
result11ac = dynamic_cast<iqapiResultWifiOfdm *>(hndl->results);
if (!strcmp(measurement, "channelEst"))
{
if (result11ac->channelEst && result11ac->channelEst->length)
{
if (bufferLength > result11ac->channelEst->length)
bufferLength = result11ac->channelEst->length;
memcpy(bufferReal, result11ac->channelEst->real, (sizeof(double)*bufferLength));
if (result11ac->channelEst->imag && bufferImag)
memcpy(bufferImag, result11ac->channelEst->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "spectralFlatness"))
{
if (result11ac->spectralFlatness && result11ac->spectralFlatness->length)
{
if (bufferLength > result11ac->spectralFlatness->length)
bufferLength = result11ac->spectralFlatness->length;
memcpy(bufferReal, result11ac->spectralFlatness->real, (sizeof(double)*bufferLength));
if (result11ac->spectralFlatness->imag && bufferImag)
memcpy(bufferImag, result11ac->spectralFlatness->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "spectralFlatnessHighLimit"))
{
if (result11ac->spectralFlatnessHighLimit && result11ac->spectralFlatnessHighLimit->length)
{
if (bufferLength > result11ac->spectralFlatnessHighLimit->length)
bufferLength = result11ac->spectralFlatnessHighLimit->length;
memcpy(bufferReal, result11ac->spectralFlatnessHighLimit->real, (sizeof(double)*bufferLength));
if (result11ac->spectralFlatnessHighLimit->imag && bufferImag)
memcpy(bufferImag, result11ac->spectralFlatnessHighLimit->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "spectralFlatnessLowLimit"))
{
if (result11ac->spectralFlatnessLowLimit && result11ac->spectralFlatnessLowLimit->length)
{
if (bufferLength > result11ac->spectralFlatnessLowLimit->length)
bufferLength = result11ac->spectralFlatnessLowLimit->length;
memcpy(bufferReal, result11ac->spectralFlatnessLowLimit->real, (sizeof(double)*bufferLength));
if (result11ac->spectralFlatnessLowLimit->imag && bufferImag)
memcpy(bufferImag, result11ac->spectralFlatnessLowLimit->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "rxRmsPowerDb"))
{
if (result11ac->rxRmsPowerDb && result11ac->rxRmsPowerDb->length)
{
if (bufferLength > result11ac->rxRmsPowerDb->length)
bufferLength = result11ac->rxRmsPowerDb->length;
//double *tempBuffer = new double[bufferLength];
//if( analysisMimo->SequentialMimo.numSections>0 )
//{
// for(int i=0; i<result11ac->rxRmsPowerDb->length; i++)
// {
// tempBuffer[i] = result11ac->rxRmsPowerDb->real[i] + attn[i/analysisMimo->SequentialMimo.numSections];
// }
//}
//memcpy(bufferReal, tempBuffer, (sizeof(double)*bufferLength));
//delete[] tempBuffer;
memcpy(bufferReal, result11ac->rxRmsPowerDb->real, (sizeof(double)*bufferLength));
if (result11ac->rxRmsPowerDb->imag && bufferImag)
memcpy(bufferImag, result11ac->rxRmsPowerDb->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "isolationDb"))
{
if(result11ac->isolationDb && result11ac->isolationDb->length)
{
if (bufferLength > result11ac->isolationDb->length)
bufferLength = result11ac->isolationDb->length;
memcpy(bufferReal, result11ac->isolationDb->real, (sizeof(double)*bufferLength));
if (result11ac->isolationDb->imag && bufferImag)
memcpy(bufferImag, result11ac->isolationDb->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "evmSymbols"))
{
if (result11ac->evmSymbols && result11ac->evmSymbols->length)
{
if (bufferLength > result11ac->evmSymbols->length)
bufferLength = result11ac->evmSymbols->length;
memcpy(bufferReal, result11ac->evmSymbols->real, (sizeof(double)*bufferLength));
if (result11ac->evmSymbols->imag && bufferImag)
memcpy(bufferImag, result11ac->evmSymbols->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "evmTones"))
{
if (result11ac->evmTones && result11ac->evmTones->length)
{
if (bufferLength > result11ac->evmTones->length)
bufferLength = result11ac->evmTones->length;
memcpy(bufferReal, result11ac->evmTones->real, (sizeof(double)*bufferLength));
if (result11ac->evmTones->imag && bufferImag)
memcpy(bufferImag, result11ac->evmTones->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "PhaseNoiseDeg_Symbols"))
{
if (result11ac->PhaseNoiseDeg_Symbols && result11ac->PhaseNoiseDeg_Symbols->length)
{
if (bufferLength > result11ac->PhaseNoiseDeg_Symbols->length)
bufferLength = result11ac->PhaseNoiseDeg_Symbols->length;
memcpy(bufferReal, result11ac->PhaseNoiseDeg_Symbols->real, (sizeof(double)*bufferLength));
if (result11ac->PhaseNoiseDeg_Symbols->imag && bufferImag)
memcpy(bufferImag, result11ac->PhaseNoiseDeg_Symbols->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "demodSymbols"))
{
if (result11ac->demodSymbols && result11ac->demodSymbols->length)
{
if (bufferLength > result11ac->demodSymbols->length)
bufferLength = result11ac->demodSymbols->length;
memcpy(bufferReal, result11ac->demodSymbols->real, (sizeof(double)*bufferLength));
if (result11ac->demodSymbols->imag && bufferImag)
memcpy(bufferImag, result11ac->demodSymbols->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "psduBits"))
{
if (result11ac->psduBits && result11ac->psduBits->length)
{
if (bufferLength > result11ac->psduBits->length)
bufferLength = result11ac->psduBits->length;
memcpy(bufferReal, result11ac->psduBits->real, (sizeof(double)*bufferLength));
if (result11ac->psduBits->imag && bufferImag)
memcpy(bufferImag, result11ac->psduBits->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
{
return 0;
}
}
else
{
return 0;
}
}
else if (dynamic_cast<iqapiResultMimo *>(hndl->results))
{
resultMimo = dynamic_cast<iqapiResultMimo *>(hndl->results);
if (!strcmp(measurement, "channelEst"))
{
if (resultMimo->channelEst && resultMimo->channelEst->length)
{
if (bufferLength > resultMimo->channelEst->length)
bufferLength = resultMimo->channelEst->length;
memcpy(bufferReal, resultMimo->channelEst->real, (sizeof(double)*bufferLength));
if (resultMimo->channelEst->imag && bufferImag)
memcpy(bufferImag, resultMimo->channelEst->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "spectralFlatness"))
{
if (resultMimo->spectralFlatness && resultMimo->spectralFlatness->length)
{
if (bufferLength > resultMimo->spectralFlatness->length)
bufferLength = resultMimo->spectralFlatness->length;
memcpy(bufferReal, resultMimo->spectralFlatness->real, (sizeof(double)*bufferLength));
if (resultMimo->spectralFlatness->imag && bufferImag)
memcpy(bufferImag, resultMimo->spectralFlatness->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "spectralFlatnessHighLimit"))
{
if (resultMimo->spectralFlatnessHighLimit && resultMimo->spectralFlatnessHighLimit->length)
{
if (bufferLength > resultMimo->spectralFlatnessHighLimit->length)
bufferLength = resultMimo->spectralFlatnessHighLimit->length;
memcpy(bufferReal, resultMimo->spectralFlatnessHighLimit->real, (sizeof(double)*bufferLength));
if (resultMimo->spectralFlatnessHighLimit->imag && bufferImag)
memcpy(bufferImag, resultMimo->spectralFlatnessHighLimit->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "spectralFlatnessLowLimit"))
{
if (resultMimo->spectralFlatnessLowLimit && resultMimo->spectralFlatnessLowLimit->length)
{
if (bufferLength > resultMimo->spectralFlatnessLowLimit->length)
bufferLength = resultMimo->spectralFlatnessLowLimit->length;
memcpy(bufferReal, resultMimo->spectralFlatnessLowLimit->real, (sizeof(double)*bufferLength));
if (resultMimo->spectralFlatnessLowLimit->imag && bufferImag)
memcpy(bufferImag, resultMimo->spectralFlatnessLowLimit->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "rxRmsPowerDb"))
{
if (resultMimo->rxRmsPowerDb && resultMimo->rxRmsPowerDb->length)
{
if (bufferLength > resultMimo->rxRmsPowerDb->length)
bufferLength = resultMimo->rxRmsPowerDb->length;
//double *tempBuffer = new double[bufferLength];
//if( analysisMimo->SequentialMimo.numSections>0 )
//{
// for(int i=0; i<resultMimo->rxRmsPowerDb->length; i++)
// {
// tempBuffer[i] = resultMimo->rxRmsPowerDb->real[i] + attn[i/analysisMimo->SequentialMimo.numSections];
// }
//}
//memcpy(bufferReal, tempBuffer, (sizeof(double)*bufferLength));
//delete[] tempBuffer;
memcpy(bufferReal, resultMimo->rxRmsPowerDb->real, (sizeof(double)*bufferLength));
if (resultMimo->rxRmsPowerDb->imag && bufferImag)
memcpy(bufferImag, resultMimo->rxRmsPowerDb->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "isolationDb"))
{
if (resultMimo->isolationDb && resultMimo->isolationDb->length)
{
if (bufferLength > resultMimo->isolationDb->length)
bufferLength = resultMimo->isolationDb->length;
memcpy(bufferReal, resultMimo->isolationDb->real, (sizeof(double)*bufferLength));
if (resultMimo->isolationDb->imag && bufferImag)
memcpy(bufferImag, resultMimo->isolationDb->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "evmSymbols"))
{
if (resultMimo->evmSymbols && resultMimo->evmSymbols->length)
{
if (bufferLength > resultMimo->evmSymbols->length)
bufferLength = resultMimo->evmSymbols->length;
memcpy(bufferReal, resultMimo->evmSymbols->real, (sizeof(double)*bufferLength));
if (resultMimo->evmSymbols->imag && bufferImag)
memcpy(bufferImag, resultMimo->evmSymbols->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "evmTones"))
{
if (resultMimo->evmTones && resultMimo->evmTones->length)
{
if (bufferLength > resultMimo->evmTones->length)
bufferLength = resultMimo->evmTones->length;
memcpy(bufferReal, resultMimo->evmTones->real, (sizeof(double)*bufferLength));
if (resultMimo->evmTones->imag && bufferImag)
memcpy(bufferImag, resultMimo->evmTones->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "PhaseNoiseDeg_Symbols"))
{
if (resultMimo->PhaseNoiseDeg_Symbols && resultMimo->PhaseNoiseDeg_Symbols->length)
{
if (bufferLength > resultMimo->PhaseNoiseDeg_Symbols->length)
bufferLength = resultMimo->PhaseNoiseDeg_Symbols->length;
memcpy(bufferReal, resultMimo->PhaseNoiseDeg_Symbols->real, (sizeof(double)*bufferLength));
if (resultMimo->PhaseNoiseDeg_Symbols->imag && bufferImag)
memcpy(bufferImag, resultMimo->PhaseNoiseDeg_Symbols->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "demodSymbols"))
{
if (resultMimo->demodSymbols && resultMimo->demodSymbols->length)
{
if (bufferLength > resultMimo->demodSymbols->length)
bufferLength = resultMimo->demodSymbols->length;
memcpy(bufferReal, resultMimo->demodSymbols->real, (sizeof(double)*bufferLength));
if (resultMimo->demodSymbols->imag && bufferImag)
memcpy(bufferImag, resultMimo->demodSymbols->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else
{
return 0;
}
}
else if (dynamic_cast<iqapiResultZigbee *>(hndl->results))
{
resultZigbee = dynamic_cast<iqapiResultZigbee *>(hndl->results);
if (!strcmp(measurement, "evmSymbols"))
{
if (resultZigbee->evmSymbols && resultZigbee->evmSymbols->length)
{
if (bufferLength > resultZigbee->evmSymbols->length)
bufferLength = resultZigbee->evmSymbols->length;
memcpy(bufferReal, resultZigbee->evmSymbols->real, (sizeof(double)*bufferLength));
if (resultZigbee->evmSymbols->imag && bufferImag)
memcpy(bufferImag, resultZigbee->evmSymbols->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "constData"))
{
if (resultZigbee->constData && resultZigbee->constData->length)
{
if (bufferLength > resultZigbee->constData->length)
bufferLength = resultZigbee->constData->length;
memcpy(bufferReal, resultZigbee->constData->real, (sizeof(double)*bufferLength));
if (resultZigbee->constData->imag && bufferImag)
memcpy(bufferImag, resultZigbee->constData->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "phaseNoiseDegError"))
{
if (resultZigbee->phaseNoiseDegError && resultZigbee->phaseNoiseDegError->length)
{
if (bufferLength > resultZigbee->phaseNoiseDegError->length)
bufferLength = resultZigbee->phaseNoiseDegError->length;
memcpy(bufferReal, resultZigbee->phaseNoiseDegError->real, (sizeof(double)*bufferLength));
if (resultZigbee->phaseNoiseDegError->imag && bufferImag)
memcpy(bufferImag, resultZigbee->phaseNoiseDegError->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "eyeDiagramData"))
{
if (resultZigbee->eyeDiagramData && resultZigbee->eyeDiagramData->length)
{
if (bufferLength > resultZigbee->eyeDiagramData->length)
bufferLength = resultZigbee->eyeDiagramData->length;
memcpy(bufferReal, resultZigbee->eyeDiagramData->real, (sizeof(double)*bufferLength));
if (resultZigbee->eyeDiagramData->imag && bufferImag)
memcpy(bufferImag, resultZigbee->eyeDiagramData->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "eyeDiagramTime"))
{
if (resultZigbee->eyeDiagramTime && resultZigbee->eyeDiagramTime->length)
{
if (bufferLength > resultZigbee->eyeDiagramTime->length)
bufferLength = resultZigbee->eyeDiagramTime->length;
memcpy(bufferReal, resultZigbee->eyeDiagramTime->real, (sizeof(double)*bufferLength));
if (resultZigbee->eyeDiagramTime->imag && bufferImag)
memcpy(bufferImag, resultZigbee->eyeDiagramTime->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "codeDomain"))
{
if (resultZigbee->codeDomain && resultZigbee->codeDomain->length)
{
if (bufferLength > resultZigbee->codeDomain->length)
bufferLength = resultZigbee->codeDomain->length;
memcpy(bufferReal, resultZigbee->codeDomain->real, (sizeof(double)*bufferLength));
if (resultZigbee->codeDomain->imag && bufferImag)
memcpy(bufferImag, resultZigbee->codeDomain->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else
{
return 0;
}
}
else if (dynamic_cast<iqapiResultCCDF *>(hndl->results))
{
resultCCDF = dynamic_cast<iqapiResultCCDF *>(hndl->results);
if (!strcmp(measurement, "prob"))
{
if (resultCCDF->prob && resultCCDF->prob->length)
{
if (bufferLength > resultCCDF->prob->length)
bufferLength = resultCCDF->prob->length;
memcpy(bufferReal, resultCCDF->prob->real, (sizeof(double)*bufferLength));
if (resultCCDF->prob->imag && bufferImag)
memcpy(bufferImag, resultCCDF->prob->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "power_rel_dB"))
{
if (resultCCDF->power_rel_dB && resultCCDF->power_rel_dB->length)
{
if (bufferLength > resultCCDF->power_rel_dB->length)
bufferLength = resultCCDF->power_rel_dB->length;
memcpy(bufferReal, resultCCDF->power_rel_dB->real, (sizeof(double)*bufferLength));
if (resultCCDF->power_rel_dB->imag && bufferImag)
memcpy(bufferImag, resultCCDF->power_rel_dB->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
}
else if (dynamic_cast<iqapiResultPowerRamp *>(hndl->results))
{
resultPowerRamp = dynamic_cast<iqapiResultPowerRamp *>(hndl->results);
if (!strcmp(measurement, "on_mask_x"))
{
if (resultPowerRamp->on_mask_x && resultPowerRamp->on_mask_x->length)
{
if (bufferLength > resultPowerRamp->on_mask_x->length)
bufferLength = resultPowerRamp->on_mask_x->length;
memcpy(bufferReal, resultPowerRamp->on_mask_x->real, (sizeof(double)*bufferLength));
if (resultPowerRamp->on_mask_x->imag && bufferImag)
memcpy(bufferImag, resultPowerRamp->on_mask_x->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "off_mask_x"))
{
if (resultPowerRamp->off_mask_x && resultPowerRamp->off_mask_x->length)
{
if (bufferLength > resultPowerRamp->off_mask_x->length)
bufferLength = resultPowerRamp->off_mask_x->length;
memcpy(bufferReal, resultPowerRamp->off_mask_x->real, (sizeof(double)*bufferLength));
if (resultPowerRamp->off_mask_x->imag && bufferImag)
memcpy(bufferImag, resultPowerRamp->off_mask_x->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "on_mask_y"))
{
if (resultPowerRamp->on_mask_y && resultPowerRamp->on_mask_y->length)
{
if (bufferLength > resultPowerRamp->on_mask_y->length)
bufferLength = resultPowerRamp->on_mask_y->length;
memcpy(bufferReal, resultPowerRamp->on_mask_y->real, (sizeof(double)*bufferLength));
if (resultPowerRamp->on_mask_y->imag && bufferImag)
memcpy(bufferImag, resultPowerRamp->on_mask_y->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "off_mask_y"))
{
if (resultPowerRamp->off_mask_y && resultPowerRamp->off_mask_y->length)
{
if (bufferLength > resultPowerRamp->off_mask_y->length)
bufferLength = resultPowerRamp->off_mask_y->length;
memcpy(bufferReal, resultPowerRamp->off_mask_y->real, (sizeof(double)*bufferLength));
if (resultPowerRamp->off_mask_y->imag && bufferImag)
memcpy(bufferImag, resultPowerRamp->off_mask_y->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "on_power_inst"))
{
if (resultPowerRamp->on_power_inst && resultPowerRamp->on_power_inst->length)
{
if (bufferLength > resultPowerRamp->on_power_inst->length)
bufferLength = resultPowerRamp->on_power_inst->length;
memcpy(bufferReal, resultPowerRamp->on_power_inst->real, (sizeof(double)*bufferLength));
if (resultPowerRamp->on_power_inst->imag && bufferImag)
memcpy(bufferImag, resultPowerRamp->on_power_inst->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "off_power_inst"))
{
if (resultPowerRamp->off_power_inst && resultPowerRamp->off_power_inst->length)
{
if (bufferLength > resultPowerRamp->off_power_inst->length)
bufferLength = resultPowerRamp->off_power_inst->length;
memcpy(bufferReal, resultPowerRamp->off_power_inst->real, (sizeof(double)*bufferLength));
if (resultPowerRamp->off_power_inst->imag && bufferImag)
memcpy(bufferImag, resultPowerRamp->off_power_inst->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "on_power_peak"))
{
if (resultPowerRamp->on_power_peak && resultPowerRamp->on_power_peak->length)
{
if (bufferLength > resultPowerRamp->on_power_peak->length)
bufferLength = resultPowerRamp->on_power_peak->length;
memcpy(bufferReal, resultPowerRamp->on_power_peak->real, (sizeof(double)*bufferLength));
if (resultPowerRamp->on_power_peak->imag && bufferImag)
memcpy(bufferImag, resultPowerRamp->on_power_peak->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "off_power_peak"))
{
if (resultPowerRamp->off_power_peak && resultPowerRamp->off_power_peak->length)
{
if (bufferLength > resultPowerRamp->off_power_peak->length)
bufferLength = resultPowerRamp->off_power_peak->length;
memcpy(bufferReal, resultPowerRamp->off_power_peak->real, (sizeof(double)*bufferLength));
if (resultPowerRamp->off_power_peak->imag && bufferImag)
memcpy(bufferImag, resultPowerRamp->off_power_peak->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "on_time_vect"))
{
if (resultPowerRamp->on_time_vect && resultPowerRamp->on_time_vect->length)
{
if (bufferLength > resultPowerRamp->on_time_vect->length)
bufferLength = resultPowerRamp->on_time_vect->length;
memcpy(bufferReal, resultPowerRamp->on_time_vect->real, (sizeof(double)*bufferLength));
if (resultPowerRamp->on_time_vect->imag && bufferImag)
memcpy(bufferImag, resultPowerRamp->on_time_vect->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
} else if (!strcmp(measurement, "off_time_vect"))
{
if (resultPowerRamp->off_time_vect && resultPowerRamp->off_time_vect->length)
{
if (bufferLength > resultPowerRamp->off_time_vect->length)
bufferLength = resultPowerRamp->off_time_vect->length;
memcpy(bufferReal, resultPowerRamp->off_time_vect->real, (sizeof(double)*bufferLength));
if (resultPowerRamp->off_time_vect->imag && bufferImag)
memcpy(bufferImag, resultPowerRamp->off_time_vect->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else
{
return 0;
}
}
else if (dynamic_cast<iqapiResultBluetooth *>(hndl->results))
{
resultBluetooth = dynamic_cast<iqapiResultBluetooth *>(hndl->results);
if (!strcmp(measurement, "P_av_each_burst"))
{
if (resultBluetooth->P_av_each_burst && resultBluetooth->P_av_each_burst->length)
{
if (bufferLength > resultBluetooth->P_av_each_burst->length)
bufferLength = resultBluetooth->P_av_each_burst->length;
memcpy(bufferReal, resultBluetooth->P_av_each_burst->real, (sizeof(double)*bufferLength));
if (resultBluetooth->P_av_each_burst->imag && bufferImag)
memcpy(bufferImag, resultBluetooth->P_av_each_burst->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "P_pk_each_burst"))
{
if (resultBluetooth->P_pk_each_burst && resultBluetooth->P_pk_each_burst->length)
{
if (bufferLength > resultBluetooth->P_pk_each_burst->length)
bufferLength = resultBluetooth->P_pk_each_burst->length;
memcpy(bufferReal, resultBluetooth->P_pk_each_burst->real, (sizeof(double)*bufferLength));
if (resultBluetooth->P_pk_each_burst->imag && bufferImag)
memcpy(bufferImag, resultBluetooth->P_pk_each_burst->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "complete_burst"))
{
if (resultBluetooth->complete_burst && resultBluetooth->complete_burst->length)
{
if (bufferLength > resultBluetooth->complete_burst->length)
bufferLength = resultBluetooth->complete_burst->length;
memcpy(bufferReal, resultBluetooth->complete_burst->real, (sizeof(double)*bufferLength));
if (resultBluetooth->complete_burst->imag && bufferImag)
memcpy(bufferImag, resultBluetooth->complete_burst->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "start_sec"))
{
if (resultBluetooth->start_sec && resultBluetooth->start_sec->length)
{
if (bufferLength > resultBluetooth->start_sec->length)
bufferLength = resultBluetooth->start_sec->length;
memcpy(bufferReal, resultBluetooth->start_sec->real, (sizeof(double)*bufferLength));
if (resultBluetooth->start_sec->imag && bufferImag)
memcpy(bufferImag, resultBluetooth->start_sec->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "stop_sec"))
{
if (resultBluetooth->stop_sec && resultBluetooth->stop_sec->length)
{
if (bufferLength > resultBluetooth->stop_sec->length)
bufferLength = resultBluetooth->stop_sec->length;
memcpy(bufferReal, resultBluetooth->stop_sec->real, (sizeof(double)*bufferLength));
if (resultBluetooth->stop_sec->imag && bufferImag)
memcpy(bufferImag, resultBluetooth->stop_sec->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "freq_est"))
{
if (resultBluetooth->freq_est && resultBluetooth->freq_est->length)
{
if (bufferLength > resultBluetooth->freq_est->length)
bufferLength = resultBluetooth->freq_est->length;
memcpy(bufferReal, resultBluetooth->freq_est->real, (sizeof(double)*bufferLength));
if (resultBluetooth->freq_est->imag && bufferImag)
memcpy(bufferImag, resultBluetooth->freq_est->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "freqEstPacketPointer"))
{
if (resultBluetooth->freqEstPacketPointer && resultBluetooth->freqEstPacketPointer->length)
{
if (bufferLength > resultBluetooth->freqEstPacketPointer->length)
bufferLength = resultBluetooth->freqEstPacketPointer->length;
memcpy(bufferReal, resultBluetooth->freqEstPacketPointer->real, (sizeof(double)*bufferLength));
if (resultBluetooth->freqEstPacketPointer->imag && bufferImag)
memcpy(bufferImag, resultBluetooth->freqEstPacketPointer->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "freq_drift"))
{
if (resultBluetooth->freq_drift && resultBluetooth->freq_drift->length)
{
if (bufferLength > resultBluetooth->freq_drift->length)
bufferLength = resultBluetooth->freq_drift->length;
memcpy(bufferReal, resultBluetooth->freq_drift->real, (sizeof(double)*bufferLength));
if (resultBluetooth->freq_drift->imag && bufferImag)
memcpy(bufferImag, resultBluetooth->freq_drift->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "freqDriftPacketPointer"))
{
if (resultBluetooth->freqDriftPacketPointer && resultBluetooth->freqDriftPacketPointer->length)
{
if (bufferLength > resultBluetooth->freqDriftPacketPointer->length)
bufferLength = resultBluetooth->freqDriftPacketPointer->length;
memcpy(bufferReal, resultBluetooth->freqDriftPacketPointer->real, (sizeof(double)*bufferLength));
if (resultBluetooth->freqDriftPacketPointer->imag && bufferImag)
memcpy(bufferImag, resultBluetooth->freqDriftPacketPointer->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "freqDeviationPointer"))
{
if (resultBluetooth->freqDeviationPointer && resultBluetooth->freqDeviationPointer->length)
{
if (bufferLength > resultBluetooth->freqDeviationPointer->length)
bufferLength = resultBluetooth->freqDeviationPointer->length;
memcpy(bufferReal, resultBluetooth->freqDeviationPointer->real, (sizeof(double)*bufferLength));
if (resultBluetooth->freqDeviationPointer->imag && bufferImag)
memcpy(bufferImag, resultBluetooth->freqDeviationPointer->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "EdrFreqvsTime"))
{
if (resultBluetooth->EdrFreqvsTime && resultBluetooth->EdrFreqvsTime->length)
{
if (bufferLength > resultBluetooth->EdrFreqvsTime->length)
bufferLength = resultBluetooth->EdrFreqvsTime->length;
memcpy(bufferReal, resultBluetooth->EdrFreqvsTime->real, (sizeof(double)*bufferLength));
if (resultBluetooth->EdrFreqvsTime->imag && bufferImag)
memcpy(bufferImag, resultBluetooth->EdrFreqvsTime->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "EdrExtremeOmegaI0"))
{
if (resultBluetooth->EdrExtremeOmegaI0 && resultBluetooth->EdrExtremeOmegaI0->length)
{
if (bufferLength > resultBluetooth->EdrExtremeOmegaI0->length)
bufferLength = resultBluetooth->EdrExtremeOmegaI0->length;
memcpy(bufferReal, resultBluetooth->EdrExtremeOmegaI0->real, (sizeof(double)*bufferLength));
if (resultBluetooth->EdrExtremeOmegaI0->imag && bufferImag)
memcpy(bufferImag, resultBluetooth->EdrExtremeOmegaI0->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
}
else if (dynamic_cast<iqapiResultPower *>(hndl->results))
{
resultPower = dynamic_cast<iqapiResultPower *>(hndl->results);
if (!strcmp(measurement, "start_sec"))
{
if (resultPower->start_sec && resultPower->start_sec->length)
{
if (bufferLength > resultPower->start_sec->length)
bufferLength = resultPower->start_sec->length;
memcpy(bufferReal, resultPower->start_sec->real, (sizeof(double)*bufferLength));
if (resultPower->start_sec->imag && bufferImag)
memcpy(bufferImag, resultPower->start_sec->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "stop_sec"))
{
if (resultPower->stop_sec && resultPower->stop_sec->length)
{
if (bufferLength > resultPower->stop_sec->length)
bufferLength = resultPower->stop_sec->length;
memcpy(bufferReal, resultPower->stop_sec->real, (sizeof(double)*bufferLength));
if (resultPower->stop_sec->imag && bufferImag)
memcpy(bufferImag, resultPower->stop_sec->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "P_av_each_burst_dBm"))
{
if (resultPower->P_av_each_burst_dBm && resultPower->P_av_each_burst_dBm->length)
{
if (bufferLength > resultPower->P_av_each_burst_dBm->length)
bufferLength = resultPower->P_av_each_burst_dBm->length;
memcpy(bufferReal, resultPower->P_av_each_burst_dBm->real, (sizeof(double)*bufferLength));
if (resultPower->P_av_each_burst_dBm->imag && bufferImag)
memcpy(bufferImag, resultPower->P_av_each_burst_dBm->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "P_pk_each_burst_dBm"))
{
if (resultPower->P_pk_each_burst_dBm && resultPower->P_pk_each_burst_dBm->length)
{
if (bufferLength > resultPower->P_pk_each_burst_dBm->length)
bufferLength = resultPower->P_pk_each_burst_dBm->length;
memcpy(bufferReal, resultPower->P_pk_each_burst_dBm->real, (sizeof(double)*bufferLength));
if (resultPower->P_pk_each_burst_dBm->imag && bufferImag)
memcpy(bufferImag, resultPower->P_av_each_burst_dBm->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
else if (!strcmp(measurement, "complete_burst"))
{
if (resultPower->complete_burst && resultPower->complete_burst->length)
{
if (bufferLength > resultPower->complete_burst->length)
bufferLength = resultPower->complete_burst->length;
memcpy(bufferReal, resultPower->complete_burst->real, (sizeof(double)*bufferLength));
if (resultPower->complete_burst->imag && bufferImag)
memcpy(bufferImag, resultPower->complete_burst->imag, (sizeof(double)*bufferLength));
return(bufferLength);
}
else
return 0;
}
}
#if !defined(IQAPI_1_5_X)
else if (dynamic_cast<iqapiResultHT40 *>(hndl->results))
{
resultHT40 = dynamic_cast<iqapiResultHT40 *>(hndl->results);
if (!strcmp(measurement, "x"))
{
if (resultHT40->ffts && resultHT40->len_of_ffts)
{
double *pReal = bufferReal;
double *pImag = bufferImag;
int len = bufferLength;
for(int i=0; i<resultHT40->len_of_ffts; i++)
{
if (len > resultHT40->ffts[i]->x->length)
{
//bufferLength = resultHT40->len_of_ffts * resultHT40->ffts[0]->length;
memcpy(pReal, resultHT40->ffts[i]->x->real, (sizeof(double) * resultHT40->ffts[i]->x->length));
pReal += resultHT40->ffts[i]->x->length;
len -= resultHT40->ffts[i]->x->length;
if (resultHT40->ffts[i]->x->imag && bufferImag)
{
memcpy(pImag, resultHT40->ffts[i]->x->imag, (sizeof(double) * resultHT40->ffts[i]->x->length));
pImag += resultHT40->ffts[i]->x->length;
}
}
else
{
// the buffer has been used up
memcpy(pReal, resultHT40->ffts[i]->x->real, (sizeof(double) * len));
if (resultHT40->ffts[i]->x->imag && bufferImag)
{
memcpy(pImag, resultHT40->ffts[i]->x->imag, (sizeof(double) * len));
}
break;
}
}
//TODO: Fix this
return(resultHT40->ffts[0]->x->length);
}
else
return 0;
}
else if (!strcmp(measurement, "y"))
{
if (resultHT40->ffts && resultHT40->len_of_ffts)
{
double *pReal = bufferReal;
double *pImag = bufferImag;
int len = bufferLength;
for(int i=0; i<resultHT40->len_of_ffts; i++)
{
if (len > resultHT40->ffts[i]->y->length)
{
//bufferLength = resultHT40->len_of_ffts * resultHT40->ffts[0]->length;
memcpy(pReal, resultHT40->ffts[i]->y->real, (sizeof(double) * resultHT40->ffts[i]->y->length));
pReal += resultHT40->ffts[i]->y->length;
len -= resultHT40->ffts[i]->y->length;
if (resultHT40->ffts[i]->y->imag && bufferImag)
{
memcpy(pImag, resultHT40->ffts[i]->y->imag, (sizeof(double) * resultHT40->ffts[i]->y->length));
pImag += resultHT40->ffts[i]->y->length;
}
}
else
{
// the buffer has been used up
memcpy(pReal, resultHT40->ffts[i]->y->real, (sizeof(double) * len));
if (resultHT40->ffts[i]->y->imag && bufferImag)
{
memcpy(pImag, resultHT40->ffts[i]->y->imag, (sizeof(double) * len));
}
break;
}
}
return(resultHT40->ffts[0]->y->length);
}
else
return 0;
}
//else if (!strcmp(measurement, "y"))
//{
// if (resultHT40->y && resultHT40->y->length)
// {
// if (bufferLength > resultHT40->y->length)
// bufferLength = resultHT40->y->length;
// memcpy(bufferReal, resultHT40->y->real, (sizeof(double)*bufferLength));
// if (resultHT40->y->imag && bufferImag)
// memcpy(bufferImag, resultHT40->y->imag, (sizeof(double)*bufferLength));
// return(bufferLength);
// }
// else
// return 0;
//}
}
#endif
else if (dynamic_cast<iqapiResultVHT80WideBand *>(hndl->results))
{
if (true == bIQxsFound || true == bIQxelFound)
{
resultVHT80Wideband = dynamic_cast<iqapiResultVHT80WideBand *>(hndl->results);
if (!strcmp(measurement, "x"))
{
if (resultVHT80Wideband->ffts && resultVHT80Wideband->len_of_ffts)
{
double *pReal = bufferReal;
double *pImag = bufferImag;
int len = bufferLength;
for(int i=0; i<resultVHT80Wideband->len_of_ffts; i++)
{
if (len > resultVHT80Wideband->ffts[i]->x->length)
{
//bufferLength = resultVHT80Wideband->len_of_ffts * resultVHT80Wideband->ffts[0]->length;
memcpy(pReal, resultVHT80Wideband->ffts[i]->x->real, (sizeof(double) * resultVHT80Wideband->ffts[i]->x->length));
pReal += resultVHT80Wideband->ffts[i]->x->length;
len -= resultVHT80Wideband->ffts[i]->x->length;
if (resultVHT80Wideband->ffts[i]->x->imag && bufferImag)
{
memcpy(pImag, resultVHT80Wideband->ffts[i]->x->imag, (sizeof(double) * resultVHT80Wideband->ffts[i]->x->length));
pImag += resultVHT80Wideband->ffts[i]->x->length;
}
}
else
{
// the buffer has been used up
memcpy(pReal, resultVHT80Wideband->ffts[i]->x->real, (sizeof(double) * len));
if (resultVHT80Wideband->ffts[i]->x->imag && bufferImag)
{
memcpy(pImag, resultVHT80Wideband->ffts[i]->x->imag, (sizeof(double) * len));
}
break;
}
}
//TODO: Fix this
return(resultVHT80Wideband->ffts[0]->x->length);
}
else
return 0;
}
else if (!strcmp(measurement, "y"))
{
if (resultVHT80Wideband->ffts && resultVHT80Wideband->len_of_ffts)
{
double *pReal = bufferReal;
double *pImag = bufferImag;
int len = bufferLength;
for(int i=0; i<resultVHT80Wideband->len_of_ffts; i++)
{
if (len > resultVHT80Wideband->ffts[i]->y->length)
{
//bufferLength = resultVHT80Wideband->len_of_ffts * resultVHT80Wideband->ffts[0]->length;
memcpy(pReal, resultVHT80Wideband->ffts[i]->y->real, (sizeof(double) * resultVHT80Wideband->ffts[i]->y->length));
pReal += resultVHT80Wideband->ffts[i]->y->length;
len -= resultVHT80Wideband->ffts[i]->y->length;
if (resultVHT80Wideband->ffts[i]->y->imag && bufferImag)
{
memcpy(pImag, resultVHT80Wideband->ffts[i]->y->imag, (sizeof(double) * resultVHT80Wideband->ffts[i]->y->length));
pImag += resultVHT80Wideband->ffts[i]->y->length;
}
}
else
{
// the buffer has been used up
memcpy(pReal, resultVHT80Wideband->ffts[i]->y->real, (sizeof(double) * len));
if (resultVHT80Wideband->ffts[i]->y->imag && bufferImag)
{
memcpy(pImag, resultVHT80Wideband->ffts[i]->y->imag, (sizeof(double) * len));
}
break;
}
}
return(resultVHT80Wideband->ffts[0]->y->length);
}
else
return 0;
}
}
else
return 0;
}
else
return 0;
}
}
return 0;
}
IQMEASURE_API int LP_GetVectorMeasurement(char *measurement, double bufferReal[], double bufferImag[], int bufferLength)
{
::TIMER_StartTimer(timerIQmeasure, "LP_GetVectorMeasurement", &timeStart);
int ret = LP_GetVectorMeasurement_NoTimer(measurement, bufferReal, bufferImag, bufferLength);
//// clear malloc and more, JK -1/15/12
//// Workaround: Jarir, 1/13/12, add following to return spectrum
//// between -40 to +40 MHz for regular HT20 to make compatible with IQ2010 //change from -33.0
//// We should return all of it (-60 to +60MHz), but spike appears
//// at +/- 50MHz with Daytona, which forced this workaround
//static int numTruncSamp = 0; // on each side
//static int numSampleUsed = 0; // return number of samples
//double freqLeftCutoff = -40.0e6; // truncation left-side cut-off frequency
//if(true == bIQxsFound || true == bIQxelFound) // 1. truncation only done for tester IQXS & DTNA so far
//{
// if (g_lastPerformedAnalysisType == ANALYSIS_FFT) // 2. truncation only for regular HT20 signal
// {
// if (!strcmp(measurement, "x")) // -----------------------
// {
// for (int k=0; k<ret; k++)
// {
// if (bufferReal[k] < freqLeftCutoff)
// numTruncSamp ++;
// else
// break;
// }
// numSampleUsed = ret-2*numTruncSamp;
// ret = numSampleUsed; // correct the return data length
// for(int j = 0; j< numSampleUsed; j++)
// {
// bufferReal[j]= bufferReal[j+numTruncSamp];
// bufferImag[j]= bufferImag[j+numTruncSamp];
// }
// }
// if (!strcmp(measurement, "y") && (numTruncSamp>0)) // ------------------
// {
// ret = numSampleUsed; // correct the return data length
// for(int j = 0; j< numSampleUsed; j++)
// {
// bufferReal[j]= bufferReal[j+numTruncSamp];
// bufferImag[j]= bufferImag[j+numTruncSamp];
// }
// numTruncSamp = 0; // clear
// numSampleUsed = 0;
// }
// }
//}
::TIMER_StopTimer(timerIQmeasure, "LP_GetVectorMeasurement", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_GetVectorMeasurement", timeDuration);
return ret;
}
void InstantiateAnalysisClasses()
{
//::TIMER_StartTimer(timerIQmeasure, "LP_SetAnalysisMode", &timeStart);
//if ( iqapiSetAnalysisMode("UNLOCK_KEY_1147014E-95E0-440d-A752-5F7C08A2FEE9") != IQAPI_ERR_OK )
//{
// throw hndl->lastErr;
//}
//::TIMER_StopTimer(timerIQmeasure, "LP_SetAnalysisMode", &timeDuration, &timeStop);
//printf("\nTime to unlock analysis in InstantiateAnalysisClasses() is %0.3f ms\n", timeDuration);
//temp, Z-99
//analysisWifiOfdm = new iqapiAnalysis11ac();'
analysisWifiOfdm = new iqapiAnalysisWifiOfdm();
analysisVHT80 = new iqapiAnalysisVHT80WideBand();
analysis80216 = new iqapiAnalysis80216();
analysisMimo = new iqapiAnalysisMimo();
analysisOfdm = new iqapiAnalysisOFDM();
analysis11b = new iqapiAnalysis11b();
analysisPowerRampOfdm = new iqapiAnalysisPowerRamp(true);
analysisPowerRamp11b = new iqapiAnalysisPowerRamp(false);
analysisCW = new iqapiAnalysisCW();
analysisSidelobe = new iqapiAnalysisSidelobe();
analysisWave = new iqapiAnalysisWave();
analysisCCDF = new iqapiAnalysisCCDF();
analysisFFT = new iqapiAnalysisFFT();
analysisPower = new iqapiAnalysisPower();
analysisBluetooth = new iqapiAnalysisBluetooth();
analysisZigbee = new iqapiAnalysisZigbee();
#if !defined(IQAPI_1_5_X)
analysisHT40 = new iqapiAnalysisHT40();
#endif
// FM
analysisFmRf = new iqapiAnalysisFmRf();
analysisFmAudioBase = new iqapiAnalysisFmAudioBase();
analysisFmDemodSpectrum = new iqapiAnalysisFmDemodSpectrum();
analysisFmMono = new iqapiAnalysisFmMono();
analysisFmStereo = new iqapiAnalysisFmStereo();
analysisFmAuto = new iqapiAnalysisFmAuto();
analysisRds = new iqapiAnalysisRds();
analysisRdsMono = new iqapiAnalysisRdsMono();
analysisRdsStereo = new iqapiAnalysisRdsStereo();
analysisRdsAuto = new iqapiAnalysisRdsAuto();
analysisAudioStereo = new iqapiAnalysisAudioStereo();
analysisAudioMono = new iqapiAnalysisAudioMono();
//if ( iqapiSetAnalysisMode("LOCK_KEY_431A4A5B-90A1-499c-B70F-11078C7C5954") != IQAPI_ERR_OK )
//{
// throw hndl->lastErr;
//}
return;
}
//void InitializeTesterSettings(void)
//{
// if( NULL!=hndl )
// {
// //Choose to use IQV_VSA_TYPE_1 (peak power mode)
// hndl->rx->powerMode = IQV_VSA_TYPE_1;
// for (int i=0;i<nTesters;i++)
// {
// hndl->tx->vsg[i]->source = IQV_SOURCE_WAVE; //this is needed to turn off the CW from VSG
// //Setting VSG to IQV_PORT_OFF caused MW not to configure VSGs, although hndl shows everything is corrrect.
// //TODO: the line below needs to be removed from the code
// //hndl->tx->vsg[i]->port = IQV_PORT_OFF;
//
// // Store settings for IQnxn
// g_IQnxnSettings[i].vsaAmplDBm = hndl->rx->vsa[i]->rfAmplDb;
// g_IQnxnSettings[i].vsaPort = hndl->rx->vsa[i]->port;
// g_IQnxnSettings[i].vsgPort = hndl->tx->vsg[i]->port;
// g_IQnxnSettings[i].vsgPowerDBm = hndl->tx->vsg[i]->rfGainDb;
// g_IQnxnSettings[i].vsgRFEnabled = hndl->tx->vsg[i]->enabled;
// }
// hndl->SetTxRx();
// }
// g_vsgMode = VSG_NO_MOD_FILE_LOADED;
// return;
//}
void InitializeTesterSettings(void)
{
if( NULL!=hndl )
{
//Choose to use IQV_VSA_TYPE_1 (peak power mode)
hndl->rx->powerMode = IQV_VSA_TYPE_1;
for (int i=0;i<nTesters;i++)
{
hndl->tx->vsg[i]->source = IQV_SOURCE_WAVE; //this is needed to turn off the CW from VSG
//Setting VSG to IQV_PORT_OFF caused MW not to configure VSGs, although hndl shows everything is corrrect.
//TODO: the line below needs to be removed from the code
//hndl->tx->vsg[i]->port = IQV_PORT_OFF;
// Store settings for IQnxn
g_IQnxnSettings[i].vsaAmplDBm = hndl->rx->vsa[i]->rfAmplDb;
g_IQnxnSettings[i].vsaPort = hndl->rx->vsa[i]->port;
g_IQnxnSettings[i].vsgPort = hndl->tx->vsg[i]->port;
g_IQnxnSettings[i].vsgPowerDBm = hndl->tx->vsg[i]->rfGainDb;
g_IQnxnSettings[i].vsgRFEnabled = hndl->tx->vsg[i]->enabled;
}
hndl->SetTxRx();
}
g_vsgMode = VSG_NO_MOD_FILE_LOADED;
return;
}
IQMEASURE_API int LP_DualHead_ConOpen(int tokenID, char *ipAddress1, char *ipAddress2, char *ipAddress3, char *ipAddress4)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_DualHead_ConOpen", &timeStart);
if (LibsInitialized)
{
err = hndl->ConOpen(ipAddress1, ipAddress2, ipAddress3, ipAddress4);
if(NULL!=ipAddress1 && NULL==ipAddress2 && NULL==ipAddress3 && NULL==ipAddress4)
{
nTesters = 1;
}
else if (NULL!=ipAddress1 && NULL!=ipAddress2 && NULL==ipAddress3 && NULL==ipAddress4)
{
nTesters = 2;
}
else if (NULL!=ipAddress1 && NULL!=ipAddress2 && NULL!=ipAddress3 && NULL==ipAddress4)
{
nTesters = 3;
}
else if (NULL!=ipAddress1 && NULL!=ipAddress2 && NULL!=ipAddress3 && NULL!=ipAddress4)
{
nTesters = 4;
}
else
{
err = -1;
}
if( ERR_OK==err )
{
if( !hndl->pDualHead->SetTokenID(IQV_TOKEN_NO_1, tokenID) )
{
// SetTokenID failed
err = ERR_SET_TOKEN_FAILED;
}
else
{
err = ERR_OK;
setDefaultCalled = false;
InstantiateAnalysisClasses();
//Choose to use IQV_VSA_TYPE_1 (peak power mode)
// We cannot change anything of the tester before TokenRetrieveTimeout()
//hndl->rx->powerMode = IQV_VSA_TYPE_1;
//nTesters = hndl->nTesters;
//err = hndl->SetTxRx();
g_vsgMode = VSG_NO_MOD_FILE_LOADED;
}
}
else
{
err = ERR_NO_CONNECTION;
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_DualHead_ConOpen", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_DualHead_ConOpen", timeDuration);
return err;
}
IQMEASURE_API int LP_DualHead_ObtainControl(unsigned int probeTimeMS, unsigned int timeOutMS)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_DualHead_ObtainControl", &timeStart);
if (LibsInitialized)
{
if( hndl->ConValid() )
{
// Wait for the Token
// TODO: add a total timeout
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[TokenRetrieveTimeout start]\n");
if( hndl->pDualHead->TokenRetrieveTimeout(IQV_TOKEN_NO_1, probeTimeMS, timeOutMS) )
{
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[TokenRetrieveTimeout done]\n");
if( !setDefaultCalled )
{
hndl->SetDefault();
setDefaultCalled = true;
nTesters = hndl->nTesters;
InstantiateAnalysisClasses();
InitializeTesterSettings();
if(NULL != hndl->hndlFm)
{
FmInitialized = true;
}
}
else
{
//hndl->GetStatus();
g_bDisableFreqFilter = true;
}
}
else
{
// TokenRetrieveTimeout timed out
//// If the total timeout is long enough to allow the other program to release, the timeout
//// is caused by abnormal termination, so that TokenRelease() wasn't called on the other side.
//printf("TokenReset...\n");
//hndl->pDualHead->TokenReset();
//printf("TokenReset done\n");
err = ERR_TOKEN_RETRIEVAL_TIMEDOUT;
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_DualHead_ObtainControl", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_DualHead_ObtainControl", timeDuration);
return err;
}
IQMEASURE_API int LP_DualHead_ReleaseControl()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_DualHead_ReleaseControl", &timeStart);
if (LibsInitialized)
{
if( hndl->pDualHead->TokenRelease(IQV_TOKEN_NO_1) )
{
// Token released
}
else
{
// Problem in releasing token
// TODO: how to handle this?
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_DualHead_ReleaseControl", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_DualHead_ReleaseControl", timeDuration);
return err;
}
IQMEASURE_API int LP_DualHead_ConClose(void)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_DualHead_ConClose", &timeStart);
if (LibsInitialized)
{
hndl->pDualHead->TokenRelease(IQV_TOKEN_NO_1);
int iqapiError = hndl->ConClose();
if (iqapiError)
{
err = ERR_GENERAL_ERR;
}
else
{
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_DualHead_ConClose", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_DualHead_ConClose", timeDuration);
return err;
}
IQMEASURE_API int LP_DualHead_GetTokenID(int *tokenID)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_DualHead_GetTokenID", &timeStart);
if (LibsInitialized)
{
*tokenID = hndl->pDualHead->TokenID[IQV_TOKEN_NO_1];
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_DualHead_GetTokenID", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_DualHead_GetTokenID", timeDuration);
return err;
}
IQMEASURE_API int LP_StartIQmeasureTimer()
{
int err = ERR_OK;
if(-1==timerIQmeasure)
{
TIMER_CreateTimer("IQMEASURE", &timerIQmeasure);
}
if(-1==loggerIQmeasure)
{
LOGGER_CreateLogger("IQMEASURE", &loggerIQmeasure);
}
return err;
}
IQMEASURE_API int LP_StopIQmeasureTimer()
{
int err = ERR_OK;
if(-1!=timerIQmeasure)
{
TIMER_ClearTimerHistory( timerIQmeasure );
}
return err;
}
IQMEASURE_API int LP_ReportTimerDurations()
{
int err = ERR_OK;
if(-1!=timerIQmeasure)
{
TIMER_ReportTimerDurations( timeStart, timeStop );
}
return err;
}
IQMEASURE_API int LP_SetLpcPath(char *litePointConnectionPath)
{
int err = ERR_OK;
/*
char *litePointConnectionPathReturn;
if (LibsInitialized)
{
if (bIQxelFound==true || bIQxsFound == true) // IQxel doesn't has this function anymore.
{
err = ERR_OK;
}else
{
hndl->SetLpcPath(litePointConnectionPath);
//Check "Set path" is work or not
litePointConnectionPathReturn = hndl->GetLpcPath();
if(strcmp(litePointConnectionPath, litePointConnectionPathReturn)== 0)
{
err = ERR_OK;
}
else
{
err = ERR_SET_PATH_NOT_DONE;
}
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
*/
return err;
}
//IQMEASURE_API int LP_IQ2010EXT_NewMultiSegmentWaveform(const char *multiSegmentWaveformFileName, const char *multiSegmentMarkerFileName)
IQMEASURE_API int LP_IQ2010EXT_NewMultiSegmentWaveform()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_NewMultiSegmentWaveform", &timeStart);
if (LibsInitialized)
{
// err = IQ2010EXT_NewMultiSegmentWaveform(); // TODO
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_NewMultiSegmentWaveform", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_NewMultiSegmentWaveform", timeDuration);
return err;
}
IQMEASURE_API int LP_IQ2010EXT_ClearAllWaveform(void)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_ClearAllWaveform", &timeStart);
if (LibsInitialized && bIQ201xFound)
{
// err = IQ2010EXT_ClearAllWaveform(); // TODO
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_ClearAllWaveform", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_ClearAllWaveform", timeDuration);
return err;
}
IQMEASURE_API int LP_IQ2010EXT_AddWaveform(const char *modFile, unsigned int *waveformIndex)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_AddWaveform", &timeStart);
if (LibsInitialized && bIQ201xFound)
{
err = IQ2010EXT_AddWaveform(modFile, waveformIndex); // TODO
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_AddWaveform", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_AddWaveform", timeDuration);
return err;
}
IQMEASURE_API int LP_IQ2010EXT_FinalizeMultiSegmentWaveform()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_FinalizeMultiSegmentWaveform", &timeStart);
if (LibsInitialized && bIQ201xFound)
{
err = IQ2010EXT_FinalizeMultiSegmentWaveform(); // TODO
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_FinalizeMultiSegmentWaveform", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_FinalizeMultiSegmentWaveform", timeDuration);
return err;
}
/*IQMEASURE_API int LP_IQ2010EXT_RxPer(int waveformIndex,
int freqMHz,
double powerLevelStart,
double powerLevelStop,
double step,
int packetCount,
int rfPort,
double ackPowerRmsdBm,
double ackTriggerLeveldBm
)*/
IQMEASURE_API int LP_IQ2010EXT_RxPer( int waveformIndex,
double freqMHz,
double powerLevelStartdBm,
double powerLevelStopdBm,
double stepdB,
int packetCount,
int rfPort,
double ackPowerRmsdBm,
double ackTriggerLeveldBm)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_RxPer", &timeStart);
if (LibsInitialized && bIQ201xFound)
{
// err = IQ2010EXT_RxPer( waveformIndex,
// freqMHz,
// powerLevelStart,
// powerLevelStop,
// step,
// packetCount,
// rfPort,
// ackPowerRmsdBm,
// ackTriggerLeveldBm
// ); // TODO
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_RxPer", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_RxPer", timeDuration);
return err;
}
IQMEASURE_API int LP_IQ2010EXT_GetRxPerResults_PB(double ackRespMax[],
double ackRespMin[],
double per[],
int arraySize
)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_GetRxPerResults_PB", &timeStart);
if (LibsInitialized && bIQ201xFound)
{
// err = IQ2010EXT_GetRxPerResults_PB( ackRespMax,
// ackRespMin,
// per,
// arraySize
// ); // TODO
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_GetRxPerResults_PB", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_GetRxPerResults_PB", timeDuration);
return err;
}
/*IQMEASURE_API int LP_IQ2010EXT_InitiateMultiCapture( double dataRate,
double freqMHz,
double peakPowerLeveldBm,
int captureLengthUs,
int skipPktCnt,
int captureCnt,
int rfPort,
double triggerLevelOffsetdB)*/
IQMEASURE_API int LP_IQ2010EXT_InitiateMultiCapture( char *dataRate,
double freqMHz,
double rmsPowerLeveldBm,
int captureLengthUs,
int skipPktCnt,
int captureCnt,
int rfPort,
double triggerLeveldBm)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_InitiateMultiCapture", &timeStart);
if (LibsInitialized && bIQ201xFound)
{
//err = IQ2010EXT_InitiateMultiCapture( dataRate,
// freqMHz,
// peakPowerLeveldBm,
// captureLengthUs,
// skipPktCnt,
// captureCnt,
// rfPort,
// triggerLevelOffsetdB); // TODO
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_InitiateMultiCapture", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_InitiateMultiCapture", timeDuration);
return err;
}
//IQMEASURE_API int LP_IQ2010EXT_FinishMultiCapture(void)
//{
// int err = ERR_OK;
//
// ::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_FinishMultiCapture", &timeStart);
//
// if (LibsInitialized && bIQ201xFound)
// {
// err = IQ2010EXT_FinishMultiCapture(); // TODO
// }
// else
// {
// err = ERR_NOT_INITIALIZED;
// }
//
// ::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_FinishMultiCapture", &timeDuration, &timeStop);
// ::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_FinishMultiCapture", timeDuration);
//
// return err;
//}
//
//IQMEASURE_API int LP_IQ2010EXT_Analyze80211ag( int ph_corr_mode,
// int ch_estimate,
// int sym_tim_corr,
// int freq_sync,
// int ampl_track)
//{
// int err = ERR_OK;
//
// ::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_Analyze80211ag", &timeStart);
//
// if (LibsInitialized && bIQ201xFound)
// {
// err = IQ2010EXT_Analyze80211ag( (IQV_PH_CORR_ENUM) ph_corr_mode,
// (IQV_CH_EST_ENUM) ch_estimate,
// (IQV_SYM_TIM_ENUM) sym_tim_corr,
// (IQV_FREQ_SYNC_ENUM) freq_sync,
// (IQV_AMPL_TRACK_ENUM) ampl_track); // TODO
// }
// else
// {
// err = ERR_NOT_INITIALIZED;
// }
//
// ::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_Analyze80211ag", &timeDuration, &timeStop);
// ::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_Analyze80211ag", timeDuration);
//
// return err;
//}
//
//IQMEASURE_API int LP_IQ2010EXT_Analyze80211n( char *type,
// char *mode,
// int enablePhaseCorr ,
// int enableSymTimingCorr ,
// int enableAmplitudeTracking ,
// int decodePSDU ,
// int enableFullPacketChannelEst ,
// char *referenceFile ,
// int packetFormat )
//{
// int err = ERR_OK;
//
// ::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_Analyze80211n", &timeStart);
//
// if (LibsInitialized && bIQ201xFound)
// {
//// err = IQ2010EXT_Analyze80211n( type,
//// mode,
//// enablePhaseCorr ,
//// enableSymTimingCorr ,
//// enableAmplitudeTracking ,
//// decodePSDU ,
//// enableFullPacketChannelEst ,
//// referenceFile ,
//// packetFormat
//// ); // TODO
// }
// else
// {
// err = ERR_NOT_INITIALIZED;
// }
//
// ::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_Analyze80211n", &timeDuration, &timeStop);
// ::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_Analyze80211n", timeDuration);
//
// return err;
//}
//
//IQMEASURE_API int LP_IQ2010EXT_Analyze80211b( int eq_taps ,
// int DCremove11b_flag ,
// int method_11b )
//{
// int err = ERR_OK;
//
// ::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_Analyze80211b", &timeStart);
//
// if (LibsInitialized && bIQ201xFound)
// {
// err = IQ2010EXT_Analyze80211b( (IQV_EQ_ENUM) eq_taps ,
// (IQV_DC_REMOVAL_ENUM) DCremove11b_flag ,
// (IQV_11B_METHOD_ENUM) method_11b
// ); // TODO
// }
// else
// {
// err = ERR_NOT_INITIALIZED;
// }
//
// ::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_Analyze80211b", &timeDuration, &timeStop);
// ::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_Analyze80211b", timeDuration);
//
// return err;
//}
//
//IQMEASURE_API int LP_IQ2010EXT_AnalyzePower(void)
//{
// int err = ERR_OK;
//
// ::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_AnalyzePower", &timeStart);
//
// if (LibsInitialized && bIQ201xFound)
// {
// err = IQ2010EXT_AnalyzePower(); // TODO
// }
// else
// {
// err = ERR_NOT_INITIALIZED;
// }
//
// ::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_AnalyzePower", &timeDuration, &timeStop);
// ::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_AnalyzePower", timeDuration);
//
// return err;
//}
//
//IQMEASURE_API int LP_IQ2010EXT_GetDoubleMeasurements( char *measurementName,
// double *average,
// double *minimum,
// double *maximum)
//{
// int err = ERR_OK;
//
// ::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_GetDoubleMeasurements", &timeStart);
//
// if (LibsInitialized && bIQ201xFound)
// {
// err = IQ2010EXT_GetDoubleMeasurements( measurementName,
// average,
// minimum,
// maximum
// ); // TODO
// }
// else
// {
// err = ERR_NOT_INITIALIZED;
// }
//
// ::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_GetDoubleMeasurements", &timeDuration, &timeStop);
// ::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_GetDoubleMeasurements", timeDuration);
//
// return err;
//}
//
//IQMEASURE_API int LP_IQ2010EXT_GetStringMeasurement( char *measurementName,
// char *result,
// int bufferSize,
// int indexResult)
//{
// int err = ERR_OK;
//
// ::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_GetStringMeasurement", &timeStart);
//
// if (LibsInitialized && bIQ201xFound)
// {
// err = IQ2010EXT_GetStringMeasurement( measurementName,
// result,
// bufferSize,
// indexResult
// ); // TODO
// }
// else
// {
// err = ERR_NOT_INITIALIZED;
// }
//
// ::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_GetStringMeasurement", &timeDuration, &timeStop);
// ::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_GetStringMeasurement", timeDuration);
//
// return err;
//}
//
//IQMEASURE_API int LP_IQ2010EXT_GetVectorMeasurement( char *measurementName,
// double bufferReal[],
// double bufferImag[],
// int bufferLength,
// int *dataSize,
// int indexResult)
//{
// int err = ERR_OK;
//
// ::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_GetVectorMeasurement", &timeStart);
//
// if (LibsInitialized && bIQ201xFound)
// {
//// err = IQ2010EXT_GetVectorMeasurement( measurementName,
//// bufferReal,
//// bufferImag,
//// bufferLength,
//// dataSize,
//// indexResult
//// ); // TODO
// }
// else
// {
// err = ERR_NOT_INITIALIZED;
// }
//
// ::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_GetVectorMeasurement", &timeDuration, &timeStop);
// ::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_GetVectorMeasurement", timeDuration);
//
// return err;
//}
//
//IQMEASURE_API int LP_IQ2010EXT_GetIntMeasurement( char *measurementName,
// int *result,
// int indexResult)
//{
// int err = ERR_OK;
//
// ::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_GetIntMeasurement", &timeStart);
//
// if (LibsInitialized && bIQ201xFound)
// {
// err = IQ2010EXT_GetIntMeasurement( measurementName,
// result,
// indexResult
// ); // TODO
// }
// else
// {
// err = ERR_NOT_INITIALIZED;
// }
//
// ::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_GetIntMeasurement", &timeDuration, &timeStop);
// ::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_GetIntMeasurement", timeDuration);
//
// return err;
//}
//
//IQMEASURE_API int LP_IQ2010EXT_LoadMultiSegmentWaveFile(const char *signalFile, const char *markerFile)
//{
// int err = ERR_OK;
//
// ::TIMER_StartTimer(timerIQmeasure, "LP_IQ2010EXT_LoadMultiSegmentWaveFile", &timeStart);
//
// if (LibsInitialized && bIQ201xFound)
// {
//// err = IQ2010EXT_LoadMultiSegmentWaveFile( signalFile, markerFile ); // TODO
// }
// else
// {
// err = ERR_NOT_INITIALIZED;
// }
//
// ::TIMER_StopTimer(timerIQmeasure, "LP_IQ2010EXT_LoadMultiSegmentWaveFile", &timeDuration, &timeStop);
// ::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_IQ2010EXT_LoadMultiSegmentWaveFile", timeDuration);
//
// return err;
//}
//FM IQMeasure functions
#ifdef WIN32 //Not using for Mac at this time
IQMEASURE_API int LP_FM_SetVsg(unsigned int carrierFreqHz,
double carrierPowerdBm,
int modulationEnable,
unsigned int totalFmDeviationHz,
int stereoEnable,
unsigned int pilotDeviationHz,
int rdsEnable,
unsigned int rdsDeviationHz,
unsigned int preEmphasisUs,
char* rdsTransmitString)
{
int err = ERR_OK;
int carrierOffsetHz = 0;
int rdsPhaseShift = 0;
IQV_FM_VSG_PREEMPHASIS_MODES preEmphasisModeSetting;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_SetVsg", &timeStart);
if(FmInitialized)
{
try
{
err = hndl->hndlFm->Activate(IQV_FM_VSG_TECH_ACT);
if(ERR_OK != err) { throw err;}
hndl->hndlFm->SetParamFrequency(carrierFreqHz);
hndl->hndlFm->SetParamPowerDbm(carrierPowerdBm);
hndl->hndlFm->SetParamFrequencyOffset(carrierOffsetHz);
if(PRE_EMPHASIS_75US == preEmphasisUs)
{
preEmphasisModeSetting = IQV_FM_VSG_PREEMPHASIS_75_MICRO_SEC;
}
else if(PRE_EMPHASIS_50US == preEmphasisUs)
{
preEmphasisModeSetting = IQV_FM_VSG_PREEMPHASIS_50_MICRO_SEC;
}
else if(PRE_EMPHASIS_25US == preEmphasisUs)
{
preEmphasisModeSetting = IQV_FM_VSG_PREEMPHASIS_25_MICRO_SEC;
}
else
{
preEmphasisModeSetting = IQV_FM_VSG_PREEMPHASIS_NO_PREEMPHASIS;
}
hndl->hndlFm->SetParamPreemphasisMode(preEmphasisModeSetting);
hndl->hndlFm->SetParamFrequencyDeviation(totalFmDeviationHz); // this is the total deviation
// totalFmDeviationHz = Audio deviation + pilot deviation ( if stereo enabled) + RDS deviation ( if RDS enabled)
// so must be carefully specified
/* For example:
Case 1:
MONO MODE, RDS DISABLED ( pilotDeviationHz, rdsDeviationHz values are ignored in this case)
totalFmDeviationHz = 75000 Hz.
then audio deviation = 75000 Hz.
Case 2:
STEREO MODE, RDS DISABLED ( pilotDeviationHz = 7500, rdsDeviationHz value is ignored)
totalFmDeviationHz = 75000 Hz.
Audio Deviation = totalFmDeviationHz - pilotDeviationHz( since stereo is enabled) = 67500 Hz.
Case 3:
STEREO MODE, RDS ENABLED ( pilotDeviationHz = 7500, rdsDeviationHz = 2000)
totalFmDeviationHz = 75000 Hz.
Audio Deviation = totalFmDeviationHz - pilotDeviationHz - rdsDeviationHz = 65500 Hz */
if(IQV_FM_VSG_MODULATION_STATE_ON == modulationEnable)
{
hndl->hndlFm->SetParamModulationState(IQV_FM_VSG_MODULATION_STATE_ON);
}
else
{
hndl->hndlFm->SetParamModulationState(IQV_FM_VSG_MODULATION_STATE_OFF);
}
if(FM_STEREO == stereoEnable)
{
hndl->hndlFm->SetParamStereo(IQV_FM_VSG_STEREO_MODE_ON);
pilotDeviationHz = pilotDeviationHz / 100;
pilotDeviationHz = pilotDeviationHz * 100;
hndl->hndlFm->SetParamPilotDeviation(pilotDeviationHz);
}
else
{
hndl->hndlFm->SetParamStereo(IQV_FM_VSG_STEREO_MODE_OFF);
hndl->hndlFm->SetParamPilotDeviation(0);
}
if(IQV_FM_VSG_RDS_MODE_ON == rdsEnable)
{
hndl->hndlFm->SetParamRdsMode(IQV_FM_VSG_RDS_MODE_ON);
hndl->hndlFm->SetParamRdsDeviation(rdsDeviationHz);
if(NULL != rdsTransmitString)
{
hndl->hndlFm->LoadRdsData(rdsTransmitString);
}
else
{
rdsTransmitString = "LitepointFM";
hndl->hndlFm->LoadRdsData(rdsTransmitString);
}
if(IQV_FM_VSG_RDS_PHASE_SHIFT_90 == rdsPhaseShift)
{
hndl->hndlFm->SetParamRdsPhaseShift(IQV_FM_VSG_RDS_PHASE_SHIFT_90);
}
else
{
hndl->hndlFm->SetParamRdsPhaseShift(IQV_FM_VSG_RDS_PHASE_SHIFT_NONE);
}
}
else
{
hndl->hndlFm->SetParamRdsMode(IQV_FM_VSG_RDS_MODE_OFF);
hndl->hndlFm->SetParamRdsDeviation(0);
}
}
catch (int /*vsgSetupErr*/)
{
err = ERR_FM_SET_TX_FAILED;
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_SetVsg", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_SetVsg", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_GetVsgSettings(unsigned int *carrierFreqHz,
double *carrierPowerdBm,
int *modulationEnabled,
unsigned int *totalFmDeviationHz,
int *stereoEnabled,
unsigned int *pilotDeviationHz,
int *rdsEnabled,
unsigned int *rdsDeviationHz,
unsigned int *preEmphasisMode)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_GetVsgSettings", &timeStart);
if(FmInitialized)
{
try
{
err = hndl->hndlFm->GetTx();
if(ERR_OK != err) throw err;
hndl->hndlFm->GetParamFrequency(carrierFreqHz);
hndl->hndlFm->GetParamPowerDbm(carrierPowerdBm);
hndl->hndlFm->GetParamModulationState((IQV_FM_VSG_MODULATION_STATE *)modulationEnabled);
hndl->hndlFm->GetParamFrequencyDeviation(totalFmDeviationHz);
hndl->hndlFm->GetParamStereo((IQV_FM_VSG_STEREO_MODES *)stereoEnabled);
hndl->hndlFm->GetParamPilotDeviation(pilotDeviationHz);
hndl->hndlFm->GetParamRdsMode((IQV_FM_VSG_RDS_MODES *)rdsEnabled);
hndl->hndlFm->GetParamRdsDeviation(rdsDeviationHz);
hndl->hndlFm->GetParamPreemphasisMode((IQV_FM_VSG_PREEMPHASIS_MODES *)preEmphasisMode);
}
catch (int /*vsgGetSettingsErr*/)
{
err = ERR_FM_GET_RX_FAILED;
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_GetVsgSettings", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_GetVsgSettings", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_SetFrequency(unsigned int carrierFreqHz, double carrierPowerdBm = -(DBL_MAX))
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_SetFrequency", &timeStart);
if(FmInitialized)
{
try
{
hndl->hndlFm->SetParamFrequency(carrierFreqHz);
if(carrierPowerdBm != -(DBL_MAX))
hndl->hndlFm->SetParamPowerDbm(carrierPowerdBm);
err = hndl->hndlFm->SetTx();
if(ERR_OK != err) throw err;
}
catch (int /*vsgSetupErr*/)
{
err = ERR_FM_SET_TX_FAILED;
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_SetFrequency", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_SetFrequency", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_SetCarrierPower(double carrierPowerdBm)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_SetCarrierPower", &timeStart);
if(FmInitialized)
{
try
{
hndl->hndlFm->SetParamPowerDbm(carrierPowerdBm);
err = hndl->hndlFm->SetTx();
if(ERR_OK != err) throw err;
}
catch (int /*vsgSetupErr*/)
{
err = ERR_FM_SET_TX_FAILED;
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_SetCarrierPower", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_SetCarrierPower", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_SetAudioSingleTone(double audioToneFreqHz,
int leftRightChannelSelect,
double audioToneAmpPercent,
int stereo)
{
int err = ERR_OK;
int TONE_INDEX_1 = 1;
int TONE_INDEX_5 = 5;
double audioToneAmpdB = (20*log10((audioToneAmpPercent/100)));
::TIMER_StartTimer(timerIQmeasure, "LP_FM_SetAudioSingleTone", &timeStart);
hndl->hndlFm->RemoveParamAllAudioTone();
if(FmInitialized)
{
try
{
if(FM_STEREO == stereo)
{
if(LEFT_ONLY == leftRightChannelSelect)
{
err = hndl->hndlFm->SetParamAudioTone((IQV_FM_VSG_AUDIO_TONE_INDEX)TONE_INDEX_1, audioToneFreqHz,
(IQV_FM_VSG_AUDIO_CHANNELS)LEFT_ONLY, audioToneAmpdB);
if(ERR_OK != err) throw err;
}
else if(RIGHT_ONLY == leftRightChannelSelect)
{
err = hndl->hndlFm->SetParamAudioTone((IQV_FM_VSG_AUDIO_TONE_INDEX)TONE_INDEX_5, audioToneFreqHz,
(IQV_FM_VSG_AUDIO_CHANNELS)RIGHT_ONLY, audioToneAmpdB);
if(ERR_OK != err) throw err;
}
else if(LEFT_RIGHT == leftRightChannelSelect)
{
err = hndl->hndlFm->SetParamAudioTone((IQV_FM_VSG_AUDIO_TONE_INDEX)TONE_INDEX_1, audioToneFreqHz,
(IQV_FM_VSG_AUDIO_CHANNELS)LEFT_ONLY, audioToneAmpdB);
if(ERR_OK != err) throw err;
err = hndl->hndlFm->SetParamAudioTone((IQV_FM_VSG_AUDIO_TONE_INDEX)TONE_INDEX_5, audioToneFreqHz + 1000,
(IQV_FM_VSG_AUDIO_CHANNELS)RIGHT_ONLY, audioToneAmpdB);
if(ERR_OK != err) throw err;
}
else if(LEFT_EQUALS_RIGHT == leftRightChannelSelect)
{
err = hndl->hndlFm->SetParamAudioTone((IQV_FM_VSG_AUDIO_TONE_INDEX)TONE_INDEX_1, audioToneFreqHz,
(IQV_FM_VSG_AUDIO_CHANNELS)LEFT_EQUALS_RIGHT, audioToneAmpdB);
if(ERR_OK != err) throw err;
}
else if(LEFT_EQUALS_MINUS_RIGHT == leftRightChannelSelect)
{
err = hndl->hndlFm->SetParamAudioTone((IQV_FM_VSG_AUDIO_TONE_INDEX)TONE_INDEX_1, audioToneFreqHz,
(IQV_FM_VSG_AUDIO_CHANNELS)LEFT_EQUALS_MINUS_RIGHT, audioToneAmpdB);
if(ERR_OK != err) throw err;
}
}
else if(FM_MONO == stereo)
{
err = hndl->hndlFm->SetParamAudioTone((IQV_FM_VSG_AUDIO_TONE_INDEX)TONE_INDEX_1, audioToneFreqHz,
(IQV_FM_VSG_AUDIO_CHANNELS)LEFT_ONLY, audioToneAmpdB);
if(ERR_OK != err) throw err;
}
/*err = hndl->hndlFm->SetTx();
if(ERR_OK != err) throw err;*/
}
catch (int /*singleToneAudioSetupErr*/)
{
err = ERR_FM_SET_AUDIO_TONE_FAILED;
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_SetAudioSingleTone", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_SetAudioSingleTone", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_SetAudioToneArray(double* freqHz,
int* channelSelect,
double* amplitudePercent,
int stereo,
unsigned int toneCount)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_SetAudioToneArray", &timeStart);
hndl->hndlFm->RemoveParamAllAudioTone();
if(FmInitialized)
{
if(0 == toneCount)
{
err = ERR_FM_SET_AUDIO_TONE_FAILED; // atleast 1 tone needs to be specified to be setup
}
else if( 12 < toneCount)
{
err = ERR_FM_SET_AUDIO_TONE_FAILED; // cannot set more than 12 tones in VSG
}
else
{
try
{
for (unsigned int i = 0; i < toneCount; i++)
{
if(FM_STEREO == stereo)
{
if(0 == channelSelect[i] || 1 == channelSelect[i])
{
err = hndl->hndlFm->SetParamAudioTone((IQV_FM_VSG_AUDIO_TONE_INDEX)i, freqHz[i],
(IQV_FM_VSG_AUDIO_CHANNELS)channelSelect[i], (20*log10(amplitudePercent[i]/100)));
if(ERR_OK != err) throw err;
}
else // channelSelect cannot be LEFT_RIGHT/LEFT_EQUALS_RIGHT/LEFT_EQUALS_MINUS_RIGHT for multitone audio setup. each tone's channel information must be set individually.
{
err = ERR_FM_SET_AUDIO_TONE_FAILED;
}
}
else
{
err = hndl->hndlFm->SetParamAudioTone((IQV_FM_VSG_AUDIO_TONE_INDEX)i, freqHz[i],
(IQV_FM_VSG_AUDIO_CHANNELS)LEFT_ONLY, (20*log10(amplitudePercent[i]/100)));
if(ERR_OK != err) throw err;
}
}
err = hndl->hndlFm->SetTx();
if(ERR_OK != err) throw err;
}
catch (int /*multiToneAudioSetupErr*/)
{
err = ERR_FM_GET_AUDIO_TONE_FAILED;
}
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_SetAudioToneArray", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_SetAudioToneArray", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_SetAudioToneArrayDeviation(double* freqHz,
int* channelSelect,
double* amplitudeDeviationHz,
int stereo,
unsigned int toneCount)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_SetAudioToneArrayDeviation", &timeStart);
hndl->hndlFm->RemoveParamAllAudioTone();
if(FmInitialized)
{
// change audio setup to deviation mode
hndl->hndlFm->SetParamAudioToneMode(IQV_FM_AUDIO_TONE_DEVIATION);
if(0 == toneCount)
{
err = ERR_FM_SET_AUDIO_TONE_FAILED; // atleast 1 tone needs to be specified to be setup
}
else if( 12 < toneCount)
{
err = ERR_FM_SET_AUDIO_TONE_FAILED; // cannot set more than 12 tones in VSG
}
else
{
for (unsigned int i = 0; i < toneCount; i++)
{
try
{
if(FM_STEREO == stereo)
{
if(0 == channelSelect[i] || 1 == channelSelect[i] || 3 == channelSelect[i] || 4 == channelSelect[i] )
{
err = hndl->hndlFm->SetParamAudioToneWDeviation((IQV_FM_VSG_AUDIO_TONE_INDEX)i, freqHz[i],
(IQV_FM_VSG_AUDIO_CHANNELS)channelSelect[i], amplitudeDeviationHz[i]);
if(ERR_OK != err) throw err;
}
else // channelSelect cannot be LEFT_RIGHT for multitone audio setup in deviation mode
{
err = ERR_FM_SET_AUDIO_TONE_FAILED;
}
}
else
{
err = hndl->hndlFm->SetParamAudioToneWDeviation((IQV_FM_VSG_AUDIO_TONE_INDEX)i, freqHz[i],
(IQV_FM_VSG_AUDIO_CHANNELS)LEFT_ONLY, (amplitudeDeviationHz[i]));
if(ERR_OK != err) throw err;
}
err = hndl->hndlFm->SetTx();
if(ERR_OK != err) throw err;
}
catch (int /*multiToneAudioSetupErr*/)
{
err = ERR_FM_GET_AUDIO_TONE_FAILED;
}
}
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_SetAudioToneArrayDeviation", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_SetAudioToneArrayDeviation", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_GetAudioToneArray(double *freqHz,
int *channelSelect,
double *amplitudePercent,
unsigned int toneCount)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_GetAudioToneArray", &timeStart);
if(FmInitialized)
{
try
{
err = hndl->hndlFm->GetTx();
if(ERR_OK != err) throw err;
double* audioFreqHz = new double;
IQV_FM_VSG_AUDIO_CHANNELS* channel = new IQV_FM_VSG_AUDIO_CHANNELS;
double* audioAmplitudedB = new double;
for (unsigned int toneIndex = 0; toneIndex < toneCount; toneIndex++)
{
err = hndl->hndlFm->GetParamAudioTone((IQV_FM_VSG_AUDIO_TONE_INDEX)toneIndex, audioFreqHz, channel, audioAmplitudedB);
if(ERR_OK != err) throw err;
freqHz[toneIndex] = *audioFreqHz;
channelSelect[toneIndex] = *channel;
amplitudePercent[toneIndex] = (pow(10,(*audioAmplitudedB/20))*100);
}
delete audioFreqHz;
delete channel;
delete audioAmplitudedB;
}
catch (int /*getAudioSetupErr*/)
{
err = ERR_FM_GET_AUDIO_TONE_FAILED;
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_GetAudioToneArray", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_GetAudioToneArray", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_SetAudioToneModeAmplitude(void)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_SetAudioToneModeAmplitude", &timeStart);
if(FmInitialized)
{
hndl->hndlFm->SetParamAudioToneMode(IQV_FM_AUDIO_TONE_AMPLITUDE);
if(hndl->hndlFm->SetTx())
{
err = ERR_FM_SET_TX_FAILED;
}
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_SetAudioToneModeAmplitude", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_SetAudioToneModeAmplitude", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_DeleteAudioTones()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_DeleteAudioTones", &timeStart);
if(FmInitialized)
{
hndl->hndlFm->RemoveParamAllAudioTone();
/*err = hndl->hndlFm->SetTx();
if(err)
{
err = ERR_FM_SET_TX_FAILED;
}*/
}
else
{
err = ERR_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_DeleteAudioTones", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_DeleteAudioTones", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_StartVsg()
{
int err = ERR_OK;
int vsgSettleTimems = 150;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_StartVsg", &timeStart);
if(FmInitialized)
{
hndl->hndlFm->SetParamRfOutput(IQV_FM_VSG_RF_OUTPUT_ON);
if(hndl->hndlFm->SetTx())
{
err = ERR_FM_SET_TX_FAILED;
}
Sleep(vsgSettleTimems);
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_StartVsg", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_StartVsg", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_StopVsg()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_StopVsg", &timeStart);
if(FmInitialized)
{
try
{
hndl->hndlFm->SetParamRfOutput(IQV_FM_VSG_RF_OUTPUT_OFF);
err = hndl->hndlFm->SetTx();
if(ERR_OK != err) throw err;
err = hndl->hndlFm->Deactivate(IQV_FM_VSG_TECH_ACT);
if(ERR_OK != err) throw err;
}
catch(int /*stopVsgErr*/)
{
err = ERR_FM_SET_TX_FAILED;
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_StopVsg", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_StopVsg", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_SetVsgDistortion(int amDistortionEnable,
unsigned int amFrequencyHz,
unsigned int amDepthPercent)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_SetVsgDistortion", &timeStart);
if(FmInitialized)
{
if(IQV_FM_VSG_DISTORTION_AM == amDistortionEnable)
{
hndl->hndlFm->SetParamDistortion(IQV_FM_VSG_DISTORTION_AM, amFrequencyHz, amDepthPercent);
}
else
{
hndl->hndlFm->SetParamDistortion(IQV_FM_VSG_DISTORTION_OFF, 0, 0);
}
if(hndl->hndlFm->SetTx())
{
err = ERR_FM_SET_TX_FAILED;
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_SetVsgDistortion", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_SetVsgDistortion", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_GetVsgDistortion(double *amDistortionEnableStatus,
unsigned int *amFrequencyHz,
unsigned int *amDepthPercent)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_GetVsgDistortion", &timeStart);
if(FmInitialized)
{
if(hndl->hndlFm->GetTx())
{
err = ERR_FM_GET_RX_FAILED;
}
IQV_FM_VSG_DISTORTION_TYPES *amDistortionEnableStatus = new IQV_FM_VSG_DISTORTION_TYPES;
hndl->hndlFm->GetParamDistortion(amDistortionEnableStatus, amFrequencyHz, amDepthPercent);
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_GetVsgDistortion", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_GetVsgDistortion", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_StartVsgInterference(double interfererRelativePowerdBm,
int interfererCarrierOffsetHz,
int interfererPeakFreqDeviationHz,
int interfererModulationEnable,
unsigned int interfererAudioFreqHz)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_StartVsgInterference", &timeStart);
if(FmInitialized)
{
if (IQV_FM_VSG_MODULATION_FM == interfererModulationEnable)
{
hndl->hndlFm->SetParamInterferer(IQV_FM_VSG_INTERFERING_CARRIER_OFF,interfererCarrierOffsetHz,interfererRelativePowerdBm,
interfererPeakFreqDeviationHz);
if(hndl->hndlFm->SetTx())
{
err = ERR_FM_SET_TX_FAILED;
}
hndl->hndlFm->SetParamInterfererModulation(IQV_FM_VSG_MODULATION_FM, interfererAudioFreqHz);
hndl->hndlFm->SetParamInterferer(IQV_FM_VSG_INTERFERING_CARRIER_ON,interfererCarrierOffsetHz,interfererRelativePowerdBm,
interfererPeakFreqDeviationHz);
}
else
{
hndl->hndlFm->SetParamInterfererModulation(IQV_FM_VSG_MODULATION_FM, 0);
hndl->hndlFm->SetParamInterferer(IQV_FM_VSG_INTERFERING_CARRIER_ON,interfererCarrierOffsetHz,interfererRelativePowerdBm,
0);
}
if(hndl->hndlFm->SetTx())
{
err = ERR_FM_SET_TX_FAILED;
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_StartVsgInterference", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_StartVsgInterference", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_GetVsgInterferenceSettings(double *interfererRelativePowerdBm,
int *interfererCarrierOffsetHz,
int *interfererPeakFreqDeviationHz,
int *interfererModulationEnabled,
unsigned int *interfererAudioFreqHz)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_GetVsgInterferenceSettings", &timeStart);
if(FmInitialized)
{
if(hndl->hndlFm->GetTx())
{
err = ERR_FM_GET_RX_FAILED;
}
IQV_FM_VSG_INTERFERING_CARRIER_MODES *interfererMode = new IQV_FM_VSG_INTERFERING_CARRIER_MODES;
hndl->hndlFm->GetParamInterferer(interfererMode, interfererCarrierOffsetHz, interfererRelativePowerdBm, interfererPeakFreqDeviationHz);
hndl->hndlFm->GetParamInterfererModulation((IQV_FM_VSG_MODULATION_TYPES *)interfererModulationEnabled, interfererAudioFreqHz);
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_GetVsgInterferenceSettings", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_GetVsgInterferenceSettings", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_StopVsgInterference()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_StopVsgInterference", &timeStart);
if(FmInitialized)
{
hndl->hndlFm->SetParamInterferer(IQV_FM_VSG_INTERFERING_CARRIER_OFF,0,0,0);
if(hndl->hndlFm->SetTx())
{
err = ERR_FM_SET_TX_FAILED;
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_StopVsgInterference", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_StopVsgInterference", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_SetVsa(unsigned int carrierFreqHz, double expectedPeakInputPowerdBm)
{
int err = ERR_OK;
double marginalInputPowerdBm = 1;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_SetVsa", &timeStart);
if(FmInitialized)
{
int agcMode = OFF;
int vsaSampleRate = SAMPLE_640KHz;
double expectedPeakInputPowerdBmSetting;
try
{
err = hndl->hndlFm->Activate(IQV_FM_VSA_TECH_ACT);
if (ERR_OK != err) throw err;
hndl->hndlFm->SetParamVsaAgcMode((IQV_FM_VSA_AGC_MODES)agcMode);
hndl->hndlFm->SetParamVsaSampleRate((IQV_FM_VSA_SAMPLE_RATES)vsaSampleRate);
hndl->hndlFm->SetParamVsaFrequency(carrierFreqHz);
if(expectedPeakInputPowerdBm >= 10)
{
expectedPeakInputPowerdBmSetting = 10;
}
else if(expectedPeakInputPowerdBm <= -40)
{
expectedPeakInputPowerdBmSetting = -40;
}
else
{
expectedPeakInputPowerdBmSetting = (expectedPeakInputPowerdBm + marginalInputPowerdBm);
}
hndl->hndlFm->SetParamVsaPowerDbm(expectedPeakInputPowerdBmSetting);
hndl->hndlFm->SetParamVsaRfInput(IQV_FM_VSA_RF_INPUT_ON);
err = hndl->hndlFm->SetRx();
if (ERR_OK != err) throw err;
}
catch (int /*vsaSetupErr*/)
{
err = ERR_FM_SET_RX_FAILED;
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_SetVsa", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_SetVsa", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_GetVsaSettings(unsigned int *carrierFreqHz, double *expectedPeakInputPowerdBm)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_GetVsaSettings", &timeStart);
if(FmInitialized)
{
if(hndl->hndlFm->GetRx())
{
err = ERR_FM_GET_RX_FAILED;
}
hndl->hndlFm->GetParamVsaFrequency(carrierFreqHz);
hndl->hndlFm->GetParamVsaPowerDbm(expectedPeakInputPowerdBm);
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_GetVsaSettings", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_GetVsaSettings", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_VsaDataCapture(double captureTimemillisec)
{
int err = ERR_OK;
unsigned int captureTime = captureTimemillisec > 0 ? (int)captureTimemillisec : 0;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_VsaDataCapture", &timeStart);
if(FmInitialized)
{
//Clear previous results stored
g_FmRfScalarResults.clear();
g_FmMonoScalarResults.clear();
g_FmStereoScalarResults.clear();
g_FmRfVectorResults.clear();
g_FmMonoVectorResults.clear();
g_FmStereoVectorResults.clear();
if(hndl->hndlFm->Capture(captureTime))
{
err = ERR_FM_VSA_CAPTURE_FAILED;
}
// reset the audioCaptureOnly flag to indicate that this is a VSACapture
g_audioCaptureOnly = false;
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_VsaDataCapture", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_VsaDataCapture", timeDuration);
return err;
}
// Analyze functions
IQMEASURE_API int LP_FM_Analyze_RF(int rfRBWHz, int rfOBWPercent, int rfPowerMeasBWHz, int windowType)
{
int err = ERR_OK;
//Clear previous results stored
g_FmRfScalarResults.clear();
g_FmRfVectorResults.clear();
::TIMER_StartTimer(timerIQmeasure, "LP_FM_Analyze_RF", &timeStart);
if (FmInitialized)
{
if (!hndl->hndlFm->dataFm)
{
err = ERR_FM_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->hndlFm->dataFm->length) //crezon revision
{
err = ERR_FM_NO_CAPTURE_DATA;
return err;
}
}
analysisFmRf->saResBw = rfRBWHz;
analysisFmRf->rfPowerMeasurementBw = rfPowerMeasBWHz;
analysisFmRf->percentObw = rfOBWPercent;
analysisFmRf->windowType = (IQV_FM_WINDOW_TYPE)windowType;
hndl->hndlFm->analysis = dynamic_cast<iqapiAnalysisFmRf *>(analysisFmRf);
if (LP_Analyze_FM_Hndl())
{
err = ERR_FM_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_Analyze_RF", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_Analyze_RF", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_Analyze_Demod(int audioRBWHz)
{
int err = ERR_OK;
//Clear previous results stored
g_FmRfScalarResults.clear();
g_FmRfVectorResults.clear();
::TIMER_StartTimer(timerIQmeasure, "LP_FM_Analyze_Demod", &timeStart);
if (FmInitialized)
{
if (!hndl->hndlFm->dataFm)
{
err = ERR_FM_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->hndlFm->dataFm->length) //crezon revision
{
err = ERR_FM_NO_CAPTURE_DATA;
return err;
}
}
analysisFmDemodSpectrum->saResBw = audioRBWHz;
hndl->hndlFm->analysis = dynamic_cast<iqapiAnalysisFmDemodSpectrum *>(analysisFmDemodSpectrum);
if (LP_Analyze_FM_Hndl())
{
err = ERR_FM_ANALYSIS_FAILED;
}
else
{
}
}
else
err = ERR_FM_NOT_INITIALIZED;
::TIMER_StopTimer(timerIQmeasure, "LP_FM_Analyze_Demod", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_Analyze_Demod", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_Analyze_Audio_Mono(int audioRBWHz,
int audioFreqLowLimitHz,
int audioFreqHiLimitHz,
int filterCount,
int filterType1,
double filterParam1,
int filterType2,
double filterParam2,
int filterType3,
double filterParam3)
{
int err = ERR_OK;
//Clear previous results stored
g_FmMonoScalarResults.clear();
g_FmMonoVectorResults.clear();
IQV_FM_FILTER_TYPE filter1 =(IQV_FM_FILTER_TYPE)filterType1;
double filterPar1 = filterParam1;
IQV_FM_FILTER_TYPE filter2 =(IQV_FM_FILTER_TYPE)filterType2;
double filterPar2 = filterParam2;
IQV_FM_FILTER_TYPE filter3 =(IQV_FM_FILTER_TYPE)filterType3;
double filterPar3 = filterParam3;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_Analyze_Audio_Mono", &timeStart);
if (FmInitialized)
{
if (!hndl->hndlFm->dataFm)
{
err = ERR_FM_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->hndlFm->dataFm->length) //crezon revision
{
err = ERR_FM_NO_CAPTURE_DATA;
return err;
}
}
if(g_audioCaptureOnly)
{
analysisAudioMono->saNFilters = filterCount;
analysisAudioMono->saResBw = audioRBWHz;
analysisAudioMono->saFilterType1 = filter1;
analysisAudioMono->saFilterParam1 = filterPar1;
analysisAudioMono->saFilterType2 = filter2;
analysisAudioMono->saFilterParam2 = filterPar2;
analysisAudioMono->saFilterType3 = filter3;
analysisAudioMono->saFilterParam3 = filterPar3;
analysisAudioMono->audFreqL = audioFreqLowLimitHz;
analysisAudioMono->audFreqH = audioFreqHiLimitHz;
hndl->hndlFm->analysis = dynamic_cast<iqapiAnalysisAudioMono *>(analysisAudioMono);
}
else
{
analysisFmMono->saNFilters = filterCount;
analysisFmMono->saResBw = audioRBWHz;
analysisFmMono->saFilterType1 = filter1;
analysisFmMono->saFilterParam1 = filterPar1;
analysisFmMono->saFilterType2 = filter2;
analysisFmMono->saFilterParam2 = filterPar2;
analysisFmMono->saFilterType3 = filter3;
analysisFmMono->saFilterParam3 = filterPar3;
analysisFmMono->audFreqL = audioFreqLowLimitHz;
analysisFmMono->audFreqH = audioFreqHiLimitHz;
hndl->hndlFm->analysis = dynamic_cast<iqapiAnalysisFmMono *>(analysisFmMono);
}
if (LP_Analyze_FM_Hndl())
{
err = ERR_FM_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_Analyze_Audio_Mono", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_Analyze_Audio_Mono", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_Analyze_Audio_Stereo(int audioRBWHz,
int audioFreqLowLimitHz,
int audioFreqHiLimitHz,
int filterCount,
int filterType1,
double filterParam1,
int filterType2,
double filterParam2,
int filterType3,
double filterParam3)
{
int err = ERR_OK;
//Clear previous results stored
g_FmStereoScalarResults.clear();
g_FmStereoVectorResults.clear();
IQV_FM_FILTER_TYPE filter1 =(IQV_FM_FILTER_TYPE)filterType1;
double filterPar1 = filterParam1;
IQV_FM_FILTER_TYPE filter2 =(IQV_FM_FILTER_TYPE)filterType2;
double filterPar2 = filterParam2;
IQV_FM_FILTER_TYPE filter3 =(IQV_FM_FILTER_TYPE)filterType3;
double filterPar3 = filterParam3;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_Analyze_Audio_Stereo", &timeStart);
if (FmInitialized)
{
if (!hndl->hndlFm->dataFm)
{
err = ERR_FM_NO_CAPTURE_DATA;
return err;
}
else
{
if (!hndl->hndlFm->dataFm->length) //crezon revision
{
err = ERR_FM_NO_CAPTURE_DATA;
return err;
}
}
if(g_audioCaptureOnly)
{
analysisAudioStereo->saNFilters = filterCount;
analysisAudioStereo->saResBw = audioRBWHz;
analysisAudioStereo->saFilterType1 = filter1;
analysisAudioStereo->saFilterParam1 = filterPar1;
analysisAudioStereo->saFilterType2 = filter2;
analysisAudioStereo->saFilterParam2 = filterPar2;
analysisAudioStereo->saFilterType3 = filter3;
analysisAudioStereo->saFilterParam3 = filterPar3;
analysisAudioStereo->audFreqL = audioFreqLowLimitHz;
analysisAudioStereo->audFreqH = audioFreqHiLimitHz;
hndl->hndlFm->analysis = dynamic_cast<iqapiAnalysisAudioStereo *>(analysisAudioStereo);
}
else
{
//analysisFmStereo->saNFilters = filterCount;
//analysisFmStereo->saResBw = audioRBWHz;
//analysisFmStereo->saFilterType1 = filter1;
//analysisFmStereo->saFilterParam1 = filterPar1;
//analysisFmStereo->saFilterType2 = filter2;
//analysisFmStereo->saFilterParam2 = filterPar2;
//analysisFmStereo->saFilterType3 = filter3;
//analysisFmStereo->saFilterParam3 = filterPar3;
//analysisFmStereo->audFreqL = audioFreqLowLimitHz;
//analysisFmStereo->audFreqH = audioFreqHiLimitHz;
//hndl->hndlFm->analysis = dynamic_cast<iqapiAnalysisFmStereo *>(analysisFmStereo);
analysisFmAuto->saNFilters = filterCount;
analysisFmAuto->saResBw = audioRBWHz;
analysisFmAuto->saFilterType1 = filter1;
analysisFmAuto->saFilterParam1 = filterPar1;
analysisFmAuto->saFilterType2 = filter2;
analysisFmAuto->saFilterParam2 = filterPar2;
analysisFmAuto->saFilterType3 = filter3;
analysisFmAuto->saFilterParam3 = filterPar3;
analysisFmAuto->audFreqL = audioFreqLowLimitHz;
analysisFmAuto->audFreqH = audioFreqHiLimitHz;
hndl->hndlFm->analysis = dynamic_cast<iqapiAnalysisFmAuto *>(analysisFmAuto);
}
if (LP_Analyze_FM_Hndl())
{
err = ERR_FM_ANALYSIS_FAILED;
}
else
{
}
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_Analyze_Audio_Stereo", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_Analyze_Audio_Stereo", timeDuration);
return err;
}
IQMEASURE_API double LP_FM_GetScalarMeasurement_NoTimer(char *measurement, int index)
{
if (FmInitialized)
{
if (!hndl->hndlFm->results)
{
return NA_NUMBER;
}
else
{
if(hndl->hndlFm->results)
{
if (dynamic_cast<iqapiResultFmRf *>(hndl->hndlFm->results))
{
resultFmRf = dynamic_cast<iqapiResultFmRf *>(hndl->hndlFm->results);
if(g_FmRfScalarResults.find(measurement) == g_FmRfScalarResults.end())
{
g_FmRfScalarResults["totalPower"] = resultFmRf->totalPower;
g_FmRfScalarResults["powerInBw"] = resultFmRf->powerInBw;
g_FmRfScalarResults["obw"] = resultFmRf->obw;
g_FmRfScalarResults["spectrumWaveLength"] = resultFmRf->spectrumWaveLength;
g_FmRfScalarResults["RfSpectrumWaveSaLength"] = resultFmRf->RfSpectrumWaveSaLength;
g_FmRfScalarResults["RfSpectrumWaveSaResBw"] = resultFmRf->RfSpectrumWaveSaResBw;
g_FmRfScalarResults["RfSpectrumWaveSaNoiseBw"] = resultFmRf->RfSpectrumWaveSaNoiseBw;
g_FmRfScalarResults["RfSpectrumWaveSaFreqStart"] = resultFmRf->RfSpectrumWaveSaFreqStart;
g_FmRfScalarResults["RfSpectrumWaveSaFreqStop"] = resultFmRf->RfSpectrumWaveSaFreqStop;
}
else
{
// DO nothing
}
if(g_FmRfScalarResults.find(measurement) == g_FmRfScalarResults.end())
{
return NA_NUMBER;
}
else
{
return((double)g_FmRfScalarResults.find(measurement)->second);
}
}
else if (dynamic_cast<iqapiResultFmDemodSpectrum *>(hndl->hndlFm->results))
{
resultFmDemodSpectrum = dynamic_cast<iqapiResultFmDemodSpectrum *>(hndl->hndlFm->results);
if(g_FmRfScalarResults.find(measurement) == g_FmRfScalarResults.end())
{
g_FmRfScalarResults["demodPlusPeakDeviation"] = resultFmDemodSpectrum->demodPlusPeakDeviation;
g_FmRfScalarResults["demodMinusPeakDeviation"] = resultFmDemodSpectrum->demodMinusPeakDeviation;
g_FmRfScalarResults["demodAveragePeakDeviation"] = resultFmDemodSpectrum->demodAveragePeakDeviation;
g_FmRfScalarResults["demodRmsPeakDeviation"] = resultFmDemodSpectrum->demodRmsPeakDeviation;
g_FmRfScalarResults["demodCfo"] = resultFmDemodSpectrum->demodCfo;
g_FmRfScalarResults["audioSpectrumWaveSaLength"] = resultFmDemodSpectrum->audioSpectrumWaveSaFreqStop;
g_FmRfScalarResults["audioSpectrumWaveSaResBw"] = resultFmDemodSpectrum->audioSpectrumWaveSaFreqStop;
g_FmRfScalarResults["audioSpectrumWaveSaNoiseBw"] = resultFmDemodSpectrum->audioSpectrumWaveSaFreqStop;
g_FmRfScalarResults["audioSpectrumWaveSaFreqStart"] = resultFmDemodSpectrum->audioSpectrumWaveSaFreqStop;
g_FmRfScalarResults["audioSpectrumWaveSaFreqStop"] = resultFmDemodSpectrum->audioSpectrumWaveSaFreqStop;
g_FmRfScalarResults["audioSpectrumWaveLength"] = resultFmDemodSpectrum->audioSpectrumWaveLength;
g_FmRfScalarResults["audioWaveLength"] = resultFmDemodSpectrum->audioWaveLength;
}
else
{
// DO nothing
}
if(g_FmRfScalarResults.find(measurement) == g_FmRfScalarResults.end())
{
return NA_NUMBER;
}
else
{
return((double)g_FmRfScalarResults.find(measurement)->second);
}
}
else if (dynamic_cast<iqapiResultAudioStereo *>(hndl->hndlFm->results))
{
resultAudioStereo = dynamic_cast<iqapiResultAudioStereo *>(hndl->hndlFm->results);
if(g_FmStereoScalarResults.find(measurement) == g_FmStereoScalarResults.end())
{
g_FmStereoScalarResults["audioSpectrumWaveSaLength"] = resultAudioStereo->audioSpectrumWaveSaLength;
g_FmStereoScalarResults["audioSpectrumWaveSaResBw"] = resultAudioStereo->audioSpectrumWaveSaResBw;
g_FmStereoScalarResults["audioSpectrumWaveSaNoiseBw"] = resultAudioStereo->audioSpectrumWaveSaNoiseBw;
g_FmStereoScalarResults["audioSpectrumWaveSaFreqStart"] = resultAudioStereo->audioSpectrumWaveSaFreqStart;
g_FmStereoScalarResults["audioSpectrumWaveSaFreqStop"] = resultAudioStereo->audioSpectrumWaveSaFreqStop;
g_FmStereoScalarResults["leftAudioSpectrumWaveLength"] = resultAudioStereo->leftAudioSpectrumWaveLength;
g_FmStereoScalarResults["leftAudioSpectrumWaveToneNSigFreq"] = resultAudioStereo->leftAudioSpectrumWaveToneNSigFreq;
g_FmStereoScalarResults["leftAudioSpectrumWaveLength"] = resultAudioStereo->leftAudioSpectrumWaveLength;
g_FmStereoScalarResults["leftAudioSpectrumWaveToneNSigFreq"] = resultAudioStereo->leftAudioSpectrumWaveToneNSigFreq;
g_FmStereoScalarResults["rightAudioSpectrumWaveLength"] = resultAudioStereo->rightAudioSpectrumWaveLength;
g_FmStereoScalarResults["rightAudioSpectrumWaveToneNSigFreq"] = resultAudioStereo->rightAudioSpectrumWaveToneNSigFreq;
g_FmStereoScalarResults["leftAudioSpectrumWaveToneSigPower"] = resultAudioStereo->leftAudioSpectrumWaveToneSigPower[0];
g_FmStereoScalarResults["rightAudioSpectrumWaveToneSigPower"] = resultAudioStereo->rightAudioSpectrumWaveToneSigPower[0];
g_FmStereoScalarResults["leftAudioAnaSnr"] = resultAudioStereo->leftAudioAnaSnr;
g_FmStereoScalarResults["rightAudioAnaSnr"] = resultAudioStereo->rightAudioAnaSnr;
g_FmStereoScalarResults["leftAudioAnaSinad"] = resultAudioStereo->leftAudioAnaSinad;
g_FmStereoScalarResults["rightAudioAnaSinad"] = resultAudioStereo->rightAudioAnaSinad;
g_FmStereoScalarResults["leftAudioAnaThd"] = resultAudioStereo->leftAudioAnaThd;
g_FmStereoScalarResults["rightAudioAnaThd"] = resultAudioStereo->rightAudioAnaThd;
g_FmStereoScalarResults["leftAudioAnaThdPlusN"] = (20*log10(resultAudioStereo->leftAudioAnaThdPlusN));
g_FmStereoScalarResults["rightAudioAnaThdPlusN"] = (20*log10(resultAudioStereo->rightAudioAnaThdPlusN));
g_FmStereoScalarResults["leftAudioAnaTnhd"] = resultAudioStereo->leftAudioAnaTnhd;
g_FmStereoScalarResults["rightAudioAnaTnhd"] = resultAudioStereo->rightAudioAnaTnhd;
g_FmStereoScalarResults["crosstalkMaxPower"] = resultAudioStereo->crosstalkMaxPower;
g_FmStereoScalarResults["crosstalkCrosstalk"] = resultAudioStereo->crosstalkCrosstalk[0];
g_FmStereoScalarResults["crosstalkNSigFreq"] = resultAudioStereo->crosstalkNSigFreq;
}
else
{
}
if(g_FmStereoScalarResults.find(measurement) == g_FmStereoScalarResults.end())
{
return NA_NUMBER;
}
else
{
return((double)g_FmStereoScalarResults.find(measurement)->second);
}
}
else if (dynamic_cast<iqapiResultAudioMono *>(hndl->hndlFm->results))
{
resultAudioMono = dynamic_cast<iqapiResultAudioMono *>(hndl->hndlFm->results);
if(g_FmMonoScalarResults.find(measurement) == g_FmMonoScalarResults.end())
{
g_FmMonoScalarResults["audioSpectrumWaveSaLength"] = resultAudioMono->audioSpectrumWaveSaLength;
g_FmMonoScalarResults["audioSpectrumWaveSaResBw"] = resultAudioMono->audioSpectrumWaveSaResBw;
g_FmMonoScalarResults["audioSpectrumWaveSaNoiseBw"] = resultAudioMono->audioSpectrumWaveSaNoiseBw;
g_FmMonoScalarResults["audioSpectrumWaveSaFreqStart"] = resultAudioMono->audioSpectrumWaveSaFreqStart;
g_FmMonoScalarResults["audioSpectrumWaveSaFreqStop"] = resultAudioMono->audioSpectrumWaveSaFreqStop;
g_FmMonoScalarResults["audioAnaSnr"] = resultAudioMono->audioAnaSnr;
g_FmMonoScalarResults["audioAnaSinad"] = resultAudioMono->audioAnaSinad;
g_FmMonoScalarResults["audioAnaThd"] = resultAudioMono->audioAnaThd;
g_FmMonoScalarResults["audioAnaThdPlusN"] = (20*log10(resultAudioMono->audioAnaThdPlusN));
g_FmMonoScalarResults["audioAnaTnhd"] = resultAudioMono->audioAnaTnhd;
g_FmMonoScalarResults["audioSpectrumWaveToneSigPower"] = resultAudioMono->audioSpectrumWaveToneSigPower[0];
g_FmMonoScalarResults["audioSpectrumWaveLength"] = resultAudioMono->audioSpectrumWaveLength;
g_FmMonoScalarResults["audioSpectrumWaveToneNSigFreq"] = resultAudioMono->audioSpectrumWaveToneNSigFreq;
}
else
{
}
if(g_FmMonoScalarResults.find(measurement) == g_FmMonoScalarResults.end())
{
return NA_NUMBER;
}
else
{
return((double)g_FmMonoScalarResults.find(measurement)->second);
}
}
else if (dynamic_cast<iqapiResultFmStereo *>(hndl->hndlFm->results))
{
resultFmStereo = dynamic_cast<iqapiResultFmStereo *>(hndl->hndlFm->results);
if(g_FmStereoScalarResults.find(measurement) == g_FmStereoScalarResults.end())
{
g_FmStereoScalarResults["leftAudioSpectrumWaveToneSigPower"] = resultFmStereo->leftAudioSpectrumWaveToneSigPower[0];
g_FmStereoScalarResults["rightAudioSpectrumWaveToneSigPower"] = resultFmStereo->rightAudioSpectrumWaveToneSigPower[0];
g_FmStereoScalarResults["leftAudioAnaSnr"] = resultFmStereo->leftAudioAnaSnr;
g_FmStereoScalarResults["rightAudioAnaSnr"] = resultFmStereo->rightAudioAnaSnr;
g_FmStereoScalarResults["leftAudioAnaSinad"] = resultFmStereo->leftAudioAnaSinad;
g_FmStereoScalarResults["rightAudioAnaSinad"] = resultFmStereo->rightAudioAnaSinad;
g_FmStereoScalarResults["leftAudioAnaThd"] = resultFmStereo->leftAudioAnaThd;
g_FmStereoScalarResults["rightAudioAnaThd"] = resultFmStereo->rightAudioAnaThd;
g_FmStereoScalarResults["leftAudioAnaThdPlusN"] = (20*log10(resultFmStereo->leftAudioAnaThdPlusN));
g_FmStereoScalarResults["rightAudioAnaThdPlusN"] = (20*log10(resultFmStereo->rightAudioAnaThdPlusN));
g_FmStereoScalarResults["leftAudioAnaTnhd"] = resultFmStereo->leftAudioAnaTnhd;
g_FmStereoScalarResults["rightAudioAnaTnhd"] = resultFmStereo->rightAudioAnaTnhd;
g_FmStereoScalarResults["pilotFrequencyOffset"] = resultFmStereo->pilotFrequencyOffset;
g_FmStereoScalarResults["crosstalkCrosstalk"] = resultFmStereo->crosstalkCrosstalk[0];
g_FmStereoScalarResults["leftAudioSpectrumWaveLength"] = resultFmStereo->leftAudioSpectrumWaveLength;
g_FmStereoScalarResults["leftAudioWaveLength"] = resultFmStereo->leftAudioWaveLength;
g_FmStereoScalarResults["leftAudioSpectrumWaveToneNSigFreq"] = resultFmStereo->leftAudioSpectrumWaveToneNSigFreq;
g_FmStereoScalarResults["rightAudioSpectrumWaveLength"] = resultFmStereo->rightAudioSpectrumWaveLength;
g_FmStereoScalarResults["rightAudioWaveLength"] = resultFmStereo->rightAudioWaveLength;
g_FmStereoScalarResults["rightAudioSpectrumWaveToneNSigFreq"] = resultFmStereo->rightAudioSpectrumWaveToneNSigFreq;
g_FmStereoScalarResults["crosstalkNSigFreq"] = resultFmStereo->crosstalkNSigFreq;
g_FmStereoScalarResults["crosstalkMaxPower"] = resultFmStereo->crosstalkMaxPower;
g_FmStereoScalarResults["pilotIsStereo"] = resultFmStereo->pilotIsStereo;
g_FmStereoScalarResults["audioDeviation"] = resultFmStereo->audioDeviation;
g_FmStereoScalarResults["pilotDeviation"] = resultFmStereo->pilotDeviation;
}
else
{
}
if(g_FmStereoScalarResults.find(measurement) == g_FmStereoScalarResults.end())
{
return NA_NUMBER;
}
else
{
return((double)g_FmStereoScalarResults.find(measurement)->second);
}
}
else if (dynamic_cast<iqapiResultFmMono *>(hndl->hndlFm->results))
{
resultFmMono = dynamic_cast<iqapiResultFmMono *>(hndl->hndlFm->results);
if(g_FmMonoScalarResults.find(measurement) == g_FmMonoScalarResults.end())
{
g_FmMonoScalarResults["AudioSpectrumWaveToneSigPower"] = resultFmMono->audioSpectrumWaveToneSigPower[0];
g_FmMonoScalarResults["audioSpectrumWaveSaLength"] = resultFmMono->audioSpectrumWaveSaLength;
g_FmMonoScalarResults["audioSpectrumWaveSaResBw"] = resultFmMono->audioSpectrumWaveSaResBw;
g_FmMonoScalarResults["audioSpectrumWaveSaNoiseBw"] = resultFmMono->audioSpectrumWaveSaNoiseBw;
g_FmMonoScalarResults["audioSpectrumWaveSaFreqStart"] = resultFmMono->audioSpectrumWaveSaFreqStart;
g_FmMonoScalarResults["audioSpectrumWaveSaFreqStop"] = resultFmMono->audioSpectrumWaveSaFreqStop;
g_FmMonoScalarResults["audioAnaSnr"] = resultFmMono->audioAnaSnr;
g_FmMonoScalarResults["audioAnaSinad"] = resultFmMono->audioAnaSinad;
g_FmMonoScalarResults["audioAnaThd"] = resultFmMono->audioAnaThd;
g_FmMonoScalarResults["audioAnaThdPlusN"] = (20*log10(resultFmMono->audioAnaThdPlusN));
g_FmMonoScalarResults["audioAnaTnhd"] = resultFmMono->audioAnaTnhd;
g_FmMonoScalarResults["audioSpectrumWaveLength"] = resultFmMono->audioSpectrumWaveLength;
g_FmMonoScalarResults["audioWaveLength"] = resultFmMono->audioWaveLength;
g_FmMonoScalarResults["audioSpectrumWaveToneNSigFreq"] = resultFmMono->audioSpectrumWaveToneNSigFreq;
}
else
{
}
if(g_FmMonoScalarResults.find(measurement) == g_FmMonoScalarResults.end())
{
return NA_NUMBER;
}
else
{
return((double)g_FmMonoScalarResults.find(measurement)->second);
}
}
}
}
}
else
{
return NA_NUMBER;
}
return NA_NUMBER;
}
IQMEASURE_API double LP_FM_GetScalarMeasurement(char *measurement, int index)
{
::TIMER_StartTimer(timerIQmeasure, "LP_FM_GetScalarMeasurement", &timeStart);
double value = LP_FM_GetScalarMeasurement_NoTimer(measurement, index);
::TIMER_StopTimer(timerIQmeasure, "LP_FM_GetScalarMeasurement", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_GetScalarMeasurement", timeDuration);
return value;
}
IQMEASURE_API int LP_FM_GetVectorMeasurement_NoTimer(char *measurement, double bufferReal[], double bufferImag[], int bufferLength)
{
if (FmInitialized)
{
if (!hndl->hndlFm->results || !bufferReal || !bufferLength)
{
return 0;
}
if(hndl->hndlFm->results)
{
if (dynamic_cast<iqapiResultFmRf *>(hndl->hndlFm->results))
{
if(g_FmRfVectorResults.find(measurement) == g_FmRfVectorResults.end())
{
resultFmRf = dynamic_cast<iqapiResultFmRf *>(hndl->hndlFm->results);
g_FmRfVectorResults["spectrumWaveX"].assign(resultFmRf->spectrumWaveX, (resultFmRf->spectrumWaveX + MAX_OUTPUT_WAVE_LENGTH));
g_FmRfVectorResults["spectrumWaveY"].assign(resultFmRf->spectrumWaveY, (resultFmRf->spectrumWaveY + MAX_OUTPUT_WAVE_LENGTH));
}
else
{
// Do Nothing
}
if(g_FmRfVectorResults.find(measurement) == g_FmRfVectorResults.end())
{
return (int)NA_NUMBER;
}
else
{
for(int i = 0; i < bufferLength; i++)
{
bufferReal[i] = g_FmRfVectorResults[measurement].at(i);
}
return bufferLength;
}
}
else if (dynamic_cast<iqapiResultAudioStereo *>(hndl->hndlFm->results))
{
if(g_FmStereoVectorResults.find(measurement) == g_FmStereoVectorResults.end())
{
resultAudioStereo = dynamic_cast<iqapiResultAudioStereo *>(hndl->hndlFm->results);
g_FmStereoVectorResults["crosstalkChannelIndex"].assign(resultAudioStereo->crosstalkChannelIndex, (resultAudioStereo->crosstalkChannelIndex + 50));
g_FmStereoVectorResults["crosstalkCrosstalk"].assign(resultAudioStereo->crosstalkCrosstalk, (resultAudioStereo->crosstalkCrosstalk + 50));
g_FmStereoVectorResults["crosstalkSigFreq"].assign(resultAudioStereo->crosstalkSigFreq, (resultAudioStereo->crosstalkSigFreq + 50));
g_FmStereoVectorResults["leftAudioSpectrumWaveToneSigFreq"].assign(resultAudioStereo->leftAudioSpectrumWaveToneSigFreq, (resultAudioStereo->leftAudioSpectrumWaveToneSigFreq + 50));
g_FmStereoVectorResults["leftAudioSpectrumWaveToneSigPower"].assign(resultAudioStereo->leftAudioSpectrumWaveToneSigPower, (resultAudioStereo->leftAudioSpectrumWaveToneSigPower + 50));
g_FmStereoVectorResults["leftAudioSpectrumWaveX"].assign(resultAudioStereo->leftAudioSpectrumWaveX, (resultAudioStereo->leftAudioSpectrumWaveX + MAX_OUTPUT_WAVE_LENGTH));
g_FmStereoVectorResults["leftAudioSpectrumWaveY"].assign(resultAudioStereo->leftAudioSpectrumWaveY, (resultAudioStereo->leftAudioSpectrumWaveY + MAX_OUTPUT_WAVE_LENGTH));
g_FmStereoVectorResults["rightAudioSpectrumWaveToneSigFreq"].assign(resultAudioStereo->rightAudioSpectrumWaveToneSigFreq, (resultAudioStereo->rightAudioSpectrumWaveToneSigFreq + 50));
g_FmStereoVectorResults["rightAudioSpectrumWaveToneSigPower"].assign(resultAudioStereo->rightAudioSpectrumWaveToneSigPower, (resultAudioStereo->rightAudioSpectrumWaveToneSigPower + 50));
g_FmStereoVectorResults["rightAudioSpectrumWaveX"].assign(resultAudioStereo->rightAudioSpectrumWaveX, (resultAudioStereo->rightAudioSpectrumWaveX + MAX_OUTPUT_WAVE_LENGTH));
g_FmStereoVectorResults["rightAudioSpectrumWaveY"].assign(resultAudioStereo->rightAudioSpectrumWaveY, (resultAudioStereo->rightAudioSpectrumWaveY + MAX_OUTPUT_WAVE_LENGTH));
}
else
{
// Do Nothing
}
if(g_FmStereoVectorResults.find(measurement) == g_FmStereoVectorResults.end())
{
return (int)NA_NUMBER;
}
else
{
for(int i = 0; i < bufferLength; i++)
{
bufferReal[i] = g_FmStereoVectorResults[measurement].at(i);
}
return bufferLength;
}
}
else if (dynamic_cast<iqapiResultAudioMono *>(hndl->hndlFm->results))
{
if(g_FmMonoVectorResults.find(measurement) == g_FmMonoVectorResults.end())
{
resultAudioMono = dynamic_cast<iqapiResultAudioMono *>(hndl->hndlFm->results);
g_FmMonoVectorResults["audioSpectrumWaveToneSigFreq"].assign(resultAudioMono->audioSpectrumWaveToneSigFreq, (resultAudioMono->audioSpectrumWaveToneSigFreq + 50));
g_FmMonoVectorResults["audioSpectrumWaveToneSigPower"].assign(resultAudioMono->audioSpectrumWaveToneSigPower, (resultAudioMono->audioSpectrumWaveToneSigPower + 50));
g_FmMonoVectorResults["audioSpectrumWaveX"].assign(resultAudioMono->audioSpectrumWaveX, (resultAudioMono->audioSpectrumWaveX + MAX_OUTPUT_WAVE_LENGTH));
g_FmMonoVectorResults["audioSpectrumWaveY"].assign(resultAudioMono->audioSpectrumWaveY, (resultAudioMono->audioSpectrumWaveY + MAX_OUTPUT_WAVE_LENGTH));
}
else
{
// Do Nothing
}
if(g_FmRfVectorResults.find(measurement) == g_FmRfVectorResults.end())
{
return (int)NA_NUMBER;
}
else
{
for(int i = 0; i < bufferLength; i++)
{
bufferReal[i] = g_FmRfVectorResults[measurement].at(i);
}
return bufferLength;
}
}
else if (dynamic_cast<iqapiResultFmStereo *>(hndl->hndlFm->results))
{
if(g_FmStereoVectorResults.find(measurement) == g_FmStereoVectorResults.end())
{
resultFmStereo = dynamic_cast<iqapiResultFmStereo *>(hndl->hndlFm->results);
g_FmStereoVectorResults["crosstalkChannelIndex"].assign(resultFmStereo->crosstalkChannelIndex, (resultFmStereo->crosstalkChannelIndex + 50));
g_FmStereoVectorResults["crosstalkCrosstalk"].assign(resultFmStereo->crosstalkCrosstalk, (resultFmStereo->crosstalkCrosstalk + 50));
g_FmStereoVectorResults["crosstalkSigFreq"].assign(resultFmStereo->crosstalkSigFreq, (resultFmStereo->crosstalkSigFreq + 50));
g_FmStereoVectorResults["leftAudioSpectrumWaveToneSigFreq"].assign(resultFmStereo->leftAudioSpectrumWaveToneSigFreq, (resultFmStereo->leftAudioSpectrumWaveToneSigFreq + 50));
g_FmStereoVectorResults["leftAudioSpectrumWaveToneSigPower"].assign(resultFmStereo->leftAudioSpectrumWaveToneSigPower, (resultFmStereo->leftAudioSpectrumWaveToneSigPower + 50));
g_FmStereoVectorResults["leftAudioSpectrumWaveX"].assign(resultFmStereo->leftAudioSpectrumWaveX, (resultFmStereo->leftAudioSpectrumWaveX + MAX_OUTPUT_WAVE_LENGTH));
g_FmStereoVectorResults["leftAudioSpectrumWaveY"].assign(resultFmStereo->leftAudioSpectrumWaveY, (resultFmStereo->leftAudioSpectrumWaveY + MAX_OUTPUT_WAVE_LENGTH));
g_FmStereoVectorResults["leftAudioWaveX"].assign(resultFmStereo->leftAudioWaveX, (resultFmStereo->leftAudioWaveX + MAX_OUTPUT_WAVE_LENGTH));
g_FmStereoVectorResults["leftAudioWaveY"].assign(resultFmStereo->leftAudioWaveY, (resultFmStereo->leftAudioWaveY + MAX_OUTPUT_WAVE_LENGTH));
g_FmStereoVectorResults["rightAudioSpectrumWaveToneSigFreq"].assign(resultFmStereo->rightAudioSpectrumWaveToneSigFreq, (resultFmStereo->rightAudioSpectrumWaveToneSigFreq + 50));
g_FmStereoVectorResults["rightAudioSpectrumWaveToneSigPower"].assign(resultFmStereo->rightAudioSpectrumWaveToneSigPower, (resultFmStereo->rightAudioSpectrumWaveToneSigPower + 50));
g_FmStereoVectorResults["rightAudioSpectrumWaveToneSigPower"].assign(resultFmStereo->rightAudioSpectrumWaveX, (resultFmStereo->rightAudioSpectrumWaveX + MAX_OUTPUT_WAVE_LENGTH));
g_FmStereoVectorResults["rightAudioSpectrumWaveToneSigPower"].assign(resultFmStereo->rightAudioSpectrumWaveY, (resultFmStereo->rightAudioSpectrumWaveY + MAX_OUTPUT_WAVE_LENGTH));
g_FmStereoVectorResults["rightAudioWaveX"].assign(resultFmStereo->rightAudioWaveX, (resultFmStereo->rightAudioWaveX + MAX_OUTPUT_WAVE_LENGTH));
g_FmStereoVectorResults["rightAudioWaveY"].assign(resultFmStereo->rightAudioWaveY, (resultFmStereo->rightAudioWaveY + MAX_OUTPUT_WAVE_LENGTH));
}
else
{
// Do Nothing
}
if(g_FmStereoVectorResults.find(measurement) == g_FmStereoVectorResults.end())
{
return (int)NA_NUMBER;
}
else
{
for(int i = 0; i < bufferLength; i++)
{
bufferReal[i] = g_FmStereoVectorResults[measurement].at(i);
}
return bufferLength;
}
}
else if (dynamic_cast<iqapiResultFmMono *>(hndl->hndlFm->results))
{
if(g_FmMonoVectorResults.find(measurement) == g_FmMonoVectorResults.end())
{
resultFmMono = dynamic_cast<iqapiResultFmMono *>(hndl->hndlFm->results);
g_FmMonoVectorResults["audioSpectrumWaveToneSigFreq"].assign(resultFmMono->audioSpectrumWaveToneSigFreq, (resultFmMono->audioSpectrumWaveToneSigFreq + 50));
g_FmMonoVectorResults["audioSpectrumWaveToneSigPower"].assign(resultFmMono->audioSpectrumWaveToneSigPower, (resultFmMono->audioSpectrumWaveToneSigPower + 50));
g_FmMonoVectorResults["audioSpectrumWaveX"].assign(resultFmMono->audioSpectrumWaveX, (resultFmMono->audioSpectrumWaveX + MAX_OUTPUT_WAVE_LENGTH));
g_FmMonoVectorResults["audioSpectrumWaveY"].assign(resultFmMono->audioSpectrumWaveY, (resultFmMono->audioSpectrumWaveY + MAX_OUTPUT_WAVE_LENGTH));
g_FmMonoVectorResults["audioWaveX"].assign(resultFmMono->audioWaveX, (resultFmMono->audioWaveX + MAX_OUTPUT_WAVE_LENGTH));
g_FmMonoVectorResults["audioWaveY"].assign(resultFmMono->audioWaveY, (resultFmMono->audioWaveY + MAX_OUTPUT_WAVE_LENGTH));
}
else
{
// Do Nothing
}
if(g_FmRfVectorResults.find(measurement) == g_FmRfVectorResults.end())
{
return (int)NA_NUMBER;
}
else
{
for(int i = 0; i < bufferLength; i++)
{
bufferReal[i] = g_FmRfVectorResults[measurement].at(i);
}
return bufferLength;
}
}
}
else
{
return (int)NA_NUMBER;
}
}
else
{
return (int)NA_NUMBER;
}
return (int)NA_NUMBER;
}
IQMEASURE_API int LP_FM_GetVectorMeasurement(char *measurement, double bufferReal[], double bufferImag[], int bufferLength)
{
::TIMER_StartTimer(timerIQmeasure, "LP_FM_GetVectorMeasurement", &timeStart);
int ret = LP_FM_GetVectorMeasurement_NoTimer(measurement, bufferReal, bufferImag, bufferLength);
::TIMER_StopTimer(timerIQmeasure, "LP_FM_GetVectorMeasurement", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_GetVectorMeasurement", timeDuration);
return ret;
}
IQMEASURE_API int LP_FM_AudioDataCapture(char* saveFileLocation,
double captureDurationMilliSec,
int samplingRate,
int stereo)
{
int err = ERR_OK;
//Clear previous results stored
g_FmRfScalarResults.clear();
g_FmMonoScalarResults.clear();
g_FmStereoScalarResults.clear();
g_FmRfVectorResults.clear();
g_FmMonoVectorResults.clear();
g_FmStereoVectorResults.clear();
::TIMER_StartTimer(timerIQmeasure, "LP_FM_AudioDataCapture", &timeStart);
int aimErr = ERR_OK;
// Calling AIM Control function from AimControl.h
aimErr = AIM_CaptureAndSaveAudio(samplingRate, captureDurationMilliSec, saveFileLocation, stereo);
if(ERR_AIM_CAPTURE_AUDIO_FAILED == aimErr)
{
err = ERR_FM_CAPTURE_AUDIO_FAILED;
}
else if(ERR_AIM_SAVE_WAV_AUDIO_FAILED == aimErr)
{
err = ERR_FM_SAVE_WAV_AUDIO_FAILED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_AudioDataCapture", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_AudioDataCapture", timeDuration);
return 0;
}
IQMEASURE_API int LP_FM_LoadAudioCapture(char* fileName)
{
// const int bufSize = 1024;
// int numberOfChannel = 0;
// int indexChannel = 0;
// char temp[100]={};
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_LoadAudioCapture", &timeStart);
// need to add check for wav file validity - need to check for wave headers for valid format
if(FmInitialized)
{
err = hndl->hndlFm->LoadSignalFileWav(fileName);
// set g_audioCaptureOnly flag to indicate that this is an audio capture
g_audioCaptureOnly = true;
}
else
{
err = ERR_FM_NOT_INITIALIZED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_LoadAudioCapture", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_LoadAudioCapture", timeDuration);
return err;
}
// LP_FM_AudioStimulusGenerate function
IQMEASURE_API int LP_FM_AudioStimulusGenerateAndPlayMultiTone(double sampleRateHz,
double deviationPercent,
double peakVoltageLevelVolts,
int toneCount,
int stereoEnable,
int* leftRightRelation,
double* freqHz,
double durationMilliSeconds,
char* audioWaveFileOutput)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_AudioStimulusGenerateMultiTone", &timeStart);
double peakVoltage = (deviationPercent * peakVoltageLevelVolts / 100);
int aimErr = 0;
// Calling AIM Control function from AimControl.h
aimErr = AIM_GenerateAndPlayAudioMultiTone(sampleRateHz, peakVoltage, toneCount,
stereoEnable, leftRightRelation, freqHz,
durationMilliSeconds, audioWaveFileOutput);
if(ERR_AIM_GENERATE_AUDIO_FAILED == aimErr)
{
err = ERR_FM_GENERATE_AUDIO_FAILED;
}
else if(ERR_AIM_SAVE_WAV_AUDIO_FAILED == aimErr)
{
err = ERR_FM_SAVE_WAV_AUDIO_FAILED;
}
else
{
err = ERR_FM_PLAY_AUDIO_FAILED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_AudioStimulusGenerateMultiTone", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_AudioStimulusGenerateMultiTone", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_AudioStimulusGenerateAndPlaySingleTone(double sampleRateHz,
double deviationPercent,
double peakVoltageLevelVolts,
int stereoEnable,
int leftRightRelation,
double freqHz,
double durationMilliSeconds,
char* audioWaveFileOutput)
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_AudioStimulusGenerateSingleTone", &timeStart);
double peakVoltage = (deviationPercent * peakVoltageLevelVolts / 100);
int aimErr = 0;
// Calling AIM Control function from AimControl.h
aimErr = AIM_GenerateAndPlayAudioSingleTone(sampleRateHz, peakVoltage,
stereoEnable, leftRightRelation, freqHz,
durationMilliSeconds, audioWaveFileOutput);
if(ERR_AIM_GENERATE_AUDIO_FAILED == aimErr)
{
err = ERR_FM_GENERATE_AUDIO_FAILED;
}
else if(ERR_AIM_SAVE_WAV_AUDIO_FAILED == aimErr)
{
err = ERR_FM_SAVE_WAV_AUDIO_FAILED;
}
else if(ERR_AIM_PLAY_AUDIO_FAILED == aimErr)
{
err = ERR_FM_PLAY_AUDIO_FAILED;
}
else
{
err = aimErr;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_AudioStimulusGenerateSingleTone", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_AudioStimulusGenerateSingleTone", timeDuration);
return err;
}
IQMEASURE_API int LP_FM_StopAudioPlay()
{
int err = ERR_OK;
::TIMER_StartTimer(timerIQmeasure, "LP_FM_StopAudioPlay", &timeStart);
int aimStopAudioErr = 0;
// Calling AIM Control function from AimControl.h
aimStopAudioErr = AIM_StopPlayAudio();
if(ERR_AIM_STOP_AUDIO_PLAY_FAILED == aimStopAudioErr)
{
err = ERR_FM_STOP_AUDIO_PLAY_FAILED;
}
::TIMER_StopTimer(timerIQmeasure, "LP_FM_StopAudioPlay", &timeDuration, &timeStop);
::LOGGER_Write_Ext(LOG_IQMEASURE, loggerIQmeasure, LOGGER_INFORMATION, "[IQMEASURE],[%s],%.2f,ms\n", "LP_FM_StopAudioPlay", timeDuration);
return err;
}
#endif //WIN32 //Not using FM for Mac at this time
| [
"zfh1005@126.com"
] | zfh1005@126.com |
afab00bb184674055ceeb9d096a5f545251686ae | c98bef868402592c13442cc8f32940ac9ba28359 | /Unit06/AbstractClass/Shape.cpp | 899a4b07905b8f5d07a850f882511fdab1d65743 | [] | no_license | lijianmin01/CplusplusStudy | f5f05db3968583e5d7a6aa61afae8c13cedfa308 | 895750549ea6a5f9bc046155c29017b6398c5508 | refs/heads/master | 2022-10-05T06:16:28.799141 | 2020-06-14T09:22:52 | 2020-06-14T09:22:52 | 266,767,557 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 765 | cpp | #include "Shape.h"
#include<array>
Shape::Shape(Color color_, bool filled_) {
color = color_;
filled = filled_;
}
Color Shape::getColor() { return color; }
void Shape::setColor(Color color) {
this->color = color;
}
bool Shape::isFilled() {
return filled;
}
void Shape::setFilled(bool filled) {
this->filled = filled;
}
string Shape::toString() {
//std::array<string, 6> c{ "white"s,"black"s,"red"s,"green"s,"blue"s,"yellow"s, };
//return "Shape: " + c[static_cast<int>(color)] + " " + (filled ? "filled"s : "not filled"s);
return "Shape: " + colorToString() + " " + filledToString();
}
string Shape::colorToString() {
return colorNames[static_cast<int>(color)];
}
string Shape::filledToString() {
return (filled ? "filled"s : "not filled"s);
}
| [
"lijianmin01@126.com"
] | lijianmin01@126.com |
cc9eadde3091ce3392d6acfa76b9beb40e397555 | fc38a55144a0ad33bd94301e2d06abd65bd2da3c | /thirdparty/cgal/CGAL-4.13/include/CGAL/Barycentric_coordinates_2/Discrete_harmonic_2.h | 5ab84f168856f37f05266c65d63915397a05ed42 | [
"LGPL-3.0-only",
"GPL-3.0-only",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"LicenseRef-scancode-free-unknown",
"LGPL-2.0-or-later",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"MIT-0",
"MIT",
"LGPL-3.0-or-later",
"LicenseRef-scancode-warranty-disc... | permissive | bobpepin/dust3d | 20fc2fa4380865bc6376724f0843100accd4b08d | 6dcc6b1675cb49ef3fac4a58845f9c9025aa4c9f | refs/heads/master | 2022-11-30T06:00:10.020207 | 2020-08-09T09:54:29 | 2020-08-09T09:54:29 | 286,051,200 | 0 | 0 | MIT | 2020-08-08T13:45:15 | 2020-08-08T13:45:14 | null | UTF-8 | C++ | false | false | 19,151 | h | // Copyright (c) 2014 INRIA Sophia-Antipolis (France).
// All rights reserved.
//
// This file is a part of CGAL (www.cgal.org).
// You can redistribute it and/or modify it under the terms of the GNU
// General Public License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
// SPDX-License-Identifier: GPL-3.0+
//
// Author(s) : Dmitry Anisimov, David Bommes, Kai Hormann, and Pierre Alliez.
/*!
\file Discrete_harmonic_2.h
*/
#ifndef CGAL_DISCRETE_HARMONIC_2_H
#define CGAL_DISCRETE_HARMONIC_2_H
#include <CGAL/license/Barycentric_coordinates_2.h>
#include <CGAL/disable_warnings.h>
// CGAL headers.
#include <CGAL/assertions.h>
#include <CGAL/Polygon_2_algorithms.h>
// Barycentric coordinates headers.
#include <CGAL/Barycentric_coordinates_2/barycentric_enum_2.h>
// Boost headers.
#include <boost/optional/optional.hpp>
// CGAL namespace.
namespace CGAL {
// Barycentric coordinates namespace.
namespace Barycentric_coordinates {
// Examples: see the User Manual here - https://doc.cgal.org/latest/Manual/index.html.
// [1] Reference: "M. S. Floater, K. Hormann, and G. Kos. A general construction of barycentric coordinates over convex polygons. Advances in Computational Mathematics, 24(1-4):311-331, 2006.".
/*!
* \ingroup PkgBarycentric_coordinates_2
* The class `Discrete_harmonic_2` implements 2D discrete harmonic coordinates ( \cite cgal:bc:fhk-gcbcocp-06, \cite cgal:pp-cdmsc-93, \cite cgal:bc:eddhls-maam-95 ).
* This class is parameterized by a traits class `Traits`, and it is used as a coordinate class to complete the class `Generalized_barycentric_coordinates_2`.
* For a polygon with three vertices (triangle) it is better to use the class `Triangle_coordinates_2`.
* Discrete harmonic coordinates can be computed exactly. By definition, they do not necesserily give positive values.
\tparam Traits must be a model of the concepts `BarycentricTraits_2` and `PolygonTraits_2`.
\cgalModels `BarycentricCoordinates_2`
\pre The provided polygon is strictly convex.
*/
template<class Traits>
class Discrete_harmonic_2
{
public:
/// \name Types
/// @{
/// Number type.
typedef typename Traits::FT FT;
/// Point type.
typedef typename Traits::Point_2 Point_2;
/// @}
// \name Creation
// Creates the class `Discrete_harmonic_2` that implements the behaviour of discrete harmonic coordinates for any query point that does not belong to the polygon's boundary.
// The polygon is given by a range of vertices of the type `Traits::Point_2` stored in a container of the type <a href="http://en.cppreference.com/w/cpp/container/vector">`std::vector`</a>.
Discrete_harmonic_2(const std::vector<typename Traits::Point_2> &vertices, const Traits &b_traits) :
vertex(vertices),
barycentric_traits(b_traits),
number_of_vertices(vertex.size()),
area_2(barycentric_traits.compute_area_2_object()),
squared_distance_2(barycentric_traits.compute_squared_distance_2_object()),
collinear_2(barycentric_traits.collinear_2_object())
{
// Resize all the internal containers.
r.resize(number_of_vertices);
A.resize(number_of_vertices);
B.resize(number_of_vertices);
weight.resize(number_of_vertices);
}
// Computation of Discrete Harmonic Weight Functions
// This function computes discrete harmonic weights (unnormalized coordinates) for a chosen query point.
template<class OutputIterator>
inline boost::optional<OutputIterator> weights(const Point_2 &query_point, OutputIterator &output)
{
return weights_2(query_point, output);
}
// Computation of Discrete Harmonic Basis Functions
// This function computes discrete harmonic barycentric coordinates for a chosen query point on the bounded side of a strictly convex polygon.
// \pre The provided polygon is strictly convex.
template<class OutputIterator>
inline boost::optional<OutputIterator> coordinates_on_bounded_side(const Point_2 &query_point, OutputIterator &output, const Type_of_algorithm type_of_algorithm)
{
switch(type_of_algorithm)
{
case PRECISE:
return coordinates_on_bounded_side_precise_2(query_point, output);
break;
case FAST:
return coordinates_on_bounded_side_fast_2(query_point, output);
break;
}
// Pointer cannot be here. Something went wrong.
const bool type_of_algorithm_failure = true;
CGAL_postcondition( !type_of_algorithm_failure );
if(!type_of_algorithm_failure) return boost::optional<OutputIterator>(output);
else return boost::optional<OutputIterator>();
}
// This function computes discrete harmonic barycentric coordinates for a chosen query point on the unbounded side of a strictly convex polygon.
// \pre The provided polygon is strictly convex.
template<class OutputIterator>
inline boost::optional<OutputIterator> coordinates_on_unbounded_side(const Point_2 &query_point, OutputIterator &output, const Type_of_algorithm type_of_algorithm, const bool warning_tag = true)
{
switch(type_of_algorithm)
{
case PRECISE:
return coordinates_on_unbounded_side_precise_2(query_point, output, warning_tag);
break;
case FAST:
return coordinates_on_unbounded_side_fast_2(query_point, output, warning_tag);
break;
}
// Pointer cannot be here. Something went wrong.
const bool type_of_algorithm_failure = true;
CGAL_postcondition( !type_of_algorithm_failure );
if(!type_of_algorithm_failure) return boost::optional<OutputIterator>(output);
else return boost::optional<OutputIterator>();
}
// Information Functions
// This function prints some information about discrete harmonic coordinates.
void print_coordinates_information(std::ostream &output_stream) const
{
return print_coordinates_information_2(output_stream);
}
private:
// Some convenient typedefs.
typedef typename std::vector<FT> FT_vector;
typedef typename std::vector<Point_2> Point_vector;
// Internal global variables.
const Point_vector &vertex;
const Traits &barycentric_traits;
const size_t number_of_vertices;
FT_vector r, A, B, weight;
FT dh_denominator, inverted_dh_denominator;
typename Traits::Compute_area_2 area_2;
typename Traits::Compute_squared_distance_2 squared_distance_2;
typename Traits::Collinear_2 collinear_2;
// WEIGHTS.
// Compute discrete harmonic weights without normalization.
template<class OutputIterator>
boost::optional<OutputIterator> weights_2(const Point_2 &query_point, OutputIterator &output)
{
// Get the number of vertices in the polygon.
const int n = int(number_of_vertices);
// Compute areas A, B, and distances r following the notation from [1]. Split the loop to make this computation faster.
r[0] = squared_distance_2(vertex[0] , query_point);
A[0] = area_2(vertex[0] , vertex[1], query_point);
B[0] = area_2(vertex[n-1], vertex[1], query_point);
for(int i = 1; i < n-1; ++i) {
r[i] = squared_distance_2(vertex[i] , query_point);
A[i] = area_2(vertex[i] , vertex[i+1], query_point);
B[i] = area_2(vertex[i-1], vertex[i+1], query_point);
}
r[n-1] = squared_distance_2(vertex[n-1], query_point);
A[n-1] = area_2(vertex[n-1], vertex[0] , query_point);
B[n-1] = area_2(vertex[n-2], vertex[0] , query_point);
// Compute unnormalized weights following the formula (25) with p = 2 from [1].
CGAL_precondition( A[n-1] != FT(0) && A[0] != FT(0) );
*output = (r[1]*A[n-1] - r[0]*B[0] + r[n-1]*A[0]) / (A[n-1] * A[0]);
++output;
for(int i = 1; i < n-1; ++i) {
CGAL_precondition( A[i-1] != FT(0) && A[i] != FT(0) );
*output = (r[i+1]*A[i-1] - r[i]*B[i] + r[i-1]*A[i]) / (A[i-1] * A[i]);
++output;
}
CGAL_precondition( A[n-2] != FT(0) && A[n-1] != FT(0) );
*output = (r[0]*A[n-2] - r[n-1]*B[n-1] + r[n-2]*A[n-1]) / (A[n-2] * A[n-1]);
// Return weights.
return boost::optional<OutputIterator>(output);
}
// COORDINATES ON BOUNDED SIDE.
// Compute discrete harmonic coordinates on the bounded side of the polygon with the slow O(n^2) but precise algorithm.
// Here, n - is the number of the polygon's vertices.
template<class OutputIterator>
boost::optional<OutputIterator> coordinates_on_bounded_side_precise_2(const Point_2 &query_point, OutputIterator &output)
{
CGAL_precondition( type_of_polygon() == STRICTLY_CONVEX );
// Get the number of vertices in the polygon.
const int n = int(number_of_vertices);
// Compute areas A, B, and distances r following the notation from [1]. Split the loop to make this computation faster.
r[0] = squared_distance_2(vertex[0] , query_point);
A[0] = area_2(vertex[0] , vertex[1], query_point);
B[0] = area_2(vertex[n-1], vertex[1], query_point);
for(int i = 1; i < n-1; ++i) {
r[i] = squared_distance_2(vertex[i] , query_point);
A[i] = area_2(vertex[i] , vertex[i+1], query_point);
B[i] = area_2(vertex[i-1], vertex[i+1], query_point);
}
r[n-1] = squared_distance_2(vertex[n-1], query_point);
A[n-1] = area_2(vertex[n-1], vertex[0] , query_point);
B[n-1] = area_2(vertex[n-2], vertex[0] , query_point);
// Initialize weights with the numerator of the formula (25) with p = 2 from [1].
// Then we multiply them by areas A as in the formula (5) in [1]. We also split the loop.
weight[0] = r[1]*A[n-1] - r[0]*B[0] + r[n-1]*A[0];
for(int j = 1; j < n-1; ++j) weight[0] *= A[j];
for(int i = 1; i < n-1; ++i) {
weight[i] = r[i+1]*A[i-1] - r[i]*B[i] + r[i-1]*A[i];
for(int j = 0; j < i-1; ++j) weight[i] *= A[j];
for(int j = i+1; j < n; ++j) weight[i] *= A[j];
}
weight[n-1] = r[0]*A[n-2] - r[n-1]*B[n-1] + r[n-2]*A[n-1];
for(int j = 0; j < n-2; ++j) weight[n-1] *= A[j];
// Compute the sum of all weights - denominator of discrete harmonic coordinates.
dh_denominator = weight[0];
for(int i = 1; i < n; ++i) dh_denominator += weight[i];
// Invert this denominator.
CGAL_precondition( dh_denominator != FT(0) );
inverted_dh_denominator = FT(1) / dh_denominator;
// Normalize weights and save them as resulting discrete harmonic coordinates.
for(int i = 0; i < n-1; ++i) {
*output = weight[i] * inverted_dh_denominator;
++output;
}
*output = weight[n-1] * inverted_dh_denominator;
// Return coordinates.
return boost::optional<OutputIterator>(output);
}
// Compute discrete harmonic coordinates on the bounded side of the polygon with the fast O(n) but less precise algorithm.
// Here, n - is the number of the polygon's vertices. Precision is lost near the boundary (~ 1.0e-10 and closer).
template<class OutputIterator>
boost::optional<OutputIterator> coordinates_on_bounded_side_fast_2(const Point_2 &query_point, OutputIterator &output)
{
CGAL_precondition( type_of_polygon() == STRICTLY_CONVEX );
// Get the number of vertices in the polygon.
const int n = int(number_of_vertices);
// Compute areas A, B, and distances r following the notation from [1]. Split the loop to make this computation faster.
r[0] = squared_distance_2(vertex[0] , query_point);
A[0] = area_2(vertex[0] , vertex[1], query_point);
B[0] = area_2(vertex[n-1], vertex[1], query_point);
for(int i = 1; i < n-1; ++i) {
r[i] = squared_distance_2(vertex[i] , query_point);
A[i] = area_2(vertex[i] , vertex[i+1], query_point);
B[i] = area_2(vertex[i-1], vertex[i+1], query_point);
}
r[n-1] = squared_distance_2(vertex[n-1], query_point);
A[n-1] = area_2(vertex[n-1], vertex[0] , query_point);
B[n-1] = area_2(vertex[n-2], vertex[0] , query_point);
// Compute unnormalized weights following the formula (25) with p = 2 from [1].
CGAL_precondition( A[n-1] != FT(0) && A[0] != FT(0) );
weight[0] = (r[1]*A[n-1] - r[0]*B[0] + r[n-1]*A[0]) / (A[n-1] * A[0]);
for(int i = 1; i < n-1; ++i) {
CGAL_precondition( A[i-1] != FT(0) && A[i] != FT(0) );
weight[i] = (r[i+1]*A[i-1] - r[i]*B[i] + r[i-1]*A[i]) / (A[i-1] * A[i]);
}
CGAL_precondition( A[n-2] != FT(0) && A[n-1] != FT(0) );
weight[n-1] = (r[0]*A[n-2] - r[n-1]*B[n-1] + r[n-2]*A[n-1]) / (A[n-2] * A[n-1]);
// Compute the sum of all weights - denominator of discrete harmonic coordinates.
dh_denominator = weight[0];
for(int i = 1; i < n; ++i) dh_denominator += weight[i];
// Invert this denominator.
CGAL_precondition( dh_denominator != FT(0) );
inverted_dh_denominator = FT(1) / dh_denominator;
// Normalize weights and save them as resulting discrete harmonic coordinates.
for(int i = 0; i < n-1; ++i) {
*output = weight[i] * inverted_dh_denominator;
++output;
}
*output = weight[n-1] * inverted_dh_denominator;
// Return coordinates.
return boost::optional<OutputIterator>(output);
}
// COORDINATES ON UNBOUNDED SIDE.
// Compute discrete harmonic coordinates on the unbounded side of the polygon with the slow O(n^2) but precise algorithm.
// Here, n - is the number of the polygon's vertices.
template<class OutputIterator>
boost::optional<OutputIterator> coordinates_on_unbounded_side_precise_2(const Point_2 &query_point, OutputIterator &output, bool warning_tag)
{
if(warning_tag)
std::cout << std::endl << "ATTENTION: Discrete harmonic coordinates might be not well-defined outside the polygon!" << std::endl;
// Use the same formulas as for the bounded side since they are also valid on the unbounded side.
return coordinates_on_bounded_side_precise_2(query_point, output);
}
// Compute discrete harmonic coordinates on the unbounded side of the polygon with the fast O(n) but less precise algorithm.
// Here, n - is the number of the polygon's vertices. Precision is lost near the boundary (~ 1.0e-10 and closer).
template<class OutputIterator>
boost::optional<OutputIterator> coordinates_on_unbounded_side_fast_2(const Point_2 &query_point, OutputIterator &output, bool warning_tag)
{
if(warning_tag)
std::cout << std::endl << "ATTENTION: Discrete harmonic coordinates might be not well-defined outside the polygon!" << std::endl;
// Use the same formulas as for the bounded side since they are also valid on the unbounded side.
return coordinates_on_bounded_side_fast_2(query_point, output);
}
// OTHER FUNCTIONS.
// Print some information about discrete harmonic coordinates.
void print_coordinates_information_2(std::ostream &output_stream) const
{
output_stream << std::endl << "CONVEXITY: " << std::endl << std::endl;
if(type_of_polygon() == STRICTLY_CONVEX) {
output_stream << "This polygon is strictly convex." << std::endl;
} else if(type_of_polygon() == WEAKLY_CONVEX) {
output_stream << "This polygon is weakly convex. The correct computation is not expected!" << std::endl;
} else if(type_of_polygon() == CONCAVE) {
output_stream << "This polygon polygon is not convex. The correct computation is not expected!" << std::endl;
}
output_stream << std::endl << "TYPE OF COORDINATES: " << std::endl << std::endl;
output_stream << "The coordinate functions to be computed are discrete harmonic coordinates." << std::endl;
output_stream << std::endl << "INFORMATION ABOUT COORDINATES: " << std::endl << std::endl;
output_stream << "Discrete harmonic coordinates are well-defined in the closure of an arbitrary strictly convex polygon and can be computed exactly." << std::endl;
output_stream << std::endl;
output_stream << "They satisfy the following properties: " << std::endl;
output_stream << "1. Partition of unity or constant precision;" << std::endl;
output_stream << "2. Homogeneity or linear precision;" << std::endl;
output_stream << "3. Lagrange property;" << std::endl;
output_stream << "4. Linearity along edges;" << std::endl;
output_stream << "5. Smoothness;" << std::endl;
output_stream << "6. Similarity invariance;" << std::endl;
output_stream << std::endl;
output_stream << "For polygons whose vertices lie on a common circle, they coincide with Wachspress coordinates." << std::endl;
output_stream << std::endl << "REFERENCE: " << std::endl << std::endl;
output_stream << "M. S. Floater, K. Hormann, and G. Kos. A general construction of barycentric coordinates over convex polygons. Advances in Computational Mathematics, 24(1-4):311-331, 2006." << std::endl;
}
// Check the type of the provided polygon - CONVEX, STRICTLY_CONVEX, or CONCAVE.
Type_of_polygon type_of_polygon() const
{
// First, test the polygon on convexity.
if(CGAL::is_convex_2(vertex.begin(), vertex.end(), barycentric_traits)) {
// Index of the last polygon's vertex.
const int last = int(number_of_vertices) - 1;
// Test all the consequent triplets of the polygon's vertices on collinearity.
// In case we find at least one, return WEAKLY_CONVEX polygon.
if(collinear_2(vertex[last], vertex[0], vertex[1]))
return WEAKLY_CONVEX;
for(int i = 1; i < last; ++i) {
if(collinear_2(vertex[i-1], vertex[i], vertex[i+1]))
return WEAKLY_CONVEX;
}
if(collinear_2(vertex[last-1], vertex[last], vertex[0]))
return WEAKLY_CONVEX;
// Otherwise, return STRICTLY_CONVEX polygon.
return STRICTLY_CONVEX;
}
// Otherwise, return CONCAVE polygon.
return CONCAVE;
}
};
} // namespace Barycentric_coordinates
} // namespace CGAL
#include <CGAL/enable_warnings.h>
#endif // CGAL_DISCRETE_HARMONIC_2_H
| [
"huxingyi@msn.com"
] | huxingyi@msn.com |
7af58d9e1c17ec456d869b748fbb5903a8325983 | 70986bced7a24bf5a904b40ecabd44ec5139ea04 | /ConceptsAndQuestions/cses/1687.cpp | 2a5767fa840bedf7a799f69ba9e70fe6370609ac | [] | no_license | shrey/templates_cpp | f79cd09a729d9bc7a8dc620f4824c152b4f833ac | a6b6b8186f7e763c5029230a36fed8506f6d8cf9 | refs/heads/master | 2023-07-12T07:38:44.909862 | 2021-08-25T06:11:00 | 2021-08-25T06:11:00 | 283,482,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,089 | cpp |
//Shrey Dubey
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
#include<unordered_map>
#include<vector>
#include<set>
#include<list>
#include<iomanip>
#include<queue>
#include<stack>
#include <math.h>
#include<climits>
#include<bitset>
#include<cstring>
#include<numeric>
#include<array>
using namespace std;
typedef long long ll;
typedef long double ld;
#define YES cout<<"YES\n"
#define Yes cout<<"Yes\n"
#define NO cout<<"NO\n"
#define No cout<<"No\n"
#define prDouble(x) cout<<fixed<<setprecision(10)<<x //to print decimal numbers
#define pb push_back
#define ff first
#define sec second
#define umap unordered_map
#define mp make_pair
#define KOBE ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define fo(n) for(ll i = 0; i<n; i++)
#define fnd(stl, data) find(stl.begin(), stl.end(), data)
#define forn(x,n) for(ll x = 0; x<n; x++)
#define imax INT_MAX
#define lmax LLONG_MAX
#define imin INT_MIN
#define lmin LLONG_MIN
#define vi vector<ll>
#define vl vector<ll>
#define vp vector<pair<ll,ll> >
#define vb vector<bool>
#define pr(t) cout<<t<<"\n"
#define ll long long
#define ql queue<ll>
#define qp queue<pair<ll,ll> >
#define endl "\n"
#define nl cout<<"\n"
#define re cin >>
#define pll pair<ll,ll>
#define FOR(a,b) for(ll i = a; i<=b; i++)
#define all(x) x.begin(),x.end()
// ll dx[] = {1,0,-1,0};
// ll dy[] = {0,1,0,-1};
ll mod = 1e9 + 7;
ll cl(ld a){
if(a>(ll) a){
return (ll)a+1;
}
else{
return (ll)a;
}
}
ll flr(ld a){
if(a < 0.0){
return (ll) a - 1;
}
return (ll) a;
}
//code starts here
ll n,q,x,y;
const ll M = 2e5 + 5; const ll mxe = 30;
vl gr[M];
ll up[M][mxe];
bool vis[M];
void dfs(ll cur, ll p) { // keep track of current node and its parent node
up[cur][0] = p; // mark the parent in the array
vis[cur] = 1; // mark the node as visited
for(ll x: gr[cur]) if(!vis[x]) dfs(x,cur); // visit all unvisited children
}
void solve(){
//take the input
re n; re q;
memset(up,-1,sizeof(up));
for(ll i = 2; i<=n; i++){
// re x; re y;
// gr[x].pb(y);
// gr[y].pb(x);
re up[i][0]; //did this for a qn, change it to take edge input
}
// dfs(1,-1); //use it when performing on normal graph
for(ll l = 1; l<mxe; l++){
for(ll i = 1; i<=n; i++){
if(up[i][l-1] != -1) up[i][l] = up[up[i][l-1]][l-1];
}
}
fo(q){
ll k;
re x; re k;
for(ll l = 0; l<mxe; l++){
if(x != -1 && (k & (1<<l))){
x = up[x][l];
}
}
pr(x);
}
}
int32_t main(){
KOBE;
ll t;
t = 1;
// re t;
while(t--) solve();
}
//common errors
// row - n, col - m always and loop var
// see the freq of numbers carefully
// see if there's array overflow
// use map for large inputs
//problem ideas
//check piegonhole wherever possible
//there might be many instances of limited answers like 0,1,2 only
// see suffix and prefix
//don't be obsessed with binary search
// try to find repeating pattern in matrices
| [
"wshrey09@gmail.com"
] | wshrey09@gmail.com |
7a2ea5f58b51c192b0062e573d761b1013eb6f11 | 18aee5d93a63eab684fe69e3aa0abd1372dd5d08 | /paddle/fluid/framework/ir/sigmoid_elementmul_fuse_pass.cc | 6904e5604fb5c75454681178a35c505334d99f9b | [
"Apache-2.0"
] | permissive | Shixiaowei02/Paddle | 8d049f4f29e281de2fb1ffcd143997c88078eadb | 3d4d995f26c48f7792b325806ec3d110fc59f6fc | refs/heads/develop | 2023-06-26T06:25:48.074273 | 2023-06-14T06:40:21 | 2023-06-14T06:40:21 | 174,320,213 | 2 | 1 | Apache-2.0 | 2022-12-28T05:14:30 | 2019-03-07T10:09:34 | C++ | UTF-8 | C++ | false | false | 4,536 | cc | // Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include "glog/logging.h"
#include "paddle/fluid/framework/ir/fuse_pass_base.h"
#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
#include "paddle/fluid/framework/ir/pass.h"
#include "paddle/fluid/framework/ir/sigmoid_elementmul_fuse_pass.h"
#include "paddle/fluid/framework/op_version_registry.h"
#include "paddle/fluid/platform/enforce.h"
namespace paddle {
namespace framework {
namespace ir {
namespace patterns {
struct SigmoidElementmulFusePattern : public PatternBase {
SigmoidElementmulFusePattern(PDPattern* pattern,
const std::string& name_scope);
// declare operator node's name
PATTERN_DECL_NODE(sigmoid);
PATTERN_DECL_NODE(elementwise_mul);
// declare variable node's name
PATTERN_DECL_NODE(sigmoid_x);
PATTERN_DECL_NODE(sigmoid_out);
PATTERN_DECL_NODE(elemul_out);
};
SigmoidElementmulFusePattern::SigmoidElementmulFusePattern(
PDPattern* pattern, const std::string& name_scope)
: PatternBase(pattern, name_scope, name_scope) {
auto* sigmoid_x = pattern->NewNode(sigmoid_x_repr())
->assert_is_op_input("sigmoid", "X")
->assert_var_not_persistable();
auto* sigmoid_op = pattern->NewNode(sigmoid_repr())->assert_is_op("sigmoid");
auto* sigmoid_out = pattern->NewNode(sigmoid_out_repr())
->assert_is_op_output("sigmoid", "Out")
->assert_var_not_persistable();
auto* elemul_op =
pattern->NewNode(elementwise_mul_repr())->assert_is_op("elementwise_mul");
auto* elemul_out = pattern->NewNode(elemul_out_repr())
->assert_is_op_output("elementwise_mul", "Out")
->assert_var_not_persistable();
sigmoid_op->LinksFrom({sigmoid_x}).LinksTo({sigmoid_out});
elemul_op->LinksFrom({sigmoid_x, sigmoid_out}).LinksTo({elemul_out});
}
} // namespace patterns
SigmoidElementmulFusePass::SigmoidElementmulFusePass() {}
void SigmoidElementmulFusePass::ApplyImpl(ir::Graph* graph) const {
PADDLE_ENFORCE_NOT_NULL(
graph, platform::errors::PreconditionNotMet("graph should not be null."));
Init(name_scope_, graph);
GraphPatternDetector gpd;
patterns::SigmoidElementmulFusePattern pattern(gpd.mutable_pattern(),
name_scope_);
int found_subgraph_count = 0;
auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,
Graph* graph) {
VLOG(4) << "handle SigmoidElementmulFusePass fuse";
#define GET_IR_NODE(node_) GET_IR_NODE_FROM_SUBGRAPH(node_, node_, pattern)
GET_IR_NODE(sigmoid_x);
GET_IR_NODE(sigmoid);
GET_IR_NODE(sigmoid_out);
GET_IR_NODE(elementwise_mul);
GET_IR_NODE(elemul_out);
#undef GET_IR_NODE
auto* block = sigmoid->Op()->Block();
std::string elemul_out_name = elemul_out->Name();
// Generate swish op
framework::OpDesc swish_op_desc(block);
swish_op_desc.SetType("swish");
swish_op_desc.SetInput("X", {sigmoid_x->Name()});
swish_op_desc.SetAttr("beta", 1.f);
swish_op_desc.SetOutput("Out", {elemul_out_name});
auto* swish = graph->CreateOpNode(&swish_op_desc);
IR_NODE_LINK_TO(sigmoid_x, swish);
IR_NODE_LINK_TO(swish, elemul_out);
// delete useless node
std::unordered_set<const Node*> delete_nodes;
delete_nodes = {sigmoid, sigmoid_out, elementwise_mul};
GraphSafeRemoveNodes(graph, delete_nodes);
found_subgraph_count++;
};
gpd(graph, handler);
AddStatis(found_subgraph_count);
}
} // namespace ir
} // namespace framework
} // namespace paddle
REGISTER_PASS(sigmoid_elementmul_fuse_pass,
paddle::framework::ir::SigmoidElementmulFusePass);
REGISTER_PASS_CAPABILITY(sigmoid_elementmul_fuse_pass)
.AddCombination(
paddle::framework::compatible::OpVersionComparatorCombination().EQ(
"swish", 0));
| [
"noreply@github.com"
] | noreply@github.com |
6d43c7b07091c8b6c5c3b63c3a41d4302907b4fc | 16a442cec4ce9bfbb0f2e6859085e41d6ad1cfb7 | /plugins/cudnn/frontend/CudnnFrontend.h | ef794f64c7555a37183e271877d7e32471cb171a | [
"Apache-2.0"
] | permissive | tonivega/GVirtuS | 7158b7cd1815da403e0a31787f124478593a2ff4 | e85517ac0e8ba570e76dd60e759513572174ea81 | refs/heads/master | 2023-08-27T20:04:22.932886 | 2021-11-14T16:34:13 | 2021-11-14T16:34:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,539 | h | /*
* gVirtuS -- A GPGPU transparent virtualization component.
*
* Copyright (C) 2009-2010 The University of Napoli Parthenope at Naples.
*
* This file is part of gVirtuS.
*
* gVirtuS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* gVirtuS 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 General Public License
* along with gVirtuS; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Written by: Giuseppe Coviello <giuseppe.coviello@uniparthenope.it>,
* Department of Applied Science
*/
#ifndef CUDNNFRONTEND_H
#define CUDNNFRONTEND_H
#include <map>
#include <set>
#include <stack>
#include <list>
#include <iostream>
#include <cudnn.h>
#include <gvirtus/frontend/Frontend.h>
using gvirtus::communicators::Buffer;
using gvirtus::frontend::Frontend;
typedef struct __configureFunction{
gvirtus::common::funcs __f;
gvirtus::communicators::Buffer* buffer;
} configureFunction;
class CudnnFrontend {
public:
static inline void Execute(const char * routine, const Buffer * input_buffer = NULL) {
Frontend::GetFrontend()->Execute(routine, input_buffer);
}
/**
* Prepares the Frontend for the execution. This method _must_ be called
* before any requests of execution or any method for adding parameters for
* the next execution.
*/
static inline void Prepare() {
Frontend::GetFrontend()->Prepare();
}
static inline Buffer *GetLaunchBuffer() {
return Frontend::GetFrontend()->GetInputBuffer();
}
/**
* Adds a scalar variabile as an input parameter for the next execution
* request.
*
* @param var the variable to add as a parameter.
*/
template <class T> static inline void AddVariableForArguments(T var) {
Frontend::GetFrontend()->GetInputBuffer()->Add(var);
}
/**
* Adds a string (array of char(s)) as an input parameter for the next
* execution request.
*
* @param s the string to add as a parameter.
*/
static inline void AddStringForArguments(const char *s) {
Frontend::GetFrontend()->GetInputBuffer()->AddString(s);
}
/**
* Adds, marshalling it, an host pointer as an input parameter for the next
* execution request.
* The optional parameter n is usefull when adding an array: with n is
* possible to specify the length of the array in terms of elements.
*
* @param ptr the pointer to add as a parameter.
* @param n the length of the array, if ptr is an array.
*/
template <class T>static inline void AddHostPointerForArguments(T *ptr, size_t n = 1) {
Frontend::GetFrontend()->GetInputBuffer()->Add(ptr, n);
}
/**
* Adds a device pointer as an input parameter for the next execution
* request.
*
* @param ptr the pointer to add as a parameter.
*/
static inline void AddDevicePointerForArguments(const void *ptr) {
Frontend::GetFrontend()->GetInputBuffer()->Add((uint64_t) ptr);
}
/**
* Adds a symbol, a named variable, as an input parameter for the next
* execution request.
*
* @param symbol the symbol to add as a parameter.
*/
static inline void AddSymbolForArguments(const char *symbol) {
/* TODO: implement AddSymbolForArguments
* AddStringForArguments(CudaUtil::MarshalHostPointer((void *) symbol));
* AddStringForArguments(symbol);
* */
}
static inline cudnnStatus_t GetExitCode() {
return (cudnnStatus_t) Frontend::GetFrontend()->GetExitCode();
}
static inline bool Success() {
return Frontend::GetFrontend()->Success(cudaSuccess);
}
template <class T> static inline T GetOutputVariable() {
return Frontend::GetFrontend()->GetOutputBuffer()->Get<T> ();
}
/**
* Retrives an host pointer from the output parameters of the last execution
* request.
* The optional parameter n is usefull when retriving an array: with n is
* possible to specify the length of the array in terms of elements.
*
* @param n the length of the array.
*
* @return the pointer from the output parameters.
*/
template <class T>static inline T * GetOutputHostPointer(size_t n = 1) {
return Frontend::GetFrontend()->GetOutputBuffer()->Assign<T> (n);
}
/**
* Retrives a device pointer from the output parameters of the last
* execution request.
*
* @return the pointer to the device memory.
*/
static inline void * GetOutputDevicePointer() {
return (void *) Frontend::GetFrontend()->GetOutputBuffer()->Get<uint64_t>();
}
/**
* Retrives a string, array of chars, from the output parameters of the last
* execution request.
*
* @return the string from the output parameters.
*/
static inline char * GetOutputString() {
return Frontend::GetFrontend()->GetOutputBuffer()->AssignString();
}
CudnnFrontend();
static void * handler;
};
#endif /* CUDNNFRONTEND_H */
| [
"gco@nec-labs.com"
] | gco@nec-labs.com |
de44d487e337780f3714cb675b844772efb21fbe | 0c9ca0bf95cdaeaef3be0d81d17ade9ff050bdc7 | /lib/fles_ipc/TimesliceSubscriber.cpp | ac01ab07e029154c9a609a169dd721cdf8288c9e | [] | no_license | tim-geier/flesnet | a6fa19cf27ab6eb708948b5df5bab589cfa8599e | 28a7e0836fd68b329267799f28cbf9cdae436d88 | refs/heads/master | 2020-08-26T10:29:37.358680 | 2020-06-29T11:07:00 | 2020-06-29T11:07:00 | 217,001,067 | 0 | 0 | null | 2020-04-16T07:22:41 | 2019-10-23T07:58:23 | C++ | UTF-8 | C++ | false | false | 1,030 | cpp | // Copyright 2014 Jan de Cuveland <cmail@cuveland.de>
#include "TimesliceSubscriber.hpp"
namespace fles {
TimesliceSubscriber::TimesliceSubscriber(const std::string& address,
uint32_t hwm) {
subscriber_.setsockopt(ZMQ_RCVHWM, hwm);
subscriber_.connect(address.c_str());
subscriber_.setsockopt(ZMQ_SUBSCRIBE, nullptr, 0);
}
fles::StorableTimeslice* TimesliceSubscriber::do_get() {
if (eos_flag) {
return nullptr;
}
zmq::message_t message;
subscriber_.recv(&message);
boost::iostreams::basic_array_source<char> device(
static_cast<char*>(message.data()), message.size());
boost::iostreams::stream<boost::iostreams::basic_array_source<char>> s(
device);
boost::archive::binary_iarchive ia(s);
fles::StorableTimeslice* sts = nullptr;
try {
sts = new fles::StorableTimeslice();
ia >> *sts;
} catch (boost::archive::archive_exception& e) {
delete sts;
eos_flag = true;
return nullptr;
}
return sts;
}
} // namespace fles
| [
"cuveland@compeng.uni-frankfurt.de"
] | cuveland@compeng.uni-frankfurt.de |
022fb23b2acb234f1da416ec20fa025e6c47d259 | 2286cad2c9042d2e9b4130cae289e28ab144446d | /srcs/get_real_path.cpp | 096d93968a1d8abd67624e033cf71dd4d2de2bc9 | [] | no_license | rcherik/Gomoku | 114ebddf1c9986c991e66fa133580bc5f39cc7e8 | a9bd864f3d169ec5751bdffbbd318cc45c8f03c1 | refs/heads/master | 2021-01-19T03:34:55.263024 | 2017-04-05T15:30:09 | 2017-04-05T15:30:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,680 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_real_path.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mdufaud <mdufaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2014/04/30 22:47:41 by mdufaud #+# #+# */
/* Updated: 2016/07/01 11:47:03 by rcherik ### ########.fr */
/* */
/* ************************************************************************** */
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <mach-o/dyld.h>
#ifdef __linux__
std::string getRealPath(void)
{
char tmp[32];
char buf[1024];
int bytes;
std::string s;
sprintf(tmp, "/proc/%d/exe", getpid());
bytes = readlink(tmp, buf, 1024);
bytes = bytes > 1023 ? 1203 : bytes;
if (bytes >= 0)
buf[bytes] = 0;
s = std::string(buf);
s.erase(s.begin() + s.find_last_of("/"), s.end());
s += std::string("/");
return (s);
}
#endif
#ifdef __APPLE__
std::string getRealPath(void)
{
char buf[1024];
uint32_t size;
std::string s;
size = 1024;
if (_NSGetExecutablePath(buf, &size) != 0)
return ("");
buf[size - 1] = 0;
s = std::string(buf);
s.erase(s.begin() + s.find_last_of("/"), s.end());
s += std::string("/");
return (s);
}
#endif
| [
"rcherik@student.42.fr"
] | rcherik@student.42.fr |
fce671ce199802bd862f58607be7f97b01ea3e3d | c8f63f9504d8b4d129ef61332cc0f347a47e5e92 | /room.cpp | 58383c7b1ac9835b9ae448c5f51fc006f8d34568 | [] | no_license | BassmanB/AcademicalProjectC | 01e50c05c6959ce0f84291a320f6b68d95f84148 | a51392f04d0ea100d149f64473ecaff79d877d24 | refs/heads/master | 2020-03-21T05:36:34.966477 | 2018-06-21T12:45:39 | 2018-06-21T12:45:39 | 138,168,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,406 | cpp | #include "stdafx.h"
#include "room.h"
#include <random>
#include <iostream>
using namespace std;
void putToRoom(reception &receptions, room rooms[]) {
for (int j = 0; j < receptions.family.size(); j++) {
for (int i = 0; i < receptions.family.size(); i++) {
if (rooms[j].familyName.size() <= rooms[j].capacity && rooms[j].familyName[i] == "empty") {
rooms[j].familyName[i] = receptions.family[i];
receptions.family.erase(receptions.family.begin() + i);
}
}
}
};
int make_rooms(room rooms[]) {
int sumOfRooms = 0;
for (int i = 0; i<15; i++) {
rooms[i].number = i;
rooms[i].capacity = rand() % 5 + 1;
}
for (int i = 0; i<15; i++) {
sumOfRooms = sumOfRooms + rooms[i].capacity;
}
return sumOfRooms;
};
void removeFromRoom(room rooms[], vector<string> family){
for (int i = 0; i < 15; i++) {
for (int j = 0; j <rooms[i].familyName.size(); j++) {
if (rooms[i].familyName[j] ==family[j]){
rooms[i].familyName[j] = "empty";
}
}
}
};
void killPeopleInRoom(room rooms[]) {
int n;
bool check = false;
cout << "Choose from which room you want to kill People " << endl;
cin >> n;
if (n > 0 || n <= 15) {
check = true;
}
while (check == false) {
cout << "Write n again " << endl;
cin >> n;
if (n > 0 || n <= 15) {
check = true;
}
}
for (int i = 0; i < rooms[n].familyName.size(); i++) {
rooms[n].familyName[i] = "empty";
}
};
| [
"daniel.czarnozynski@gmail.com"
] | daniel.czarnozynski@gmail.com |
a13bd874258357aa89c025a86a2e826dfd44bb92 | 54cd2cca6dea49b4f96f50b4a54db2673edff478 | /51CTO下载-钱能c++第二版源码/ch06/f0601.cpp | 2efb67613340bae54974318879d05d81103ac39c | [] | no_license | fashioning/Leetcode | 2b13dec74af05b184844da177c98249897204206 | 2a21c369afa3509806c748ac60867d3a0da70c94 | refs/heads/master | 2020-12-30T10:23:17.562412 | 2018-10-22T14:19:06 | 2018-10-22T14:19:06 | 40,231,848 | 0 | 0 | null | 2018-10-22T14:19:07 | 2015-08-05T07:40:24 | C++ | GB18030 | C++ | false | false | 671 | cpp | //=====================================
// f0601.cpp
// 频繁调用一个小函数
//=====================================
#include<iostream>
using namespace std;
//-------------------------------------
bool isnumber(char); // 函数声明
//-------------------------------------
int main(){
for(char c; cin>>c && c!='\n'; ) // 反复读入字符,若为回车便结束
if(isnumber(c)) // 调用一个小函数
cout<<"you entered a digit.\n";
else cout<<"you entered a non-digit.\n";
}//------------------------------------
bool isnumber(char ch){
return ch>='0' && ch<='9' ? 1 : 0;
}//====================================
| [
"fashioning@126.com"
] | fashioning@126.com |
0a0d617abf5e2af29a11c788bfb2e811b61b2dbc | f572dab4cb0145896a4e8e61b13941470689a112 | /PUCMM334.cpp | 6b826289a09c41d06809a0ff68c27e9182ecfdf0 | [] | no_license | ojusvini/Coding-Practice | e0e407bc3bade2026c28a11e3bfde9c5c9d1518a | 93f3f039aa1a11672e247b31299928b25f2ba109 | refs/heads/master | 2021-01-17T20:27:41.906143 | 2016-08-16T08:09:03 | 2016-08-16T08:09:03 | 65,799,962 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 878 | cpp | #include <stdio.h>
int main(){
int n,min,max,e,i,tc = 0;
scanf("%d",&n);
int a[n];
int h[100]={0};
min = 99999999;
max = -1;
e = 0;
for(i=0;i<n;i++){
scanf("%d",&a[i]);
if(a[i]>=n) e =1;
if(a[i]>max) max = a[i];
if(a[i]<min) min = a[i];
}
if(max-min>1) e = 1;
if(e==1) printf("-1\n");
else {
for(i=0;i<n;i++){
if(a[i]==max) h[i] = 0;
else if(a[i]==min) h[i] = 1;
else if(a[i]!=max&&a[i]!=min) {
e = 1;
break;
}
}
if(e==1) printf("-1\n");
else {
if(max==min && max == 0)
tc = 0;
else {
tc = 0;
for(i=0;i<n;i++){
if(h[i] == 1)tc++;
}
for(i=0;i<n;i++){
if(h[i]==1 && a[i] != tc-1){
e = 1;
break;
}
else if(h[i]==0 && a[i] != tc){
e = 1;
break;
}
}
}
if(e==1) printf("-1\n");
else printf("%d\n",tc);
}
}
return 0;
}
| [
"ojusviniagarwal95@gmail.com"
] | ojusviniagarwal95@gmail.com |
550ef455ff78127f163492acb800cf8a1aec2ec2 | 4ff43e75606c130dcccec8167fb7741c6ff510e7 | /code/ubuntu/RC2/um_acc/Legend code/src/eiquadprog.hpp | 6f7a25af41ab9bde30050ee7ce1970a49ebcaf6a | [] | no_license | getc1995/Scaled-Robot-Cars | 2b80ae65c7178ccc7f161556e4fa91e8cf71a6a9 | 2555bddf771a024d2fc1f55cc8a6f8960354705c | refs/heads/master | 2020-03-13T11:45:33.545684 | 2018-04-26T06:04:46 | 2018-04-26T06:04:46 | 131,097,677 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,066 | hpp | #ifndef _EIGEN_QUADSOLVE_HPP_
#define _EIGEN_QUADSOLVE_HPP_
/*
FILE eiquadprog.hh
NOTE: this is a modified of uQuadProg++ package, working with Eigen data structures.
uQuadProg++ is itself a port made by Angelo Furfaro of QuadProg++ originally developed by
Luca Di Gaspero, working with ublas data structures.
The quadprog_solve() function implements the algorithm of Goldfarb and Idnani
for the solution of a (convex) Quadratic Programming problem
by means of a dual method.
The problem is in the form:
min 0.5 * x G x + g0 x
s.t.
CE^T x + ce0 = 0
CI^T x + ci0 >= 0
The matrix and vectors dimensions are as follows:
G: n * n
g0: n
CE: n * p
ce0: p
CI: n * m
ci0: m
x: n
The function will return the cost of the solution written in the x vector or
std::numeric_limits::infinity() if the problem is infeasible. In the latter case
the value of the x vector is not correct.
References: D. Goldfarb, A. Idnani. A numerically stable dual method for solving
strictly convex quadratic programs. Mathematical Programming 27 (1983) pp. 1-33.
Notes:
1. pay attention in setting up the vectors ce0 and ci0.
If the constraints of your problem are specified in the form
A^T x = b and C^T x >= d, then you should set ce0 = -b and ci0 = -d.
2. The matrix G is modified within the function since it is used to compute
the G = L^T L cholesky factorization for further computations inside the function.
If you need the original matrix G you should make a copy of it and pass the copy
to the function.
The author will be grateful if the researchers using this software will
acknowledge the contribution of this modified function and of Di Gaspero's
original version in their research papers.
LICENSE
Copyright (2011) Benjamin Stephens
Copyright (2010) Gael Guennebaud
Copyright (2008) Angelo Furfaro
Copyright (2006) Luca Di Gaspero
This file is a porting of QuadProg++ routine, originally developed
by Luca Di Gaspero, exploiting uBlas data structures for vectors and
matrices instead of native C++ array.
uquadprog is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
uquadprog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with uquadprog; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Cholesky>
namespace Eigen {
// namespace internal {
template<typename Scalar>
inline Scalar distance(Scalar a, Scalar b)
{
Scalar a1, b1, t;
a1 = std::abs(a);
b1 = std::abs(b);
if (a1 > b1)
{
t = (b1 / a1);
return a1 * std::sqrt(1.0 + t * t);
}
else
if (b1 > a1)
{
t = (a1 / b1);
return b1 * std::sqrt(1.0 + t * t);
}
return a1 * std::sqrt(2.0);
}
// }
inline void compute_d(VectorXd &d, const MatrixXd& J, const VectorXd& np)
{
d = J.adjoint() * np;
}
inline void update_z(VectorXd& z, const MatrixXd& J, const VectorXd& d, int iq)
{
z = J.rightCols(z.size()-iq) * d.tail(d.size()-iq);
}
inline void update_r(const MatrixXd& R, VectorXd& r, const VectorXd& d, int iq)
{
r.head(iq)= R.topLeftCorner(iq,iq).triangularView<Upper>().solve(d.head(iq));
}
bool add_constraint(MatrixXd& R, MatrixXd& J, VectorXd& d, int& iq, double& R_norm);
void delete_constraint(MatrixXd& R, MatrixXd& J, VectorXi& A, VectorXd& u, int p, int& iq, int l);
/* solve_quadprog2 is used when the Cholesky decomposition of the G matrix is precomputed */
double solve_quadprog2(LLT<MatrixXd,Lower> &chol, double c1, VectorXd & g0,
const MatrixXd & CE, const VectorXd & ce0,
const MatrixXd & CI, const VectorXd & ci0,
VectorXd& x);
/* solve_quadprog is used for on-demand QP solving */
inline double solve_quadprog(MatrixXd & G, VectorXd & g0,
const MatrixXd & CE, const VectorXd & ce0,
const MatrixXd & CI, const VectorXd & ci0,
VectorXd& x){
LLT<MatrixXd,Lower> chol(G.cols());
double c1;
/* compute the trace of the original matrix G */
c1 = G.trace();
/* decompose the matrix G in the form LL^T */
chol.compute(G);
return solve_quadprog2(chol, c1, g0, CE, ce0, CI, ci0, x);
}
/* solve_quadprog2 is used for when the Cholesky decomposition of G is pre-computed */
inline double solve_quadprog2(LLT<MatrixXd,Lower> &chol, double c1, VectorXd & g0,
const MatrixXd & CE, const VectorXd & ce0,
const MatrixXd & CI, const VectorXd & ci0,
VectorXd& x)
{
int i, j, k, l; /* indices */
int ip, me, mi;
int n=g0.size();
int p=CE.cols();
int m=CI.cols();
MatrixXd R(g0.size(),g0.size()), J(g0.size(),g0.size());
VectorXd s(m+p), z(n), r(m + p), d(n), np(n), u(m + p);
VectorXd x_old(n), u_old(m + p);
double f_value, psi, c2, sum, ss, R_norm;
const double inf = std::numeric_limits<double>::infinity();
double t, t1, t2; /* t is the step length, which is the minimum of the partial step length t1
* and the full step length t2 */
VectorXi A(m + p), A_old(m + p), iai(m + p), iaexcl(m+p);
int q;
int iq, iter = 0;
me = p; /* number of equality constraints */
mi = m; /* number of inequality constraints */
q = 0; /* size of the active set A (containing the indices of the active constraints) */
/*
* Preprocessing phase
*/
/* initialize the matrix R */
d.setZero();
R.setZero();
R_norm = 1.0; /* this variable will hold the norm of the matrix R */
/* compute the inverse of the factorized matrix G^-1, this is the initial value for H */
// J = L^-T
J.setIdentity();
J = chol.matrixU().solve(J);
c2 = J.trace();
#ifdef TRACE_SOLVER
print_matrix("J", J, n);
#endif
/* c1 * c2 is an estimate for cond(G) */
/*
* Find the unconstrained minimizer of the quadratic form 0.5 * x G x + g0 x
* this is a feasible point in the dual space
* x = G^-1 * g0
*/
x = chol.solve(g0);
x = -x;
/* and compute the current solution value */
f_value = 0.5 * g0.dot(x);
#ifdef TRACE_SOLVER
std::cerr << "Unconstrained solution: " << f_value << std::endl;
print_vector("x", x, n);
#endif
/* Add equality constraints to the working set A */
iq = 0;
for (i = 0; i < me; i++)
{
np = CE.col(i);
compute_d(d, J, np);
update_z(z, J, d, iq);
update_r(R, r, d, iq);
#ifdef TRACE_SOLVER
print_matrix("R", R, iq);
print_vector("z", z, n);
print_vector("r", r, iq);
print_vector("d", d, n);
#endif
/* compute full step length t2: i.e., the minimum step in primal space s.t. the contraint
becomes feasible */
t2 = 0.0;
if (std::abs(z.dot(z)) > std::numeric_limits<double>::epsilon()) // i.e. z != 0
t2 = (-np.dot(x) - ce0(i)) / z.dot(np);
x += t2 * z;
/* set u = u+ */
u(iq) = t2;
u.head(iq) -= t2 * r.head(iq);
/* compute the new solution value */
f_value += 0.5 * (t2 * t2) * z.dot(np);
A(i) = -i - 1;
if (!add_constraint(R, J, d, iq, R_norm))
{
// FIXME: it should raise an error
// Equality constraints are linearly dependent
return f_value;
}
}
/* set iai = K \ A */
for (i = 0; i < mi; i++)
iai(i) = i;
l1: iter++;
#ifdef TRACE_SOLVER
print_vector("x", x, n);
#endif
/* step 1: choose a violated constraint */
for (i = me; i < iq; i++)
{
ip = A(i);
iai(ip) = -1;
}
/* compute s(x) = ci^T * x + ci0 for all elements of K \ A */
ss = 0.0;
psi = 0.0; /* this value will contain the sum of all infeasibilities */
ip = 0; /* ip will be the index of the chosen violated constraint */
for (i = 0; i < mi; i++)
{
iaexcl(i) = 1;
sum = CI.col(i).dot(x) + ci0(i);
s(i) = sum;
psi += std::min(0.0, sum);
}
#ifdef TRACE_SOLVER
print_vector("s", s, mi);
#endif
if (std::abs(psi) <= mi * std::numeric_limits<double>::epsilon() * c1 * c2* 100.0)
{
/* numerically there are not infeasibilities anymore */
q = iq;
return f_value;
}
/* save old values for u, x and A */
u_old.head(iq) = u.head(iq);
A_old.head(iq) = A.head(iq);
x_old = x;
l2: /* Step 2: check for feasibility and determine a new S-pair */
for (i = 0; i < mi; i++)
{
if (s(i) < ss && iai(i) != -1 && iaexcl(i))
{
ss = s(i);
ip = i;
}
}
if (ss >= 0.0)
{
q = iq;
return f_value;
}
/* set np = n(ip) */
np = CI.col(ip);
/* set u = (u 0)^T */
u(iq) = 0.0;
/* add ip to the active set A */
A(iq) = ip;
#ifdef TRACE_SOLVER
std::cerr << "Trying with constraint " << ip << std::endl;
print_vector("np", np, n);
#endif
l2a:/* Step 2a: determine step direction */
/* compute z = H np: the step direction in the primal space (through J, see the paper) */
compute_d(d, J, np);
update_z(z, J, d, iq);
/* compute N* np (if q > 0): the negative of the step direction in the dual space */
update_r(R, r, d, iq);
#ifdef TRACE_SOLVER
std::cerr << "Step direction z" << std::endl;
print_vector("z", z, n);
print_vector("r", r, iq + 1);
print_vector("u", u, iq + 1);
print_vector("d", d, n);
print_ivector("A", A, iq + 1);
#endif
/* Step 2b: compute step length */
l = 0;
/* Compute t1: partial step length (maximum step in dual space without violating dual feasibility */
t1 = inf; /* +inf */
/* find the index l s.t. it reaches the minimum of u+(x) / r */
for (k = me; k < iq; k++)
{
double tmp;
if (r(k) > 0.0 && ((tmp = u(k) / r(k)) < t1) )
{
t1 = tmp;
l = A(k);
}
}
/* Compute t2: full step length (minimum step in primal space such that the constraint ip becomes feasible */
if (std::abs(z.dot(z)) > std::numeric_limits<double>::epsilon()) // i.e. z != 0
t2 = -s(ip) / z.dot(np);
else
t2 = inf; /* +inf */
/* the step is chosen as the minimum of t1 and t2 */
t = std::min(t1, t2);
#ifdef TRACE_SOLVER
std::cerr << "Step sizes: " << t << " (t1 = " << t1 << ", t2 = " << t2 << ") ";
#endif
/* Step 2c: determine new S-pair and take step: */
/* case (i): no step in primal or dual space */
if (t >= inf)
{
/* QPP is infeasible */
// FIXME: unbounded to raise
q = iq;
return inf;
}
/* case (ii): step in dual space */
if (t2 >= inf)
{
/* set u = u + t * [-r 1) and drop constraint l from the active set A */
u.head(iq) -= t * r.head(iq);
u(iq) += t;
iai(l) = l;
delete_constraint(R, J, A, u, p, iq, l);
#ifdef TRACE_SOLVER
std::cerr << " in dual space: "
<< f_value << std::endl;
print_vector("x", x, n);
print_vector("z", z, n);
print_ivector("A", A, iq + 1);
#endif
goto l2a;
}
/* case (iii): step in primal and dual space */
x += t * z;
/* update the solution value */
f_value += t * z.dot(np) * (0.5 * t + u(iq));
u.head(iq) -= t * r.head(iq);
u(iq) += t;
#ifdef TRACE_SOLVER
std::cerr << " in both spaces: "
<< f_value << std::endl;
print_vector("x", x, n);
print_vector("u", u, iq + 1);
print_vector("r", r, iq + 1);
print_ivector("A", A, iq + 1);
#endif
if (t == t2)
{
#ifdef TRACE_SOLVER
std::cerr << "Full step has taken " << t << std::endl;
print_vector("x", x, n);
#endif
/* full step has taken */
/* add constraint ip to the active set*/
if (!add_constraint(R, J, d, iq, R_norm))
{
iaexcl(ip) = 0;
delete_constraint(R, J, A, u, p, iq, ip);
#ifdef TRACE_SOLVER
print_matrix("R", R, n);
print_ivector("A", A, iq);
#endif
for (i = 0; i < m; i++)
iai(i) = i;
for (i = 0; i < iq; i++)
{
A(i) = A_old(i);
iai(A(i)) = -1;
u(i) = u_old(i);
}
x = x_old;
goto l2; /* go to step 2 */
}
else
iai(ip) = -1;
#ifdef TRACE_SOLVER
print_matrix("R", R, n);
print_ivector("A", A, iq);
#endif
goto l1;
}
/* a patial step has taken */
#ifdef TRACE_SOLVER
std::cerr << "Partial step has taken " << t << std::endl;
print_vector("x", x, n);
#endif
/* drop constraint l */
iai(l) = l;
delete_constraint(R, J, A, u, p, iq, l);
#ifdef TRACE_SOLVER
print_matrix("R", R, n);
print_ivector("A", A, iq);
#endif
s(ip) = CI.col(ip).dot(x) + ci0(ip);
#ifdef TRACE_SOLVER
print_vector("s", s, mi);
#endif
goto l2a;
}
inline bool add_constraint(MatrixXd& R, MatrixXd& J, VectorXd& d, int& iq, double& R_norm)
{
int n=J.rows();
#ifdef TRACE_SOLVER
std::cerr << "Add constraint " << iq << '/';
#endif
int i, j, k;
double cc, ss, h, t1, t2, xny;
/* we have to find the Givens rotation which will reduce the element
d(j) to zero.
if it is already zero we don't have to do anything, except of
decreasing j */
for (j = n - 1; j >= iq + 1; j--)
{
/* The Givens rotation is done with the matrix (cc cs, cs -cc).
If cc is one, then element (j) of d is zero compared with element
(j - 1). Hence we don't have to do anything.
If cc is zero, then we just have to switch column (j) and column (j - 1)
of J. Since we only switch columns in J, we have to be careful how we
update d depending on the sign of gs.
Otherwise we have to apply the Givens rotation to these columns.
The i - 1 element of d has to be updated to h. */
cc = d(j - 1);
ss = d(j);
h = distance(cc, ss);
if (h == 0.0)
continue;
d(j) = 0.0;
ss = ss / h;
cc = cc / h;
if (cc < 0.0)
{
cc = -cc;
ss = -ss;
d(j - 1) = -h;
}
else
d(j - 1) = h;
xny = ss / (1.0 + cc);
for (k = 0; k < n; k++)
{
t1 = J(k,j - 1);
t2 = J(k,j);
J(k,j - 1) = t1 * cc + t2 * ss;
J(k,j) = xny * (t1 + J(k,j - 1)) - t2;
}
}
/* update the number of constraints added*/
iq++;
/* To update R we have to put the iq components of the d vector
into column iq - 1 of R
*/
R.col(iq-1).head(iq) = d.head(iq);
#ifdef TRACE_SOLVER
std::cerr << iq << std::endl;
#endif
if (std::abs(d(iq - 1)) <= std::numeric_limits<double>::epsilon() * R_norm)
// problem degenerate
return false;
R_norm = std::max<double>(R_norm, std::abs(d(iq - 1)));
return true;
}
inline void delete_constraint(MatrixXd& R, MatrixXd& J, VectorXi& A, VectorXd& u, int p, int& iq, int l)
{
int n = R.rows();
#ifdef TRACE_SOLVER
std::cerr << "Delete constraint " << l << ' ' << iq;
#endif
int i, j, k, qq;
double cc, ss, h, xny, t1, t2;
/* Find the index qq for active constraint l to be removed */
for (i = p; i < iq; i++)
if (A(i) == l)
{
qq = i;
break;
}
/* remove the constraint from the active set and the duals */
for (i = qq; i < iq - 1; i++)
{
A(i) = A(i + 1);
u(i) = u(i + 1);
R.col(i) = R.col(i+1);
}
A(iq - 1) = A(iq);
u(iq - 1) = u(iq);
A(iq) = 0;
u(iq) = 0.0;
for (j = 0; j < iq; j++)
R(j,iq - 1) = 0.0;
/* constraint has been fully removed */
iq--;
#ifdef TRACE_SOLVER
std::cerr << '/' << iq << std::endl;
#endif
if (iq == 0)
return;
for (j = qq; j < iq; j++)
{
cc = R(j,j);
ss = R(j + 1,j);
h = distance(cc, ss);
if (h == 0.0)
continue;
cc = cc / h;
ss = ss / h;
R(j + 1,j) = 0.0;
if (cc < 0.0)
{
R(j,j) = -h;
cc = -cc;
ss = -ss;
}
else
R(j,j) = h;
xny = ss / (1.0 + cc);
for (k = j + 1; k < iq; k++)
{
t1 = R(j,k);
t2 = R(j + 1,k);
R(j,k) = t1 * cc + t2 * ss;
R(j + 1,k) = xny * (t1 + R(j,k)) - t2;
}
for (k = 0; k < n; k++)
{
t1 = J(k,j);
t2 = J(k,j + 1);
J(k,j) = t1 * cc + t2 * ss;
J(k,j + 1) = xny * (J(k,j) + t1) - t2;
}
}
}
}
#endif
| [
"gtcheng@umich.edu"
] | gtcheng@umich.edu |
2cfb0d8610307e40ad85092d2dcd5b596aa4ff69 | e3ff26ae10b753758e3086ddd19e497fd868b768 | /U201514559/U201514559_1/U201514559_1.cpp | a7485de509981b65e357882a033da261e9c05032 | [] | no_license | zhou-mh/CPP_LAB | 1acd03f20e00e36d19a09ae5f7a8f27b312d2e6a | 9cdca0554e61e517efaff5ab082e80de977990a2 | refs/heads/master | 2021-08-24T06:10:45.703204 | 2017-12-08T10:28:09 | 2017-12-08T10:28:09 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,962 | cpp | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct STACK {
int *elems; //申请内存用于存放栈的元素
int max; //栈能存放的最大元素个数
int pos; //栈实际已有元素个数,栈空时pos=0;
};
void initSTACK(STACK *const p, int m); //初始化p指向的栈:最多m个元素
void initSTACK(STACK *const p, const STACK&s); //用栈s初始化p指向的栈
int size(const STACK *const p); //返回p指向的栈的最大元素个数max
int howMany(const STACK *const p); //返回p指向的栈的实际元素个数pos
int getelem(const STACK *const p, int x); //取下标x处的栈元素
STACK *const push(STACK *const p, int e); //将e入栈,并返回p
STACK *const pop(STACK *const p, int &e); //出栈到e,并返回p
STACK *const assign(STACK*const p, const STACK&s); //赋s给p指的栈,并返回p
void print(const STACK*const p); //打印p指向的栈
void destroySTACK(STACK*const p); //销毁p指向的栈
void PrintToFile(const STACK*const p, ofstream &MyFile,int fin_flag, int x);//打印p指向的栈,并输出到文件
void initSTACK(STACK *const p, int m)//构造函数
{
if (p == NULL)
{
return;
}
if (m > 0)//确认有空间分配
{
p->elems = (int*)malloc(sizeof(int)*m);
p->max = m;
p->pos = 0;
}
return;
}
void initSTACK(STACK *const p, const STACK&s) //用栈s初始化p指向的栈
{
p->elems = (int*)malloc((s.max) * sizeof(int));
for (int i = 0; i<(s.pos); i++)
{
p->elems[i] = s.elems[i];
}
p->pos = s.pos;
p->max = s.max;
}
int size(const STACK *const p) //返回p指向的栈的最大元素个数max
{
return p->max;
}
int howMany(const STACK *const p) //返回p指向的栈的实际元素个数pos
{
return p->pos;
}
int getelem(const STACK *const p, int x) //取下标x处的栈元素
{
if (x <= p->pos)
return p->elems[x];
else
return -1984;
}
STACK *const push(STACK *const p, int e)//入栈函数
{
if ((p->pos) < (p->max))//判断当前栈空间大小是否足够
{
p->elems[p->pos] = e;
(p->pos)++;
return p;
}
else
{
return NULL;
}
}
STACK *const pop(STACK *const p, int &e) //出栈函数
{
if ((p->pos) == 0)
{
return NULL;
}
else
{
e = p->elems[(p->pos) - 1];//把栈顶元素出栈到e
(p->elems[(p->pos) - 1]) = 0;
(p->pos)--;
return p;
}
}
STACK *const assign(STACK*const p, const STACK&s) //赋s给p指的栈, 并返回p
{
p->max = s.max;
free(p->elems);
p->elems = NULL;
p->elems = (int*)malloc((s.max) * sizeof(int));
for (int i = 0; i < (s.pos); i++)
{
p->elems[i] = s.elems[i];
}
p->pos = s.pos;
return p;
}
void print(const STACK*const p)//打印p指向的栈,并输出到文件
{
for (int i = 0; i < p->pos; i++)
{
cout<< " " << getelem(p, i);
}
}
void PrintToFile(const STACK*const p, ofstream &MyFile, int fin_flag,int x)//打印p指向的栈,并输出到文件
{
if (fin_flag <5)//完成的操作为1-5
{
for (int i = 0; i < p->pos; i++)
{
cout<< " " << getelem(p, i);
MyFile << " " << getelem(p, i);
}
}
if (fin_flag == 5)
{
cout << " " << howMany(p);
MyFile << " " << howMany(p);
}
if (fin_flag == 6)
{
cout << " " << getelem(p, x);
MyFile << " " << getelem(p, x);
}
}
void destroySTACK(STACK*const p)//析构函数
{
if(p->elems!=NULL && p->max > 0)
free(p->elems);
p->max = 0;
p->pos = 0;
return;
}
int main(int argc, char* argv[])
{
int x = 0;//栈元素下标
int size_1 = 0;
int size_2 = 0;
int opt_flag = 0;//操作开始标志
int push_e = 0;//入栈元素
int pop_e = 0;//出栈元素
int pop_num = 0;//出栈元素个数
STACK *stack1 = NULL;
STACK *stack2 = NULL;
STACK *stack3 = NULL;
stack1 = (STACK *)malloc(sizeof(STACK));//给s分配内存
stack2 = (STACK *)malloc(sizeof(STACK));//给s分配内存
stack3 = (STACK *)malloc(sizeof(STACK));//中间操作
ofstream MyFile("U201514559_1.txt");//新建一个对应文件名的文本文档
//判断是否设定栈或队列大小,-S
if ((strcmp("-S", argv[1]) == 0) || (strcmp("-s", argv[1]) == 0))
{
//正确输入-S后
//判断是否输入了栈和队列大小
cout << "S";
MyFile << "S";//在文件中写入S操作
if (argv[2] == NULL)
{
//cout << "未输入栈队或队列大小!" << endl;
return -3;
}
sscanf(argv[2], "%d", &size_1);//获取命令行参数
initSTACK(stack1, size_1);//调用构造函数
cout << " " << size_1;//返回max
MyFile << " " << size_1;//在文件中写入 返回栈的最大元素max
//循环判定操作
for (int i = 3; i < argc; i++)
{
//检测到操作符
if ((strcmp("-I", argv[i]) == 0) || (strcmp("-i", argv[i]) == 0))
{
PrintToFile(stack1, MyFile, opt_flag, x);//操作完成后调用
opt_flag = 1;
cout << " " << "I";
MyFile << " " << "I";//在文件中写入I
continue;
}
if ((strcmp("-O", argv[i]) == 0) || (strcmp("-o", argv[i]) == 0))
{
PrintToFile(stack1, MyFile, opt_flag, x);//操作完成后调用
opt_flag = 2;
cout << " " << "O";
MyFile << " " << "O";//在文件中写入O
continue;
}
if ((strcmp("-C", argv[i]) == 0) || (strcmp("-c", argv[i]) == 0))
{
PrintToFile(stack1, MyFile, opt_flag, x);//操作完成后调用
opt_flag = 3;
cout << " " << "C";
MyFile << " " << "C";//在文件中写入C
//不需要输入参数,直接调用拷贝构造函数
initSTACK(stack2, *stack1);
assign(stack1, *stack2);//把新栈赋值给旧栈,以后操作新栈
continue;
};
if ((strcmp("-A", argv[i]) == 0) || (strcmp("-a", argv[i]) == 0))
{
PrintToFile(stack1, MyFile, opt_flag, x);//操作完成后调用
opt_flag = 4;
cout << " " << "A";
MyFile << " " << "A";//在文件中写入A
continue;
}
if ((strcmp("-N", argv[i]) == 0) || (strcmp("-n", argv[i]) == 0))
{
PrintToFile(stack1, MyFile, opt_flag, x);//操作完成后调用
opt_flag = 5;
cout << " " << "N";
MyFile << " " << "N";//在文件中写入N
continue;
}
if ((strcmp("-G", argv[i]) == 0) || (strcmp("-g", argv[i]) == 0))
{
PrintToFile(stack1, MyFile, opt_flag, x);//操作完成后调用
opt_flag = 6;
cout << " " << "G";
MyFile << " " << "G";//在文件中写入G
continue;
}
switch (opt_flag)
{
case 0:
{
break;
}
case 1://入栈
{
sscanf(argv[i], "%d", &push_e);
if (NULL== push(stack1, push_e))//判断入栈结果返回值
{
cout << " " << "E";
MyFile << " " << "E";
return -1;
}
break;
}
case 2://出栈
{
sscanf(argv[i], "%d", &pop_num);
for (int j = 0; j < pop_num; j++)
{
if (NULL == pop(stack1, pop_e))//调用出栈函数
{
cout << " " << "E";
MyFile << " " << "E";
return -2;
}
//cout << pop_e << "成功出栈!" << endl;
}
break;
}
case 3://深拷贝构造
{
//无参数输入
break;
}
case 4://深拷贝赋值
{
sscanf(argv[i], "%d", &size_2);
initSTACK(stack3,size_2);//new
assign(stack3, *stack1);//assign
assign(stack1, *stack3);//把新栈赋值给旧栈,以后操作新栈
break;
}
case 5://剩余元素个数
{
//无参数输入
break;
}
case 6://获得下标为x的元素
{
sscanf(argv[i], "%d", &x);
if (-1984 == getelem(stack1, x))
{
cout << " " << "E";
MyFile << " " << "E";
return -3;
}
break;
}
default:
break;
}
}
PrintToFile(stack1, MyFile, opt_flag, x);//命令结束后后调用
}
else
{
//cout << "未设定栈队或队列大小!" << endl;
return -2;
}
MyFile.close();//关闭文件
destroySTACK(stack1);//调用析构函数
//destroySTACK(stack2);//调用析构函数
//destroySTACK(stack3);//调用析构函数
stack1 = NULL;
stack2 = NULL;
stack3 = NULL;
return 0;
}
| [
"630212894@qq.com"
] | 630212894@qq.com |
dbb39946b37b3a356c2b48b4a6876194b7bcc3e1 | 315be1ae38a996c59a9876606c4977ccc4346bfd | /Ter1d/Function.cpp | a5536678d34033661eb2c40b1004ca479218851a | [] | no_license | Coco6333/Ter1d | 3331f13165d0443e001e23ab996ef73f26791818 | 34935ec01fd6af13fbe728f54a5b4b11815ff1fb | refs/heads/main | 2023-04-04T15:57:12.166504 | 2021-04-21T08:58:21 | 2021-04-21T08:58:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,007 | cpp | #include "Function.h"
#include <cmath>
using namespace std;
using namespace Eigen;
Function::Function(DataFile* data_file) :
_df(data_file), _g(_df->Get_g())
{
}
double Function::Initial_condition_forH(double x, double y)
{
if (_df->Get_mesh_name()=="Mesh1D")
{
if (_df->Get_scenario() == "Barreer")
{
if (x<(_df->Get_xmax()+_df->Get_xmin())/2.0)
{
return 2.;
}
else
{
return 1.;
}
}
else
{
cout << "Choose an implanted scenario." << endl;
exit(0);
}
}
else if (_df->Get_mesh_name()=="Mesh2D")
{
if (_df->Get_scenario() == "Barreer")
{
if (x<(_df->Get_xmax()+_df->Get_xmin())/2.0)
{
return 2.;
}
else
{
return 1.;
}
}
else
{
cout << "Choose an implanted scenario." << endl;
exit(0);
}
}
else
{
cout << "Choose an implanted mesh, we can't initialize H" << endl;
exit(0);
}
}
double Function::Initial_condition_forU(double x, double y)
{
if (_df->Get_mesh_name()=="Mesh1D")
{
if (_df->Get_scenario() == "Barreer")
{
return 0;
}
else
{
cout << "Choose an implanted scenario." << endl;
exit(0);
}
}
else if (_df->Get_mesh_name()=="Mesh2D")
{
if (_df->Get_scenario() == "Barreer")
{
return 0;
}
else
{
cout << "Choose an implanted scenario." << endl;
exit(0);
}
}
else
{
cout << "Choose an implanted mesh, we can't initialize U" << endl;
exit(0);
}
}
double Function::Source_term(double x, double y,double t)
{
if (_df->Get_mesh_name()=="Mesh1D")
{
if (_df->Get_scenario() == "Barreer")
{
return 0;
}
else
{
cout << "Choose an implanted scenario." << endl;
exit(0);
}
}
else if (_df->Get_mesh_name()=="Mesh2D")
{
if (_df->Get_scenario() == "Barreer")
{
return 0;
}
else
{
cout << "Choose an implanted scenario." << endl;
exit(0);
}
}
else
{
cout << "Choose an implanted mesh, we can't calculate S" << endl;
exit(0);
}
}
double Function::maxdeB(MatrixXd B)
{
double max=0;
for (int i=0; i< B.rows() ; i++)
{
for (int j=0;j<B.cols();++j)
{
if (B(i,j) > max)
max = B(i,j);
}
}
return max;
}
VectorXd Function::phi(VectorXd theta)
{
VectorXd res(2);
res(0)=(theta(0)+abs(theta(0)))/(1+theta(0));
res(1)=(theta(1)+abs(theta(1)))/(1+theta(1));
return res;
}
double Function::Produit_Scalaire(VectorXd U,VectorXd V)
{
double res=0;
if (U.rows()!=V.rows())
{
cout << "U et V ne sont pas de la même taille abruti !!" << endl;
exit(0);
}
else
{
for (int i =0; i<U.rows();++i)
{
res+=U(i)*V(i);
}
}
return res;
}
| [
"noreply@github.com"
] | noreply@github.com |
6ac391de279bf21115ce73dc768c87d22159dbc5 | 4250259ae7252286646dbc5dafbb56c1bdf78218 | /ThirdUpload/date.h | 4868338f98788f62074b95b799132f8951c06e0c | [] | no_license | ywang208/cs-8-first-project | 1a41252860f4690b35ba3812d7ad4d4004746236 | af69336b061089db56a603049ee193bc6800b6a2 | refs/heads/master | 2021-07-08T12:26:54.446164 | 2017-10-07T05:14:26 | 2017-10-07T05:14:26 | 103,898,806 | 2 | 0 | null | 2017-09-27T06:52:13 | 2017-09-18T06:04:08 | null | UTF-8 | C++ | false | false | 80 | h | #ifndef DATE_H
#define DATE_H
#include <iostream>
class Date
#endif // DATE_H
| [
"noreply@github.com"
] | noreply@github.com |
13f25edf87fd64706e980c2d0e0cf9f4fb44ef7f | 7cce0635a50e8d2db92b7b1bf4ad49fc218fb0b8 | /Visual C++2005入门经典学习/Visual C++2005入门经典学习例程/Ex1/Ex1_04/Ex1_04Doc.h | 397582cfc9a400e906e149c4cb3ac86a8c544ff5 | [] | no_license | liquanhai/cxm-hitech-matrix428 | dcebcacea58123aabcd9541704b42b3491444220 | d06042a3de79379a77b0e4e276de42de3c1c6d23 | refs/heads/master | 2021-01-20T12:06:23.622153 | 2013-01-24T01:05:10 | 2013-01-24T01:05:10 | 54,619,320 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 616 | h | // Ex1_04Doc.h : interface of the CEx1_04Doc class
//
#pragma once
class CEx1_04Doc : public CDocument
{
protected: // create from serialization only
CEx1_04Doc();
DECLARE_DYNCREATE(CEx1_04Doc)
// Attributes
public:
// Operations
public:
// Overrides
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
// Implementation
public:
virtual ~CEx1_04Doc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
DECLARE_MESSAGE_MAP()
};
| [
"chengxianming1981@gmail.com"
] | chengxianming1981@gmail.com |
36ce53cfe39031c68ce8bc9aa63a0022c98dfa64 | e80ae28057ef89da3082df24443756f5ddd2e157 | /boj_10871.cpp | aa980095c3fadee913c168146fc0e347c49fab54 | [] | no_license | HyeongDo/Algorithm | c91af8e3821320e4b804cf372e5305e1c0d4b9af | 341bd430fd705b60639a3df083eb00d6f5d19d82 | refs/heads/master | 2020-06-18T03:31:06.280866 | 2020-05-16T07:26:55 | 2020-05-16T07:26:55 | 196,148,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 557 | cpp | #include<iostream>
using namespace std;
int n,m[11][11],MIN=10000000;
bool ck[11];
void dfs(int s,int e,int cnt,int sum){
if(cnt==n&&s==e){
MIN=min(MIN,sum);
return;
}
for(int i=0;i<n;i++){
if(m[e][i]==0) continue;
if(ck[e]==false && m[e][i]>0){
ck[e]=true;
sum+=m[e][i];
if(sum<=MIN){
dfs(s,i,cnt+1,sum);
}
ck[e]=false;
sum-=m[e][i];
}
}
}
int main(void){
cin>>n;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>m[i][j];
}
}
for(int i=0;i<n;i++){
dfs(i,i,0,0);
}
cout<<MIN;
return 0;
}
| [
"gudeh8080"
] | gudeh8080 |
b7ee3df9cd989a8e20a094a548f23e735683d5fc | 193a74cc76bf1bc990ce7a3bf5fb0638236d9912 | /test/core/promise/promise_factory_test.cc | 47d8a3a855bc07bf7d0bbdb120e5d1c6ff82fa9b | [
"Apache-2.0",
"BSD-3-Clause",
"MPL-2.0"
] | permissive | jtattermusch/grpc | 899a0ab7fbc5987c37a4ffd13698b7540887343b | e5f7b1b8cd5666dfc4038daefb7d683ee1171856 | refs/heads/master | 2023-08-31T05:56:04.075028 | 2022-10-28T05:25:17 | 2022-10-28T05:25:17 | 31,382,470 | 4 | 2 | Apache-2.0 | 2023-08-22T12:51:41 | 2015-02-26T18:39:52 | C++ | UTF-8 | C++ | false | false | 2,186 | cc | // Copyright 2021 gRPC authors.
//
// 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 "src/core/lib/promise/detail/promise_factory.h"
#include <functional>
#include "absl/functional/bind_front.h"
#include "absl/types/variant.h"
#include "gtest/gtest.h"
#include "src/core/lib/promise/poll.h"
#include "src/core/lib/promise/promise.h"
namespace grpc_core {
namespace promise_detail {
namespace testing {
template <typename Arg, typename F>
auto MakeOnceFactory(F f) {
return OncePromiseFactory<Arg, F>(std::move(f));
}
template <typename Arg, typename F>
auto MakeRepeatedFactory(F f) {
return RepeatedPromiseFactory<Arg, F>(std::move(f));
}
TEST(AdaptorTest, FactoryFromPromise) {
EXPECT_EQ(
MakeOnceFactory<void>([]() { return Poll<int>(Poll<int>(42)); }).Make()(),
Poll<int>(42));
EXPECT_EQ(MakeRepeatedFactory<void>([]() {
return Poll<int>(Poll<int>(42));
}).Make()(),
Poll<int>(42));
EXPECT_EQ(MakeOnceFactory<void>(Promise<int>([]() {
return Poll<int>(Poll<int>(42));
})).Make()(),
Poll<int>(42));
EXPECT_EQ(MakeRepeatedFactory<void>(Promise<int>([]() {
return Poll<int>(Poll<int>(42));
})).Make()(),
Poll<int>(42));
}
TEST(AdaptorTest, FactoryFromBindFrontPromise) {
EXPECT_EQ(MakeOnceFactory<void>(
absl::bind_front([](int i) { return Poll<int>(i); }, 42))
.Make()(),
Poll<int>(42));
}
} // namespace testing
} // namespace promise_detail
} // namespace grpc_core
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| [
"noreply@github.com"
] | noreply@github.com |
b23be7e5127aec1d4050e46bd12590b3c6a671b6 | 92f902439bc208acf5510a2676ed0556e9a45bd0 | /cmtp/capi.cc | 146ca9de0a8cadffb3151e2c8f2427e16828a331 | [] | no_license | mahashg/bluetooth_object_oriented_driver | a3fa075ff711b053ab2d980dd6bdda9d2359460a | 0251ad11e1e8e2c9464abffb6fc049dea10b1981 | refs/heads/master | 2021-06-09T12:32:30.837879 | 2016-12-15T08:12:12 | 2016-12-15T08:12:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,931 | cc | /*
CMTP implementation for Linux Bluetooth stack (BlueZ).
Copyright (C) 2002-2003 Marcel Holtmann <marcel@holtmann.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
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 OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
#include "capi.h"
struct cmtp_application* CMTP_CAPI::cmtp_application_add(struct cmtp_session *session, __u16 appl)
{
struct cmtp_application *app = kzalloc(sizeof(*app), GFP_KERNEL);
BT_DBG("session %p application %p appl %d", session, app, appl);
if (!app)
return NULL;
app->state = BT_OPEN;
app->appl = appl;
list_add_tail(&app->list, &session->applications);
return app;
}
void CMTP_CAPI::cmtp_application_del(struct cmtp_session *session, struct cmtp_application *app)
{
BT_DBG("session %p application %p", session, app);
if (app) {
list_del(&app->list);
kfree(app);
}
}
struct cmtp_application* CMTP_CAPI::cmtp_application_get(struct cmtp_session *session, int pattern, __u16 value)
{
struct cmtp_application *app;
struct list_head *p, *n;
list_for_each_safe(p, n, &session->applications) {
app = list_entry(p, struct cmtp_application, list);
switch (pattern) {
case CMTP_MSGNUM:
if (app->msgnum == value)
return app;
break;
case CMTP_APPLID:
if (app->appl == value)
return app;
break;
case CMTP_MAPPING:
if (app->mapping == value)
return app;
break;
}
}
return NULL;
}
int CMTP_CAPI::cmtp_msgnum_get(struct cmtp_session *session)
{
session->msgnum++;
if ((session->msgnum & 0xff) > 200)
session->msgnum = CMTP_INITIAL_MSGNUM + 1;
return session->msgnum;
}
void CMTP_CAPI::cmtp_send_capimsg(struct cmtp_session *session, struct sk_buff *skb)
{
struct cmtp_scb *scb = (struct cmtp_scb *) skb->cb;
BT_DBG("session %p skb %p len %d", session, skb, skb->len);
scb->id = -1;
scb->data = (CAPIMSG_COMMAND(skb->data) == CAPI_DATA_B3);
skb_queue_tail(&session->transmit, skb);
wake_up_interruptible(sk_sleep(session->sock->sk));
}
CMTP_CAPI::cmtp_send_interopmsg(struct cmtp_session *session,
__u8 subcmd, __u16 appl, __u16 msgnum,
__u16 function, unsigned char *buf, int len)
{
struct sk_buff *skb;
unsigned char *s;
BT_DBG("session %p subcmd 0x%02x appl %d msgnum %d", session, subcmd, appl, msgnum);
skb = alloc_skb(CAPI_MSG_BASELEN + 6 + len, GFP_ATOMIC);
if (!skb) {
BT_ERR("Can't allocate memory for interoperability packet");
return;
}
s = skb_put(skb, CAPI_MSG_BASELEN + 6 + len);
capimsg_setu16(s, 0, CAPI_MSG_BASELEN + 6 + len);
capimsg_setu16(s, 2, appl);
capimsg_setu8 (s, 4, CAPI_INTEROPERABILITY);
capimsg_setu8 (s, 5, subcmd);
capimsg_setu16(s, 6, msgnum);
/* Interoperability selector (Bluetooth Device Management) */
capimsg_setu16(s, 8, 0x0001);
capimsg_setu8 (s, 10, 3 + len);
capimsg_setu16(s, 11, function);
capimsg_setu8 (s, 13, len);
if (len > 0)
memcpy(s + 14, buf, len);
cmtp_send_capimsg(session, skb);
}
void CMTP_CAPI::cmtp_recv_interopmsg(struct cmtp_session *session, struct sk_buff *skb)
{
struct capi_ctr *ctrl = &session->ctrl;
struct cmtp_application *application;
__u16 appl, msgnum, func, info;
__u32 controller;
BT_DBG("session %p skb %p len %d", session, skb, skb->len);
switch (CAPIMSG_SUBCOMMAND(skb->data)) {
case CAPI_CONF:
if (skb->len < CAPI_MSG_BASELEN + 10)
break;
func = CAPIMSG_U16(skb->data, CAPI_MSG_BASELEN + 5);
info = CAPIMSG_U16(skb->data, CAPI_MSG_BASELEN + 8);
switch (func) {
case CAPI_FUNCTION_REGISTER:
msgnum = CAPIMSG_MSGID(skb->data);
application = cmtp_application_get(session, CMTP_MSGNUM, msgnum);
if (application) {
application->state = BT_CONNECTED;
application->msgnum = 0;
application->mapping = CAPIMSG_APPID(skb->data);
wake_up_interruptible(&session->wait);
}
break;
case CAPI_FUNCTION_RELEASE:
appl = CAPIMSG_APPID(skb->data);
application = cmtp_application_get(session, CMTP_MAPPING, appl);
if (application) {
application->state = BT_CLOSED;
application->msgnum = 0;
wake_up_interruptible(&session->wait);
}
break;
case CAPI_FUNCTION_GET_PROFILE:
if (skb->len < CAPI_MSG_BASELEN + 11 + sizeof(capi_profile))
break;
controller = CAPIMSG_U16(skb->data, CAPI_MSG_BASELEN + 11);
msgnum = CAPIMSG_MSGID(skb->data);
if (!info && (msgnum == CMTP_INITIAL_MSGNUM)) {
session->ncontroller = controller;
wake_up_interruptible(&session->wait);
break;
}
if (!info && ctrl) {
memcpy(&ctrl->profile,
skb->data + CAPI_MSG_BASELEN + 11,
sizeof(capi_profile));
session->state = BT_CONNECTED;
capi_ctr_ready(ctrl);
}
break;
case CAPI_FUNCTION_GET_MANUFACTURER:
if (skb->len < CAPI_MSG_BASELEN + 15)
break;
controller = CAPIMSG_U32(skb->data, CAPI_MSG_BASELEN + 10);
if (!info && ctrl) {
int len = min_t(uint, CAPI_MANUFACTURER_LEN,
skb->data[CAPI_MSG_BASELEN + 14]);
memset(ctrl->manu, 0, CAPI_MANUFACTURER_LEN);
strncpy(ctrl->manu,
skb->data + CAPI_MSG_BASELEN + 15, len);
}
break;
case CAPI_FUNCTION_GET_VERSION:
if (skb->len < CAPI_MSG_BASELEN + 32)
break;
controller = CAPIMSG_U32(skb->data, CAPI_MSG_BASELEN + 12);
if (!info && ctrl) {
ctrl->version.majorversion = CAPIMSG_U32(skb->data, CAPI_MSG_BASELEN + 16);
ctrl->version.minorversion = CAPIMSG_U32(skb->data, CAPI_MSG_BASELEN + 20);
ctrl->version.majormanuversion = CAPIMSG_U32(skb->data, CAPI_MSG_BASELEN + 24);
ctrl->version.minormanuversion = CAPIMSG_U32(skb->data, CAPI_MSG_BASELEN + 28);
}
break;
case CAPI_FUNCTION_GET_SERIAL_NUMBER:
if (skb->len < CAPI_MSG_BASELEN + 17)
break;
controller = CAPIMSG_U32(skb->data, CAPI_MSG_BASELEN + 12);
if (!info && ctrl) {
int len = min_t(uint, CAPI_SERIAL_LEN,
skb->data[CAPI_MSG_BASELEN + 16]);
memset(ctrl->serial, 0, CAPI_SERIAL_LEN);
strncpy(ctrl->serial,
skb->data + CAPI_MSG_BASELEN + 17, len);
}
break;
}
break;
case CAPI_IND:
if (skb->len < CAPI_MSG_BASELEN + 6)
break;
func = CAPIMSG_U16(skb->data, CAPI_MSG_BASELEN + 3);
if (func == CAPI_FUNCTION_LOOPBACK) {
int len = min_t(uint, skb->len - CAPI_MSG_BASELEN - 6,
skb->data[CAPI_MSG_BASELEN + 5]);
appl = CAPIMSG_APPID(skb->data);
msgnum = CAPIMSG_MSGID(skb->data);
cmtp_send_interopmsg(session, CAPI_RESP, appl, msgnum, func,
skb->data + CAPI_MSG_BASELEN + 6, len);
}
break;
}
kfree_skb(skb);
}
void CMTP_CAPI::cmtp_recv_capimsg(struct cmtp_session *session, struct sk_buff *skb)
struct capi_ctr *ctrl = &session->ctrl;
struct cmtp_application *application;
__u16 appl;
__u32 contr;
BT_DBG("session %p skb %p len %d", session, skb, skb->len);
if (skb->len < CAPI_MSG_BASELEN)
return;
if (CAPIMSG_COMMAND(skb->data) == CAPI_INTEROPERABILITY) {
cmtp_recv_interopmsg(session, skb);
return;
}
if (session->flags & (1 << CMTP_LOOPBACK)) {
kfree_skb(skb);
return;
}
appl = CAPIMSG_APPID(skb->data);
contr = CAPIMSG_CONTROL(skb->data);
application = cmtp_application_get(session, CMTP_MAPPING, appl);
if (application) {
appl = application->appl;
CAPIMSG_SETAPPID(skb->data, appl);
} else {
BT_ERR("Can't find application with id %d", appl);
kfree_skb(skb);
return;
}
if ((contr & 0x7f) == 0x01) {
contr = (contr & 0xffffff80) | session->num;
CAPIMSG_SETCONTROL(skb->data, contr);
}
if (!ctrl) {
BT_ERR("Can't find controller %d for message", session->num);
kfree_skb(skb);
return;
}
capi_ctr_handle_message(ctrl, appl, skb);
}
int CMTP_CAPI::cmtp_load_firmware(struct capi_ctr *ctrl, capiloaddata *data)
{
BT_DBG("ctrl %p data %p", ctrl, data);
return 0;
}
void CMTP_CAPI::cmtp_reset_ctr(struct capi_ctr *ctrl)
{
struct cmtp_session *session = ctrl->driverdata;
BT_DBG("ctrl %p", ctrl);
capi_ctr_down(ctrl);
atomic_inc(&session->terminate);
wake_up_process(session->task);
}
void CMTP_CAPI::cmtp_register_appl(struct capi_ctr *ctrl, __u16 appl, capi_register_params *rp)
{
DECLARE_WAITQUEUE(wait, current);
struct cmtp_session *session = ctrl->driverdata;
struct cmtp_application *application;
unsigned long timeo = CMTP_INTEROP_TIMEOUT;
unsigned char buf[8];
int err = 0, nconn, want = rp->level3cnt;
BT_DBG("ctrl %p appl %d level3cnt %d datablkcnt %d datablklen %d",
ctrl, appl, rp->level3cnt, rp->datablkcnt, rp->datablklen);
application = cmtp_application_add(session, appl);
if (!application) {
BT_ERR("Can't allocate memory for new application");
return;
}
if (want < 0)
nconn = ctrl->profile.nbchannel * -want;
else
nconn = want;
if (nconn == 0)
nconn = ctrl->profile.nbchannel;
capimsg_setu16(buf, 0, nconn);
capimsg_setu16(buf, 2, rp->datablkcnt);
capimsg_setu16(buf, 4, rp->datablklen);
application->state = BT_CONFIG;
application->msgnum = cmtp_msgnum_get(session);
cmtp_send_interopmsg(session, CAPI_REQ, 0x0000, application->msgnum,
CAPI_FUNCTION_REGISTER, buf, 6);
add_wait_queue(&session->wait, &wait);
while (1) {
set_current_state(TASK_INTERRUPTIBLE);
if (!timeo) {
err = -EAGAIN;
break;
}
if (application->state == BT_CLOSED) {
err = -application->err;
break;
}
if (application->state == BT_CONNECTED)
break;
if (signal_pending(current)) {
err = -EINTR;
break;
}
timeo = schedule_timeout(timeo);
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&session->wait, &wait);
if (err) {
cmtp_application_del(session, application);
return;
}
}
void CMTP_CAPI::cmtp_release_appl(struct capi_ctr *ctrl, __u16 appl)
{
struct cmtp_session *session = ctrl->driverdata;
struct cmtp_application *application;
BT_DBG("ctrl %p appl %d", ctrl, appl);
application = cmtp_application_get(session, CMTP_APPLID, appl);
if (!application) {
BT_ERR("Can't find application");
return;
}
application->msgnum = cmtp_msgnum_get(session);
cmtp_send_interopmsg(session, CAPI_REQ, application->mapping, application->msgnum,
CAPI_FUNCTION_RELEASE, NULL, 0);
wait_event_interruptible_timeout(session->wait,
(application->state == BT_CLOSED), CMTP_INTEROP_TIMEOUT);
cmtp_application_del(session, application);
}
u16 CMTP_CAPI::cmtp_send_message(struct capi_ctr *ctrl, struct sk_buff *skb)
{
struct cmtp_session *session = ctrl->driverdata;
struct cmtp_application *application;
__u16 appl;
__u32 contr;
BT_DBG("ctrl %p skb %p", ctrl, skb);
appl = CAPIMSG_APPID(skb->data);
contr = CAPIMSG_CONTROL(skb->data);
application = cmtp_application_get(session, CMTP_APPLID, appl);
if ((!application) || (application->state != BT_CONNECTED)) {
BT_ERR("Can't find application with id %d", appl);
return CAPI_ILLAPPNR;
}
CAPIMSG_SETAPPID(skb->data, application->mapping);
if ((contr & 0x7f) == session->num) {
contr = (contr & 0xffffff80) | 0x01;
CAPIMSG_SETCONTROL(skb->data, contr);
}
cmtp_send_capimsg(session, skb);
return CAPI_NOERROR;
}
char* CMTP_CAPI::cmtp_procinfo(struct capi_ctr *ctrl)
{
return "CAPI Message Transport Protocol";
}
int CMTP_CAPI::cmtp_proc_show(struct seq_file *m, void *v)
{
struct capi_ctr *ctrl = m->private;
struct cmtp_session *session = ctrl->driverdata;
struct cmtp_application *app;
struct list_head *p, *n;
seq_printf(m, "%s\n\n", cmtp_procinfo(ctrl));
seq_printf(m, "addr %s\n", session->name);
seq_printf(m, "ctrl %d\n", session->num);
list_for_each_safe(p, n, &session->applications) {
app = list_entry(p, struct cmtp_application, list);
seq_printf(m, "appl %d -> %d\n", app->appl, app->mapping);
}
return 0;
}
int CMTP_CAPI::cmtp_proc_open(struct inode *inode, struct file *file)
{
return single_open(file, cmtp_proc_show, PDE_DATA(inode));
}
int CMTP_CAPI::cmtp_attach_device(struct cmtp_session *session)
{
unsigned char buf[4];
long ret;
BT_DBG("session %p", session);
capimsg_setu32(buf, 0, 0);
cmtp_send_interopmsg(session, CAPI_REQ, 0xffff, CMTP_INITIAL_MSGNUM,
CAPI_FUNCTION_GET_PROFILE, buf, 4);
ret = wait_event_interruptible_timeout(session->wait,
session->ncontroller, CMTP_INTEROP_TIMEOUT);
BT_INFO("Found %d CAPI controller(s) on device %s", session->ncontroller, session->name);
if (!ret)
return -ETIMEDOUT;
if (!session->ncontroller)
return -ENODEV;
if (session->ncontroller > 1)
BT_INFO("Setting up only CAPI controller 1");
session->ctrl.owner = THIS_MODULE;
session->ctrl.driverdata = session;
strcpy(session->ctrl.name, session->name);
session->ctrl.driver_name = "cmtp";
session->ctrl.load_firmware = cmtp_load_firmware;
session->ctrl.reset_ctr = cmtp_reset_ctr;
session->ctrl.register_appl = cmtp_register_appl;
session->ctrl.release_appl = cmtp_release_appl;
session->ctrl.send_message = cmtp_send_message;
session->ctrl.procinfo = cmtp_procinfo;
session->ctrl.proc_fops = &cmtp_proc_fops;
if (attach_capi_ctr(&session->ctrl) < 0) {
BT_ERR("Can't attach new controller");
return -EBUSY;
}
session->num = session->ctrl.cnr;
BT_DBG("session %p num %d", session, session->num);
capimsg_setu32(buf, 0, 1);
cmtp_send_interopmsg(session, CAPI_REQ, 0xffff, cmtp_msgnum_get(session),
CAPI_FUNCTION_GET_MANUFACTURER, buf, 4);
cmtp_send_interopmsg(session, CAPI_REQ, 0xffff, cmtp_msgnum_get(session),
CAPI_FUNCTION_GET_VERSION, buf, 4);
cmtp_send_interopmsg(session, CAPI_REQ, 0xffff, cmtp_msgnum_get(session),
CAPI_FUNCTION_GET_SERIAL_NUMBER, buf, 4);
cmtp_send_interopmsg(session, CAPI_REQ, 0xffff, cmtp_msgnum_get(session),
CAPI_FUNCTION_GET_PROFILE, buf, 4);
return 0;
}
void CMTP_CAPI::cmtp_detach_device(struct cmtp_session *session)
{
BT_DBG("session %p", session);
detach_capi_ctr(&session->ctrl);
}
void cmtp_recv_capimsg(struct cmtp_session *session, struct sk_buff *skb){
cmtp_capi.cmtp_recv_capimsg(session, skb);
}
int cmtp_attach_device(struct cmtp_session *session){
return cmtp_capi.cmtp_attach_device(session);
}
void cmtp_detach_device(struct cmtp_session *session){
cmtp_capi.cmtp_detach_device(session);
}
static int cmtp_proc_open(struct inode *inode, struct file *file){
return cmtp_capi.cmtp_proc_open(inode, file);
}
| [
"mgupta3@linkedin.com"
] | mgupta3@linkedin.com |
cf8182a9a8d89ac3dfdef31c27a0c8b843246f35 | a8b2ab984cf02660efce5a7696cd3218d7023883 | /cpp/1361.validate-binary-tree-nodes.cpp | 1e8b7322fcbd18e3591186e89f76b1918a8ab0ea | [
"MIT"
] | permissive | vermouth1992/Leetcode | b445f51de3540ef453fb594f04d5c9d9ad934c0c | 386e794861f37c17cfea0c8baa3f544c8e5ca7a8 | refs/heads/master | 2022-11-07T13:04:00.393597 | 2022-10-28T02:59:22 | 2022-10-28T02:59:22 | 100,220,916 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,270 | cpp | /*
* @lc app=leetcode id=1361 lang=cpp
*
* [1361] Validate Binary Tree Nodes
*
* https://leetcode.com/problems/validate-binary-tree-nodes/description/
*
* algorithms
* Medium (42.92%)
* Total Accepted: 26.3K
* Total Submissions: 62.3K
* Testcase Example: '4\n[1,-1,3,-1]\n[2,-1,-1,-1]'
*
* You have n binary tree nodes numbered from 0 to n - 1 where node i has two
* children leftChild[i] and rightChild[i], return true if and only if all the
* given nodes form exactly one valid binary tree.
*
* If node i has no left child then leftChild[i] will equal -1, similarly for
* the right child.
*
* Note that the nodes have no values and that we only use the node numbers in
* this problem.
*
*
* Example 1:
*
*
* Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]
* Output: true
*
*
* Example 2:
*
*
* Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]
* Output: false
*
*
* Example 3:
*
*
* Input: n = 2, leftChild = [1,0], rightChild = [-1,-1]
* Output: false
*
*
* Example 4:
*
*
* Input: n = 6, leftChild = [1,-1,-1,4,-1,-1], rightChild = [2,-1,-1,5,-1,-1]
* Output: false
*
*
*
* Constraints:
*
*
* 1 <= n <= 10^4
* leftChild.length == rightChild.length == n
* -1 <= leftChild[i], rightChild[i] <= n - 1
*
*
*/
#include "common.hpp"
class Solution {
public:
bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
// In a valid binary tree, each node has exactly one parent and there is only one node that has no parent.
std::vector<int> parents (n, 0);
for (size_t i = 0; i < n; i++) {
int parent = i;
int left_child = leftChild[i];
if (left_child != -1) {
if (parents[left_child] != 0) return false;
parents[left_child] += 1;
}
int right_child = rightChild[i];
if (right_child != -1) {
if (parents[right_child] != 0) return false;
parents[right_child] += 1;
}
}
int root = -1;
for (int i = 0; i < n; i++) {
if (parents[i] != 0) continue;
if (parents[i] == 0 && root != -1) {
return false;
} else {
root = i;
}
}
if (root == -1) return false;
// dfs from root to detect cycle
std::vector<bool> visited (n, false);
std::queue<int> frontier;
int num_visited = 0;
frontier.push(root);
while (!frontier.empty()) {
int curr = frontier.front();
frontier.pop();
num_visited += 1;
if (visited[curr]) return false;
visited[curr] = true;
if (leftChild[curr] != -1) {
frontier.push(leftChild[curr]);
}
if (rightChild[curr] != -1) {
frontier.push(rightChild[curr]);
}
}
if (num_visited != n) return false;
return true;
}
};
int main() {
auto left = std::vector<int> {1, 0};
auto right = std::vector<int> {-1, -1};
std::cout << Solution().validateBinaryTreeNodes(2, left, right) << std::endl;
} | [
"czhangseu@gmail.com"
] | czhangseu@gmail.com |
c882b8c34379c3a02cb2fa97720a952f5c9136ee | 9f8a069f7d337a022cae89e3e5b75d161c832e2d | /Midterm_Case/Graded_Mesh/TimeAccurate/Laminar/725/uniform/cumulativeContErr | 8ae0183ca452f197652269e11cc51ab4a4a3e90d | [] | no_license | Logan-Price/CFD | 453f6df21f90fd91a834ce98bc0b3970406f148d | 16e510ec882e65d5f7101e0aac91dbe8a035f65d | refs/heads/master | 2023-04-06T04:17:49.899812 | 2021-04-19T01:22:14 | 2021-04-19T01:22:14 | 359,291,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1912 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class uniformDimensionedScalarField;
location "725/uniform";
object cumulativeContErr;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
value 0.000250261;
// ************************************************************************* //
| [
"loganprice2369@gmail.com"
] | loganprice2369@gmail.com | |
728ecd62d1bb9e47b76e9e9c64a1b67839462117 | 7b2e8e7987777bb35391c9c244931e4fd960e42e | /MarioBros/StageLoader.h | 1d7080fef73c49587c1f3104d58a978cb56374a6 | [] | no_license | hiro23190/2week | c3d87406f5e8b8c1734b0d728301606633cbb523 | ce13282aba6a90f0d99451471b9ae68335131046 | refs/heads/master | 2020-05-20T00:41:40.692615 | 2019-05-07T00:50:54 | 2019-05-07T00:50:54 | 185,292,855 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 324 | h | #pragma once
#include <vector>
struct EnemyData {
int frame;
int type;
int dir;
};
class StageLoader
{
private:
int _stageNo;
std::vector<EnemyData> _enemyData;
public:
StageLoader();
~StageLoader();
void LoadStage(int&);
const int GetStageNo() const;
const std::vector<EnemyData> GetEnemyData() const;
};
| [
"1701327@PC65211"
] | 1701327@PC65211 |
b369cdb809a20e6a4fd5fa5b49b7c8a98c0956df | f678d3a6d93f949eaf286d41a3270f430726b615 | /nonconsecutive_ones_ints/main.cpp | 24d16177d1dfec7f4439e6542e82dc54ec0af15a | [] | no_license | yinxx/leetcode | aa1eac1b513c4ed44613cc55de3daa67e1760c65 | 8a6954928acb0961ec3b65d7b7882305c0e617cf | refs/heads/master | 2020-03-20T16:45:12.669033 | 2017-12-25T03:35:34 | 2017-12-25T03:35:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,319 | cpp | #include <iostream>
#include <vector>
#include <cmath>
/** ALGORITHM
* There is a natural recurrence relation to this:
* Base case: r(0) = 1, r(1) = 2
*
* r(i) = r(i-2) + r(i-1)
*
* Imperfect numbers are defined as numbers x such that 2^i < x < 2^{i+1} for some i >= 0.
*
* Imperfect numbers are hard to retrieve the answers of, as we need to prune iteratively:
*
* while residue != 0:
* cur_i = log_2(residue)
* count += r(cur_i)
* residue -= 2^cur_i
*/
int find_integers(int num){
// base cases
if(num == 0)
return 1;
if(num == 1)
return 2;
// dp to handle recursion
std::vector<int> dp(std::log2(num+1));
dp[0] = 1;
dp[1] = 2;
for(int i = 2; i <= std::log2(num+1); i++){
dp[i] = dp[i-2] + dp[i-1];
}
// now residue on num:
auto trunc = [](int x) -> int{
int radix = std::log2(x+1);
return std::min(int(std::exp2(radix) + std::exp2(radix-1) - 1), x);
};
int residue = trunc(num);
int count = 0;
while(residue >= 0){
int radix = std::log2(residue+1);
count += dp[radix];
residue -= std::exp2(radix);
residue = trunc(residue);
}
return count;
}
int main(){
std::cout << "ANSWER : " << find_integers(2525) << std::endl;
return 0;
}
| [
"dev@Rays-MBP.lan"
] | dev@Rays-MBP.lan |
72767a82d4f4c68185e703b060b836002829bd0d | d08ecd1ecfa5d83a0b574a04a8b48165df8491ab | /monton/clases.h | c38872b6baf9e875850350b82baa9da800fe92d0 | [] | no_license | luisthmn/ED_Parcial4 | fc2e8fd47a2c9ea73a668b0fd070ba8867e71116 | a83b641cca6f162bede4db82c95400d4f2f21aec | refs/heads/master | 2020-05-23T19:47:24.852042 | 2019-05-24T20:58:19 | 2019-05-24T20:58:19 | 186,919,022 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 662 | h | #ifndef CLASES_H_INCLUDED
#define CLASES_H_INCLUDED
//-----------------------------------------------------------
struct nodo{
nodo *padre, *h_der, *h_izq, *anterior, *siguiente;
int valor;
};
//---------------------------------------------------------
class monton{
nodo *raiz, *principio, *Final, *donde;
enum _como{H_DER, H_IZQ};
enum _como como;
public:
monton();
~monton();
void agregar(int a);
int sacar();
void pintar();
void subir(nodo *p);
void bajar(nodo *p);
void intercambiar(nodo *p, nodo *q);
};
//------------------------------------------------------------
#endif // CLASES_H_INCLUDED
| [
"33427296+luisthmn@users.noreply.github.com"
] | 33427296+luisthmn@users.noreply.github.com |
4139cd32802bd73e8a43956d512044ad7c41a167 | 9dd36466d34234636c8c0a2b93ba4254cd0d53b7 | /nodemcu.ino | 0686e3a5aef878951326909ab1df6797beb0e716 | [] | no_license | dimasarna/oltp | be94bd8729625edce59c3df28104234d1a64f53b | df481e986736b280e10ff55180aad0b1a4d835d3 | refs/heads/main | 2023-07-09T01:09:21.472926 | 2021-08-06T09:49:54 | 2021-08-06T09:49:54 | 393,330,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,240 | ino | #define ARDUINOJSON_ENABLE_ARDUINO_STRING 1
#include <ArduinoJson.h>
/*************************************************************
Download latest Blynk library here:
https://github.com/blynkkk/blynk-library/releases/latest
Blynk is a platform with iOS and Android apps to control
Arduino, Raspberry Pi and the likes over the Internet.
You can easily build graphic interfaces for all your
projects by simply dragging and dropping widgets.
Downloads, docs, tutorials: http://www.blynk.cc
Sketch generator: http://examples.blynk.cc
Blynk community: http://community.blynk.cc
Follow us: http://www.fb.com/blynkapp
http://twitter.com/blynk_app
Blynk library is licensed under MIT license
This example code is in public domain.
*************************************************************
This example runs directly on NodeMCU.
Note: This requires ESP8266 support package:
https://github.com/esp8266/Arduino
Please be sure to select the right NodeMCU module
in the Tools -> Board menu!
For advanced settings please follow ESP examples :
- ESP8266_Standalone_Manual_IP.ino
- ESP8266_Standalone_SmartConfig.ino
- ESP8266_Standalone_SSL.ino
Change WiFi ssid, pass, and Blynk auth token to run :)
Feel free to apply it to any other example. It's simple!
*************************************************************/
/* Comment this out to disable prints and save space */
//#define BLYNK_PRINT Serial
#include <BlynkSimpleEsp8266.h>
#include <ESP8266WiFi.h> // Include the Wi-Fi library
#include <ESP8266WiFiMulti.h> // Include the Wi-Fi-Multi library
ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti'
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
//char auth[] = "DzTHs6XogNtZmyENzzGDzVMkgUI6I3ld";
char auth[] = "jFjEeW3BiAIEDbnXEUmJ_0aQCin01gX9";
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "YourNetworkName";
char pass[] = "YourPassword";
// Create json document instance
StaticJsonDocument<512> doc;
StaticJsonDocument<256> data;
// Create instance blynk widget
WidgetLCD lcd(V1);
WidgetMap hwMap(V2);
// Message buffer
char line0[17];
char line1[17];
char line2[17];
char line3[17];
BlynkTimer timer;
int timer1_ID;
int timer2_ID;
void printVI()
{
lcd.clear();
lcd.print(0, 0, line0);
lcd.print(0, 1, line1);
timer.toggle(timer1_ID);
timer.toggle(timer2_ID);
}
void printTL()
{
lcd.clear();
lcd.print(0, 0, line2);
lcd.print(0, 1, line3);
timer.toggle(timer1_ID);
timer.toggle(timer2_ID);
}
BLYNK_WRITE(V0) {
float latitude = param[0].asFloat();
float longitude = param[1].asFloat();
char lat_str[8];
char lng_str[9];
dtostrf(latitude, 7, 4, lat_str);
dtostrf(longitude, 8, 4, lng_str);
sprintf(line3, "%6s,%7s", lat_str, lng_str);
hwMap.location(0, latitude, longitude, "Machine");
data["location"]["lat"] = latitude;
data["location"]["lng"] = longitude;
serializeJson(data, Serial);
}
BLYNK_WRITE(V6) {
data["cmd"][0] = param.asInt();
serializeJson(data, Serial);
}
BLYNK_WRITE(V7) {
data["cmd"][1] = param.asInt();
serializeJson(data, Serial);
}
void setup()
{
// Debug console
Serial.begin(9600);
wifiMulti.addAP("SSID_TA_PLN", "12345678"); // add Wi-Fi networks you want to connect to
wifiMulti.addAP("ANOTHER_SSID", "ANOTHER_PASSWORD"); // add Wi-Fi networks you want to connect to
//Blynk.begin(auth, ssid, pass);
// You can also specify server:
//Blynk.config(auth, "blynk.iot-cm.com", 8080);
Blynk.config(auth, "blynk-cloud.com", 80);
//Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
delay(500);
}
Blynk.connect();
timer.setTimeout(3600000L, [] () {} ); // dummy/sacrificial Function
timer1_ID = timer.setInterval(5000L, printVI);
timer2_ID = timer.setInterval(5000L, printTL);
timer.disable(timer2_ID);
}
void loop()
{
Blynk.run();
timer.run();
if (Serial.available()) {
deserializeJson(doc, Serial);
float UL1 = doc["voltage"][0];
float CT1 = doc["current"][0];
float UL2 = doc["voltage"][1];
float CT2 = doc["current"][1];
float UL3 = doc["voltage"][2];
float CT3 = doc["current"][2];
char UL1_str[4];
char CT1_str[4];
char UL2_str[4];
char CT2_str[4];
char UL3_str[4];
char CT3_str[4];
dtostrf(UL1, 3, 0, UL1_str);
dtostrf(UL2, 3, 0, UL2_str);
dtostrf(UL3, 3, 0, UL3_str);
dtostrf(CT1, 3, 1, CT1_str);
dtostrf(CT2, 3, 1, CT2_str);
dtostrf(CT3, 3, 1, CT3_str);
sprintf(line0, " %3sA %3sA %3sA ", CT1_str, CT2_str, CT3_str);
sprintf(line1, " %3sV %3sV %3sV ", UL1_str, UL2_str, UL3_str);
float Temp1 = doc["temperature"][0];
float Temp2 = doc["temperature"][1];
char Temp1_str[5];
char Temp2_str[5];
dtostrf(Temp1, 4, 1, Temp1_str);
dtostrf(Temp2, 4, 1, Temp2_str);
sprintf(line2, "T1 %4s T2 %4s", Temp1_str, Temp2_str);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
cdc09510c3a391b6f3db96f1bd06faaee94e62b6 | e6d76ee85a5cb6617af198cf54a3c6f3022c2ae1 | /headers/City.h | d0dbdae835c7a8e35f30eb1101b3a2f44d4911df | [] | no_license | wkerstiens/MissileCommand | f71b1df143c0b7bfd22e086fb9c9efaacea01701 | 3fb732855fa8fa0b94143cf72150f175a7c49a3c | refs/heads/master | 2023-01-06T22:40:07.026882 | 2020-11-08T22:32:34 | 2020-11-08T22:32:34 | 310,698,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | h | //
// Created by William Kerstiens on 11/7/20.
//
#include "Drawable.h"
#ifndef MISSILECOMMAND_CITY_H
#define MISSILECOMMAND_CITY_H
enum class CITY_STATUS {
INTACT,
DESTROYED
};
class City : public Drawable {
public:
City(int x, int y, int w, int h);
void Render(SDL_Renderer *renderer) override;
void printStatus() override;
void Update() override;
CITY_STATUS Status();
void Status(CITY_STATUS status);
protected:
private:
std::mutex _mtxStatus;
CITY_STATUS _status;
int _x {0};
int _y {0};
int _width{0};
int _height {0};
};
#endif //MISSILECOMMAND_CITY_H
| [
"tony.kerstiens@gmail.com"
] | tony.kerstiens@gmail.com |
916ed04a0594a8c58cc93170414cbfa653d2b408 | 5c27401da2c64ff7fd21d874a84235fedc96eca3 | /oculus2/oculus_rviz_plugins/include/oculus_rviz_plugins/ogre_oculus.h | b4a6d6d7652df65bd67c6322490729e91ff9e6c8 | [] | no_license | irvs/tms_dev_oculus | 1dfac0d3295745bfec991b5503c3f4d98897af58 | c3e5972cb4bcb96e424c31eed4eafe568c78a08d | refs/heads/master | 2020-06-02T18:15:34.537834 | 2014-11-07T11:16:14 | 2014-11-07T11:16:14 | 26,313,893 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,459 | h | /// Copyright (C) 2013 Kojack
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
/// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
/// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
/// DEALINGS IN THE SOFTWARE.
#pragma once
#include "OGRE/OgreQuaternion.h"
#include "OGRE/OgreVector3.h"
#include <string>
namespace OVR
{
class HMDDevice;
class SensorFusion;
class DeviceManager;
class SensorDevice;
namespace Util
{
class MagCalibration;
namespace Render
{
class StereoConfig;
}
}
}
namespace Ogre
{
class SceneManager;
class RenderWindow;
class Camera;
class SceneNode;
class Viewport;
class CompositorInstance;
}
namespace oculus_rviz_plugins
{
class Oculus
{
public:
Oculus(void);
~Oculus(void);
bool setupOculus();
bool setupOgre(Ogre::SceneManager *sm, Ogre::RenderWindow *win, Ogre::SceneNode *parent = 0);
void shutDownOculus();
void shutDownOgre();
bool isOgreReady() const;
bool isOculusReady() const;
/// Update camera node using current Oculus orientation.
void update();
/// Retrieve the SceneNode that contains the two cameras used for stereo rendering.
Ogre::SceneNode *getCameraNode();
/// Retrieve the current orientation of the Oculus HMD.
Ogre::Quaternion getOrientation(int i) const;
/// Retrieve either of the two distortion compositors.
Ogre::CompositorInstance *getCompositor(unsigned int i);
/// Retrieve either of the two cameras.
Ogre::Camera *getCamera(unsigned int i)
{
return m_cameras[i % 2];
}
/// Retrieve either of the two viewports.
Ogre::Viewport *getViewport(unsigned int i)
{
return m_viewports[i % 2];
}
/// Retrieve the projection centre offset.
float getCentreOffset() const;
const ovrHmd *getHMDDevice()
{
return &m_hmd;
}
const ovrHmdDesc *getHMDDesc()
{
return &m_hmdDesc;
}
/// Re-create projection matrices based on camera parameters
void updateProjectionMatrices();
protected:
bool m_oculusReady; /// Has the oculus rift been fully initialised?
bool m_ogreReady; /// Has ogre been fully initialised?
Ogre::SceneManager *m_sceneManager;
Ogre::RenderWindow *m_window;
Ogre::SceneNode *m_cameraNode;
Ogre::Quaternion m_orientation;
float m_centreOffset; /// Projection centre offset.
Ogre::Camera *m_cameras[2];
Ogre::Viewport *m_viewports[2];
Ogre::CompositorInstance *m_compositors[2];
ovrHmd m_hmd;
ovrHmdDesc m_hmdDesc;
ovrEyeRenderDesc EyeRenderDesc[2];
};
}
| [
"onishi@irvs.ait.kyushu-u.ac.jp"
] | onishi@irvs.ait.kyushu-u.ac.jp |
b56c8cafa08dcbefb528aa823052c7c5b4ebd621 | 19d77ac096ea9bec1e3b5e0d18a5c4d1cbb6ef99 | /Source/Libs/ProcessEnumerator/ModuleInfo.h | 09a0bb0d6e099c1e3e82abac9a6e2a6b9ab2ad71 | [] | no_license | GrayMage/GrayMod | 9bd30645349470b0977afee7b15f9df96a419279 | 9cba50b79295a390490dfd4842f97f9b72c2e1b7 | refs/heads/master | 2021-01-22T06:18:42.108876 | 2017-04-06T17:41:17 | 2017-04-06T17:44:35 | 81,752,238 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 418 | h | #pragma once
#include <string>
#include <winnt.h>
class CModuleInfo
{
friend class CProcessInfo;
friend class CModuleList;
private:
CModuleInfo(HMODULE hModule, TCHAR *moduleName) : _hModule(hModule), _moduleName(moduleName) {};
HMODULE _hModule;
std::string _moduleName;
public:
HMODULE handle() const
{
return _hModule;
}
std::string name() const
{
return _moduleName;
}
}; | [
"graymage@users.noreply.github.com"
] | graymage@users.noreply.github.com |
ccaa51c38b3a8f3426e33e12166189513c557c35 | 70ecac44b229e4e35050fd93ccc8b8778dc94720 | /AtCoder/typical90/015 - Don't be too close/main.cpp | 6739f136c4f67eda7ef7db130fe837ebe4534645 | [
"MIT"
] | permissive | t-mochizuki/cpp-study | 5602661ee1ad118b93ee8993e006f84b85a10a8b | 1f6eb99db765fd970f2a44f941610d9a79200953 | refs/heads/main | 2023-07-21T13:55:11.664199 | 2023-07-10T09:35:11 | 2023-07-10T09:35:11 | 92,583,299 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,387 | cpp | // g++ -std=c++14 -DDEV=1 main.cpp
#include <stdio.h>
#include <cassert>
#include <iostream>
#include <fstream>
#include <vector>
#include <tuple>
using std::cin;
using std::cout;
using std::endl;
using std::terminate;
using std::vector;
using std::tuple;
using std::make_tuple;
using std::tie;
// キーワード: 調和級数はO(NlogN)
#define rep(i, a, n) for (int i = (a); i < (n); ++i)
#define bit(n, k) ((n >> k) & 1)
// ボールpを選ぶと、ボールp+1からボールp+k-1までは選ぶことができない。
// a個のボールの選び方は(N-(k-1)(a-1))!/((N-(k-1)(a-1)-a)!a!)通りになる。
template<int MOD>
class Modulo {
private:
int value;
tuple<int, int> extendedEuclidean(int a, int b, int x = 1, int y = 0, int u = 0, int v = 1) const {
if (b == 0) {
return make_tuple(x, y);
} else {
int q = a / b;
int r = a % b;
x = x - (q * u);
y = y - (q * v);
return extendedEuclidean(b, r, u, v, x, y);
}
}
int inverse() const {
int x, y;
tie(x, y) = extendedEuclidean(value, MOD);
int gcd = value * x + MOD * y;
assert(gcd == 1);
return x % MOD;
}
public:
Modulo(int x) {
if (x < 0) {
x %= MOD;
x += MOD;
}
value = x;
}
Modulo operator+(Modulo that) const { return Modulo((value + that.value) % MOD); }
Modulo operator-(Modulo that) const { return Modulo((value - that.value + MOD) % MOD); }
Modulo operator*(Modulo that) const {
long a = value;
long b = that.value;
return Modulo((a * b) % MOD);
}
Modulo operator/(Modulo that) const { return Modulo(value) * Modulo(that.inverse()); }
int get() {
return value;
}
};
typedef Modulo<1000000007> Mod1000000007;
template<class T>
class Combination {
private:
vector<T> fac/*torial*/, inv/*erse element*/;
public:
Combination(int N) {
fac.assign(N+1, T(1));
rep(i, 1, N+1) {
if (i == 1) {
fac[i] = T(1);
} else {
fac[i] = T(i) * fac[i-1];
}
}
inv.assign(N+1, T(1));
for (int i = N; i >= 0; --i) {
if (i == N) {
inv[i] = T(1) / fac[i];
} else {
inv[i] = T(i+1) * inv[i+1];
}
}
}
T get(int n, int k) {
assert(n >= k);
assert(k >= 0);
return fac[n] * inv[k] * inv[n-k];
}
};
typedef Combination<Mod1000000007> Combination1000000007;
class Problem {
private:
int N;
public:
Problem() {
cin >> N;
}
void solve() {
Combination1000000007 C = Combination1000000007(N);
rep(k, 1, N+1) {
Mod1000000007 ans = Mod1000000007(0);
for (int a = 1; a <= N; ++a) {
if ((k-1)*(a-1) > N) break;
if (N-(k-1)*(a-1) >= a) {
ans = ans + C.get(N-(k-1)*(a-1), a);
}
}
cout << ans.get() << endl;
}
}
};
int main() {
#ifdef DEV
std::ifstream in("input");
cin.rdbuf(in.rdbuf());
int t; cin >> t;
for (int x = 1; x <= t; ++x) {
Problem p;
p.solve();
}
#else
Problem p;
p.solve();
#endif
return 0;
}
| [
"t-mochizuki@users.noreply.github.com"
] | t-mochizuki@users.noreply.github.com |
b4ea82907ae0c6c194b420ebdcb52f5a8d7a4c77 | f0d0ae0e964cbfeb1160e27b79ef06b58db577f1 | /fp_core/src/main/include/fruitpunch/Elements/Text.h | e38c221a2d229d43e3d81b39254fc8af706e4ae3 | [
"MIT"
] | permissive | leolimasa/fruitpunch | 7275002d89c0b1f6044017e431d592896ee84a98 | 31773128238830d3d335c1915877dc0db56836cd | refs/heads/master | 2021-01-10T08:44:03.223173 | 2020-02-03T05:28:40 | 2020-02-03T05:28:40 | 51,225,202 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | h |
/*
* Text.h
*
* Created on: 2012-06-24
* Author: leo
*/
#ifndef TEXT_H_
#define TEXT_H_
#include <boost/shared_ptr.hpp>
#include <fruitpunch/Graphics/Sprite.h>
#include <fruitpunch/Resources/Font.h>
namespace fp_core {
/// A text that can be drawn on a scene
class Text : public Sprite {
public:
typedef boost::shared_ptr<Text> ref;
Text(std::string text);
virtual void onFontChange();
virtual void renderFrame();
/// Updates the internal sprite with a new texture of the text
void update();
// ---------------------------------------------------------------------------
// Getters
// ---------------------------------------------------------------------------
std::string getText() const;
Font::ref getFont() const;
// ---------------------------------------------------------------------------
// Setters
// ---------------------------------------------------------------------------
void setText(std::string text);
void setFont(Font::ref font);
private:
Font::ref mFont;
std::string mText;
bool mFontChanged;
};
}
#endif
| [
"leo@leo-sa.com"
] | leo@leo-sa.com |
c9eceadfcd982d8cb074c972968c26c7524d3764 | fb5280dc04e883bd2489a9e75fd6dde9e4694197 | /sceneManager.h | 8542cba905c136fd02ea43914507b32c82c414ad | [] | no_license | mbeom/Angvik_ | d4ae6d6c4c03a595fc3ef21b7c82574bc74e58fb | b9da5777d4caa66ae18894b03657a014a2da86af | refs/heads/main | 2023-08-05T14:24:24.444799 | 2021-10-05T02:32:31 | 2021-10-05T02:32:31 | 404,584,543 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 572 | h | #pragma once
#include "singletonBase.h"
#include <string>
#include <map>
class gameNode;
class sceneManager : public singletonBase<sceneManager>
{
private:
typedef map<string, gameNode*> mapSceneList;
typedef map<string, gameNode*>::iterator mapSceneIter;
private:
static gameNode* _currentScene;
mapSceneList _mSceneList;
sceneManager();
~sceneManager();
friend singletonBase;
public:
HRESULT init();
void release();
void update();
void render();
gameNode* addScene(string sceneName, gameNode* scene);
HRESULT changeScene(string sceneName);
};
| [
"skysklgf@gmail.com"
] | skysklgf@gmail.com |
d326006a53cf72fa014e6a5c0eed2dfc50be7ba1 | 6035029a5e8fa0653fa7d0dd8bd09b6b3c6eee41 | /new/common/UDPSenderFactory.h | eb7ad7c042d0d1695d998c5f4d2fdf44467b571e | [] | no_license | symanli/just-p2p-live-p2pcommon2 | 55b9a74622758cf85d2f046a38263db05c298f15 | c546a704460c573be241b10be5916e798f42a370 | refs/heads/master | 2022-11-18T04:02:23.338671 | 2016-01-11T02:22:39 | 2016-01-11T02:22:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | h |
#ifndef _LIVE_P2PCOMMON2_NEW_COMMON_UDPSENDER_FACTORY_H_
#define _LIVE_P2PCOMMON2_NEW_COMMON_UDPSENDER_FACTORY_H_
#include "common/UDPSender.h"
#include <boost/function.hpp>
typedef boost::function<void (BYTE*, size_t, const InetSocketAddress&, UINT)> UDPSenderCallbackType;
class udp_socket;
class UDPSenderFactory
{
public:
#ifndef _PPL_USE_ASIO
static UDPSender* CreateNormal(int udp);
#else
static UDPSender* CreateNormal(boost::shared_ptr<udp_socket> udp);
#endif
static UDPSender* CreateTCPProxy(UINT timeout, UDPSenderCallbackType callback);
static UDPSender* CreateHTTPProxy(UINT timeout, UDPSenderCallbackType callback);
};
#endif
| [
"isxxguo@pptv.com"
] | isxxguo@pptv.com |
eec180ec5a5d54eb0e87798b5637b86949da74fb | 64729bf6be8c4894d5c6087748903e0d80f1fcf1 | /DS-I/cs17btech11029_q1.cpp | 11c8a66706042001580886307d8c5d793d0e3704 | [] | no_license | Puneet2000/Semester-III | 4e68069fb1be88428c6cb816d0c5ea576f012aa9 | d962ab46e186c9cfdbc542b113e9614620ac0767 | refs/heads/master | 2020-03-24T14:56:12.307755 | 2018-12-23T07:41:07 | 2018-12-23T07:41:07 | 142,781,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 910 | cpp | #include<iostream>
using namespace std;
struct cgpa{
float cg;
struct cgpa *next;
};
int main()
{
struct cgpa *head=NULL;
struct cgpa *s1 = (struct cgpa*) malloc(sizeof(struct cgpa));
struct cgpa *s2 = (struct cgpa*) malloc(sizeof(struct cgpa));
struct cgpa *s3 = (struct cgpa*) malloc(sizeof(struct cgpa));
struct cgpa *s4 = (struct cgpa*) malloc(sizeof(struct cgpa));
struct cgpa *temp = (struct cgpa*) malloc(sizeof(struct cgpa));
cout<<"Enter the CGPA's (with spaces) : ";
cin>>(s1->cg)>>(s2->cg)>>(s3->cg)>>(s4->cg);
head=s4;
s4->next=s3;
s3->next=s2;
s2->next=s1;
s1->next=NULL;
temp=head;
int i=0;
while(temp!=NULL)
{
cout<<"Node "<<i<<endl;
cout<<"index : "<<i<<"\nvalue : "<<temp->cg<<"\nNode address : "<<&temp<<"\npointer address : "<<temp->next<<endl;
temp=temp->next;
i++;
}
free(s1);
free(s2);
free(s3);
free(s4);
free(head);
free(temp);
cout<<"Memory deallocated"<<endl;
return 0;} | [
"cs17btech11029@iith.ac.in"
] | cs17btech11029@iith.ac.in |
ebeaca3358c80455a35fb1ad5a079f329e8a0cad | 3b36791752cdfe4bc71d319796d8e86308fe81c3 | /Asteroids/Asteroids/entity.cpp | 0aa120993e44ae7bc0cf6beed8785cbc0809af7b | [] | no_license | yongchu7/Asteroids | 9ad5a0f8a6bdd639594487c754c7312f781240b0 | 6162eb562db1fc65eb34c23faf6827489d2ad7ea | refs/heads/master | 2021-03-22T00:46:49.197436 | 2017-12-16T04:10:56 | 2017-12-16T04:10:56 | 114,432,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 879 | cpp | #include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
#include <SFML/System.hpp>
#include <SFML/OpenGL.hpp>
#include <SFML/Main.hpp>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <time.h>
#include <list>
#include "animation.h"
#include "entity.h"
using namespace sf;
using namespace std;
Entity::Entity()
{
life = 1;
}
void Entity::settings(Animation &a, int X, int Y, float Angle = 0, int radius = 1)
{
anim = a;
x = X; y = Y;
angle = Angle;
R = radius;
}
virtual void Entity::update() {};
void Entity::draw(RenderWindow &app)
{
anim.sprite.setPosition(x, y);
anim.sprite.setRotation(angle + 90);
app.draw(anim.sprite);
CircleShape circle(R);
circle.setFillColor(Color(255, 0, 0, 170));
circle.setPosition(x, y);
circle.setOrigin(R, R);
//app.draw(circle);
}
virtual ~Entity() {}; | [
"zjhzcyt@GMAIL.COM"
] | zjhzcyt@GMAIL.COM |
f2e9590c17aefd262389e5a4415593fee34c6087 | bc784c75af65e4149158f83bb58207fe66fdf5c7 | /easy_problems/euclidean_tsp.cpp | 03e9533f3457fa9eb13fdac66c761c21c71153d0 | [] | no_license | atseng1729/Kattis-Problems | 9b89e2a56c36970c5475a77f446d5dcffac2ab23 | d8c53a7a3e5028f203022c041197ca57f56b0733 | refs/heads/master | 2020-03-27T06:47:56.267526 | 2018-08-31T04:20:49 | 2018-08-31T04:20:49 | 146,136,060 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 913 | cpp | #include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;
double N, P, S, V, lowerC, upperC, tempLowerC, tempUpperC;
double nOverP, logN, sOverV, sqrt2;
int main() {
cin >> N >> P >> S >> V;
lowerC = 0, upperC = 100;
nOverP = N / P / pow(10, 9);
logN = log2(N);
sOverV = S / V;
sqrt2 = sqrt(2);
while (upperC - lowerC > .0000000001) {
tempLowerC = (2 * lowerC + upperC) / 3;
tempUpperC = (lowerC + 2 * upperC) / 3;
if (nOverP * pow(logN, tempLowerC * sqrt2) + sOverV * (1 + 1 / tempLowerC)
> nOverP * pow(logN, tempUpperC * sqrt2) + sOverV * (1 + 1 / tempUpperC)) {
lowerC = tempLowerC;
} else {
upperC = tempUpperC;
}
}
cout << setprecision(14) << (nOverP * pow(logN, lowerC * sqrt2) + sOverV * (1 + 1 / lowerC)) << " ";
cout << setprecision(14) << lowerC;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
b9b18df8e6e23d9545aef1af39c608e761dc9272 | f0e3847816f0a130ce0f10df4328a85fc71a8d43 | /main.cpp | 13d24e5255918ca3dd9ad91306ae8d8f98c07ed0 | [] | no_license | reddomon/projectus | 2001330486d13f07be3f296d1857ebd415f43165 | e546ee34b074458a9da605955864ae2e8041707e | refs/heads/master | 2019-01-19T11:23:55.925738 | 2013-04-27T07:42:34 | 2013-04-27T07:42:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,184 | cpp | /*
* File: main.cpp
* Author: red
*
* Created on September 18, 2012, 12:44 AM
*/
#include <cstdlib>
#include <stdio.h>
#include <iostream>
//#include <gtk-2.0/gtk/gtk.h>
#include <ddk/usb.h> //usb configuration
#include "rs232.h"
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
long a;
unsigned char byte[]="g0 x12.34 y34.22 z45.466";
char t[2]="s";
unsigned char gelen[11];
int sonuc,i,deger,sayici;
unsigned int port;
printf("bu program rs232 seri port durumunu gösterir\n");
cin >> port;
deger=OpenComport(port,9600);
if(deger==1) return 1;
/* struct sysinfo bilgi;
a=bilgi.uptime;
printf("%ld\n",a);
printf("basliyor\n"); */
while(1){
cin >> byte;
sayici=0;
while(1){
sonuc=SendByte(port,byte[sayici]);
sayici++;
if(byte[sayici]=='\0') break;
}
if(sonuc==1) printf("veri yollanamadı!yonetici oldugunuzdan emin olun");
else if(sonuc==0) printf("veri yollandı\n");
cin >> byte;
if(byte) break;
}
CloseComport(port);
return 0;
}
| [
"reddomon@gmail.com"
] | reddomon@gmail.com |
1d40f13c6733a9bb7dae3dc2cc26c2ff3df86fb6 | 07d221ca1cbc8545ad6e9f8e8388bdca6576fb01 | /Plugins/MenuSystem/Source/MenuSystem/Public/Widgets/Settings/GraphicsSetting.h | 3fd9de0934aab0871c5f7094c0c0312503ec446a | [
"Apache-2.0"
] | permissive | AliElSaleh/MenuSystem-UE4 | ba8852a795c97d6b65eed94ed41251223ce9be40 | 3b588c2a0f084739001276f1a7573aaa820c413c | refs/heads/master | 2020-06-08T08:14:41.079309 | 2019-12-26T02:29:13 | 2019-12-26T02:29:13 | 193,194,226 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 863 | h | // Copyright Ali El Saleh 2019
#pragma once
#include "Settings/VideoSetting.h"
#include "GraphicsSetting.generated.h"
/**
* Base class of a graphics setting
*/
UCLASS(config=Game)
class MENUSYSTEM_API UGraphicsSetting : public UVideoSetting
{
GENERATED_BODY()
public:
void Init() override;
void Reset() override;
void RevertChange() override;
void ChangeGraphicsSetting(int32 Index);
void SetSelectedOption(int32 Index);
protected:
UFUNCTION(BlueprintCallable, Category = "Graphics Setting")
virtual void ChangeGraphicsSetting(const FString& SelectedItem);
UFUNCTION(BlueprintCallable, Category = "Graphics Setting")
virtual void PopulateList(class UComboBoxString* DropDownList);
UFUNCTION(BlueprintCallable, Category = "Graphics Setting")
virtual void SetSelectedOption(class UComboBoxString* DropDownList);
int32 QualityIndex;
};
| [
"elsaleh78@gmail.com"
] | elsaleh78@gmail.com |
82940f5cb61a8b3800612f55cd2000b4b34d47cd | 5ea98407f2bf90054a716baf4d500290b19acec9 | /src/kernel.cpp | bc7608e0ab3223b1efdd666d4e8f4841b0b3efa5 | [
"MIT"
] | permissive | TKPoseidon/peps | 663b737390067c9aaffedc25c98ce3fe5ee5e151 | f5687c7231ac0a7882f8b24302fe4244d3b8f311 | refs/heads/master | 2022-12-30T18:50:58.139448 | 2020-10-07T13:11:47 | 2020-10-07T13:11:47 | 300,279,574 | 1 | 0 | MIT | 2020-10-01T12:56:52 | 2020-10-01T12:56:51 | null | UTF-8 | C++ | false | false | 19,602 | cpp | /* @flow */
// Copyright (c) 2012-2013 The PPCoin developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017 The Peps developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include <boost/lexical_cast.hpp>
#include "db.h"
#include "kernel.h"
#include "script/interpreter.h"
#include "timedata.h"
#include "util.h"
using namespace std;
bool fTestNet = false; //Params().NetworkID() == CBaseChainParams::TESTNET;
// Modifier interval: time to elapse before new modifier is computed
// Set to 3-hour for production network and 20-minute for test network
unsigned int nModifierInterval;
int nStakeTargetSpacing = 60;
unsigned int getIntervalVersion(bool fTestNet)
{
if (fTestNet)
return MODIFIER_INTERVAL_TESTNET;
else
return MODIFIER_INTERVAL;
}
// Hard checkpoints of stake modifiers to ensure they are deterministic
static std::map<int, unsigned int> mapStakeModifierCheckpoints =
boost::assign::map_list_of(0, 0xfd11f4e7u);
// Get time weight
int64_t GetWeight(int64_t nIntervalBeginning, int64_t nIntervalEnd)
{
return nIntervalEnd - nIntervalBeginning - nStakeMinAge;
}
// Get the last stake modifier and its generation time from a given block
static bool GetLastStakeModifier(const CBlockIndex* pindex, uint64_t& nStakeModifier, int64_t& nModifierTime)
{
if (!pindex)
return error("GetLastStakeModifier: null pindex");
while (pindex && pindex->pprev && !pindex->GeneratedStakeModifier())
pindex = pindex->pprev;
if (!pindex->GeneratedStakeModifier())
return error("GetLastStakeModifier: no generation at genesis block");
nStakeModifier = pindex->nStakeModifier;
nModifierTime = pindex->GetBlockTime();
return true;
}
// Get selection interval section (in seconds)
static int64_t GetStakeModifierSelectionIntervalSection(int nSection)
{
assert(nSection >= 0 && nSection < 64);
int64_t a = getIntervalVersion(fTestNet) * 63 / (63 + ((63 - nSection) * (MODIFIER_INTERVAL_RATIO - 1)));
return a;
}
// Get stake modifier selection interval (in seconds)
static int64_t GetStakeModifierSelectionInterval()
{
int64_t nSelectionInterval = 0;
for (int nSection = 0; nSection < 64; nSection++) {
nSelectionInterval += GetStakeModifierSelectionIntervalSection(nSection);
}
return nSelectionInterval;
}
// select a block from the candidate blocks in vSortedByTimestamp, excluding
// already selected blocks in vSelectedBlocks, and with timestamp up to
// nSelectionIntervalStop.
static bool SelectBlockFromCandidates(
vector<pair<int64_t, uint256> >& vSortedByTimestamp,
map<uint256, const CBlockIndex*>& mapSelectedBlocks,
int64_t nSelectionIntervalStop,
uint64_t nStakeModifierPrev,
const CBlockIndex** pindexSelected)
{
bool fModifierV2 = false;
bool fFirstRun = true;
bool fSelected = false;
uint256 hashBest = 0;
*pindexSelected = (const CBlockIndex*)0;
BOOST_FOREACH (const PAIRTYPE(int64_t, uint256) & item, vSortedByTimestamp) {
if (!mapBlockIndex.count(item.second))
return error("SelectBlockFromCandidates: failed to find block index for candidate block %s", item.second.ToString().c_str());
const CBlockIndex* pindex = mapBlockIndex[item.second];
if (fSelected && pindex->GetBlockTime() > nSelectionIntervalStop)
break;
//if the lowest block height (vSortedByTimestamp[0]) is >= switch height, use new modifier calc
if (fFirstRun){
fModifierV2 = pindex->nHeight >= Params().ModifierUpgradeBlock();
fFirstRun = false;
}
if (mapSelectedBlocks.count(pindex->GetBlockHash()) > 0)
continue;
// compute the selection hash by hashing an input that is unique to that block
uint256 hashProof;
if(fModifierV2)
hashProof = pindex->GetBlockHash();
else
hashProof = pindex->IsProofOfStake() ? 0 : pindex->GetBlockHash();
CDataStream ss(SER_GETHASH, 0);
ss << hashProof << nStakeModifierPrev;
uint256 hashSelection = Hash(ss.begin(), ss.end());
// the selection hash is divided by 2**32 so that proof-of-stake block
// is always favored over proof-of-work block. this is to preserve
// the energy efficiency property
if (pindex->IsProofOfStake())
hashSelection >>= 32;
if (fSelected && hashSelection < hashBest) {
hashBest = hashSelection;
*pindexSelected = (const CBlockIndex*)pindex;
} else if (!fSelected) {
fSelected = true;
hashBest = hashSelection;
*pindexSelected = (const CBlockIndex*)pindex;
}
}
if (GetBoolArg("-printstakemodifier", false))
LogPrintf("SelectBlockFromCandidates: selection hash=%s\n", hashBest.ToString().c_str());
return fSelected;
}
// Stake Modifier (hash modifier of proof-of-stake):
// The purpose of stake modifier is to prevent a txout (coin) owner from
// computing future proof-of-stake generated by this txout at the time
// of transaction confirmation. To meet kernel protocol, the txout
// must hash with a future stake modifier to generate the proof.
// Stake modifier consists of bits each of which is contributed from a
// selected block of a given block group in the past.
// The selection of a block is based on a hash of the block's proof-hash and
// the previous stake modifier.
// Stake modifier is recomputed at a fixed time interval instead of every
// block. This is to make it difficult for an attacker to gain control of
// additional bits in the stake modifier, even after generating a chain of
// blocks.
bool ComputeNextStakeModifier(const CBlockIndex* pindexPrev, uint64_t& nStakeModifier, bool& fGeneratedStakeModifier)
{
nStakeModifier = 0;
fGeneratedStakeModifier = false;
if (!pindexPrev) {
fGeneratedStakeModifier = true;
return true; // genesis block's modifier is 0
}
if (pindexPrev->nHeight == 0) {
//Give a stake modifier to the first block
fGeneratedStakeModifier = true;
nStakeModifier = uint64_t("stakemodifier");
return true;
}
// First find current stake modifier and its generation block time
// if it's not old enough, return the same stake modifier
int64_t nModifierTime = 0;
if (!GetLastStakeModifier(pindexPrev, nStakeModifier, nModifierTime))
return error("ComputeNextStakeModifier: unable to get last modifier");
if (GetBoolArg("-printstakemodifier", false))
LogPrintf("ComputeNextStakeModifier: prev modifier= %s time=%s\n", boost::lexical_cast<std::string>(nStakeModifier).c_str(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nModifierTime).c_str());
if (nModifierTime / getIntervalVersion(fTestNet) >= pindexPrev->GetBlockTime() / getIntervalVersion(fTestNet))
return true;
// Sort candidate blocks by timestamp
vector<pair<int64_t, uint256> > vSortedByTimestamp;
vSortedByTimestamp.reserve(64 * getIntervalVersion(fTestNet) / nStakeTargetSpacing);
int64_t nSelectionInterval = GetStakeModifierSelectionInterval();
int64_t nSelectionIntervalStart = (pindexPrev->GetBlockTime() / getIntervalVersion(fTestNet)) * getIntervalVersion(fTestNet) - nSelectionInterval;
const CBlockIndex* pindex = pindexPrev;
while (pindex && pindex->GetBlockTime() >= nSelectionIntervalStart) {
vSortedByTimestamp.push_back(make_pair(pindex->GetBlockTime(), pindex->GetBlockHash()));
pindex = pindex->pprev;
}
int nHeightFirstCandidate = pindex ? (pindex->nHeight + 1) : 0;
reverse(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
sort(vSortedByTimestamp.begin(), vSortedByTimestamp.end());
// Select 64 blocks from candidate blocks to generate stake modifier
uint64_t nStakeModifierNew = 0;
int64_t nSelectionIntervalStop = nSelectionIntervalStart;
map<uint256, const CBlockIndex*> mapSelectedBlocks;
for (int nRound = 0; nRound < min(64, (int)vSortedByTimestamp.size()); nRound++) {
// add an interval section to the current selection round
nSelectionIntervalStop += GetStakeModifierSelectionIntervalSection(nRound);
// select a block from the candidates of current round
if (!SelectBlockFromCandidates(vSortedByTimestamp, mapSelectedBlocks, nSelectionIntervalStop, nStakeModifier, &pindex))
return error("ComputeNextStakeModifier: unable to select block at round %d", nRound);
// write the entropy bit of the selected block
nStakeModifierNew |= (((uint64_t)pindex->GetStakeEntropyBit()) << nRound);
// add the selected block from candidates to selected list
mapSelectedBlocks.insert(make_pair(pindex->GetBlockHash(), pindex));
if (fDebug || GetBoolArg("-printstakemodifier", false))
LogPrintf("ComputeNextStakeModifier: selected round %d stop=%s height=%d bit=%d\n",
nRound, DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nSelectionIntervalStop).c_str(), pindex->nHeight, pindex->GetStakeEntropyBit());
}
// Print selection map for visualization of the selected blocks
if (fDebug || GetBoolArg("-printstakemodifier", false)) {
string strSelectionMap = "";
// '-' indicates proof-of-work blocks not selected
strSelectionMap.insert(0, pindexPrev->nHeight - nHeightFirstCandidate + 1, '-');
pindex = pindexPrev;
while (pindex && pindex->nHeight >= nHeightFirstCandidate) {
// '=' indicates proof-of-stake blocks not selected
if (pindex->IsProofOfStake())
strSelectionMap.replace(pindex->nHeight - nHeightFirstCandidate, 1, "=");
pindex = pindex->pprev;
}
BOOST_FOREACH (const PAIRTYPE(uint256, const CBlockIndex*) & item, mapSelectedBlocks) {
// 'S' indicates selected proof-of-stake blocks
// 'W' indicates selected proof-of-work blocks
strSelectionMap.replace(item.second->nHeight - nHeightFirstCandidate, 1, item.second->IsProofOfStake() ? "S" : "W");
}
LogPrintf("ComputeNextStakeModifier: selection height [%d, %d] map %s\n", nHeightFirstCandidate, pindexPrev->nHeight, strSelectionMap.c_str());
}
if (fDebug || GetBoolArg("-printstakemodifier", false)) {
LogPrintf("ComputeNextStakeModifier: new modifier=%s time=%s\n", boost::lexical_cast<std::string>(nStakeModifierNew).c_str(), DateTimeStrFormat("%Y-%m-%d %H:%M:%S", pindexPrev->GetBlockTime()).c_str());
}
nStakeModifier = nStakeModifierNew;
fGeneratedStakeModifier = true;
return true;
}
// The stake modifier used to hash for a stake kernel is chosen as the stake
// modifier about a selection interval later than the coin generating the kernel
bool GetKernelStakeModifier(uint256 hashBlockFrom, uint64_t& nStakeModifier, int& nStakeModifierHeight, int64_t& nStakeModifierTime, bool fPrintProofOfStake)
{
nStakeModifier = 0;
if (!mapBlockIndex.count(hashBlockFrom))
return error("GetKernelStakeModifier() : block not indexed");
const CBlockIndex* pindexFrom = mapBlockIndex[hashBlockFrom];
nStakeModifierHeight = pindexFrom->nHeight;
nStakeModifierTime = pindexFrom->GetBlockTime();
int64_t nStakeModifierSelectionInterval = GetStakeModifierSelectionInterval();
const CBlockIndex* pindex = pindexFrom;
CBlockIndex* pindexNext = chainActive[pindexFrom->nHeight + 1];
// loop to find the stake modifier later by a selection interval
while (nStakeModifierTime < pindexFrom->GetBlockTime() + nStakeModifierSelectionInterval) {
if (!pindexNext) {
// Should never happen
return error("Null pindexNext\n");
}
pindex = pindexNext;
pindexNext = chainActive[pindexNext->nHeight + 1];
if (pindex->GeneratedStakeModifier()) {
nStakeModifierHeight = pindex->nHeight;
nStakeModifierTime = pindex->GetBlockTime();
}
}
nStakeModifier = pindex->nStakeModifier;
return true;
}
uint256 stakeHash(unsigned int nTimeTx, CDataStream ss, unsigned int prevoutIndex, uint256 prevoutHash, unsigned int nTimeBlockFrom)
{
//Peps will hash in the transaction hash and the index number in order to make sure each hash is unique
ss << nTimeBlockFrom << prevoutIndex << prevoutHash << nTimeTx;
return Hash(ss.begin(), ss.end());
}
//test hash vs target
bool stakeTargetHit(uint256 hashProofOfStake, int64_t nValueIn, uint256 bnTargetPerCoinDay)
{
//get the stake weight - weight is equal to coin amount
uint256 bnCoinDayWeight = uint256(nValueIn) / 100;
// Now check if proof-of-stake hash meets target protocol
return (uint256(hashProofOfStake) < bnCoinDayWeight * bnTargetPerCoinDay);
}
//instead of looping outside and reinitializing variables many times, we will give a nTimeTx and also search interval so that we can do all the hashing here
bool CheckStakeKernelHash(unsigned int nBits, const CBlock blockFrom, const CTransaction txPrev, const COutPoint prevout, unsigned int& nTimeTx, unsigned int nHashDrift, bool fCheck, uint256& hashProofOfStake, bool fPrintProofOfStake)
{
//assign new variables to make it easier to read
int64_t nValueIn = txPrev.vout[prevout.n].nValue;
unsigned int nTimeBlockFrom = blockFrom.GetBlockTime();
if (nTimeTx < nTimeBlockFrom) // Transaction timestamp violation
return error("CheckStakeKernelHash() : nTime violation");
if (nTimeBlockFrom + nStakeMinAge > nTimeTx) // Min age requirement
return error("CheckStakeKernelHash() : min age violation - nTimeBlockFrom=%d nStakeMinAge=%d nTimeTx=%d", nTimeBlockFrom, nStakeMinAge, nTimeTx);
//grab difficulty
uint256 bnTargetPerCoinDay;
bnTargetPerCoinDay.SetCompact(nBits);
//grab stake modifier
uint64_t nStakeModifier = 0;
int nStakeModifierHeight = 0;
int64_t nStakeModifierTime = 0;
if (!GetKernelStakeModifier(blockFrom.GetHash(), nStakeModifier, nStakeModifierHeight, nStakeModifierTime, fPrintProofOfStake)) {
LogPrintf("CheckStakeKernelHash(): failed to get kernel stake modifier \n");
return false;
}
//create data stream once instead of repeating it in the loop
CDataStream ss(SER_GETHASH, 0);
ss << nStakeModifier;
//if wallet is simply checking to make sure a hash is valid
if (fCheck) {
hashProofOfStake = stakeHash(nTimeTx, ss, prevout.n, prevout.hash, nTimeBlockFrom);
return stakeTargetHit(hashProofOfStake, nValueIn, bnTargetPerCoinDay);
}
bool fSuccess = false;
unsigned int nTryTime = 0;
unsigned int i;
int nHeightStart = chainActive.Height();
for (i = 0; i < (nHashDrift); i++) //iterate the hashing
{
//new block came in, move on
if (chainActive.Height() != nHeightStart)
break;
//hash this iteration
nTryTime = nTimeTx + nHashDrift - i;
hashProofOfStake = stakeHash(nTryTime, ss, prevout.n, prevout.hash, nTimeBlockFrom);
// if stake hash does not meet the target then continue to next iteration
if (!stakeTargetHit(hashProofOfStake, nValueIn, bnTargetPerCoinDay))
continue;
fSuccess = true; // if we make it this far then we have successfully created a stake hash
nTimeTx = nTryTime;
if (fDebug || fPrintProofOfStake) {
LogPrintf("CheckStakeKernelHash() : using modifier %s at height=%d timestamp=%s for block from height=%d timestamp=%s\n",
boost::lexical_cast<std::string>(nStakeModifier).c_str(), nStakeModifierHeight,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", nStakeModifierTime).c_str(),
mapBlockIndex[blockFrom.GetHash()]->nHeight,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", blockFrom.GetBlockTime()).c_str());
LogPrintf("CheckStakeKernelHash() : pass protocol=%s modifier=%s nTimeBlockFrom=%u prevoutHash=%s nTimeTxPrev=%u nPrevout=%u nTimeTx=%u hashProof=%s\n",
"0.3",
boost::lexical_cast<std::string>(nStakeModifier).c_str(),
nTimeBlockFrom, prevout.hash.ToString().c_str(), nTimeBlockFrom, prevout.n, nTryTime,
hashProofOfStake.ToString().c_str());
}
break;
}
mapHashedBlocks.clear();
mapHashedBlocks[chainActive.Tip()->nHeight] = GetTime(); //store a time stamp of when we last hashed on this block
return fSuccess;
}
// Check kernel hash target and coinstake signature
bool CheckProofOfStake(const CBlock block, uint256& hashProofOfStake)
{
const CTransaction tx = block.vtx[1];
if (!tx.IsCoinStake())
return error("CheckProofOfStake() : called on non-coinstake %s", tx.GetHash().ToString().c_str());
// Kernel (input 0) must match the stake hash target per coin age (nBits)
const CTxIn& txin = tx.vin[0];
// First try finding the previous transaction in database
uint256 hashBlock;
CTransaction txPrev;
if (!GetTransaction(txin.prevout.hash, txPrev, hashBlock, true))
return error("CheckProofOfStake() : INFO: read txPrev failed");
//verify signature and script
if (!VerifyScript(txin.scriptSig, txPrev.vout[txin.prevout.n].scriptPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&tx, 0)))
return error("CheckProofOfStake() : VerifySignature failed on coinstake %s", tx.GetHash().ToString().c_str());
CBlockIndex* pindex = NULL;
BlockMap::iterator it = mapBlockIndex.find(hashBlock);
if (it != mapBlockIndex.end())
pindex = it->second;
else
return error("CheckProofOfStake() : read block failed");
// Read block header
CBlock blockprev;
if (!ReadBlockFromDisk(blockprev, pindex->GetBlockPos()))
return error("CheckProofOfStake(): INFO: failed to find block");
unsigned int nInterval = 0;
unsigned int nTime = block.nTime;
if (!CheckStakeKernelHash(block.nBits, blockprev, txPrev, txin.prevout, nTime, nInterval, true, hashProofOfStake, fDebug))
return error("CheckProofOfStake() : INFO: check kernel failed on coinstake %s, hashProof=%s \n", tx.GetHash().ToString().c_str(), hashProofOfStake.ToString().c_str()); // may occur during initial download or if behind on block chain sync
return true;
}
// Check whether the coinstake timestamp meets protocol
bool CheckCoinStakeTimestamp(int64_t nTimeBlock, int64_t nTimeTx)
{
// v0.3 protocol
return (nTimeBlock == nTimeTx);
}
// Get stake modifier checksum
unsigned int GetStakeModifierChecksum(const CBlockIndex* pindex)
{
assert(pindex->pprev || pindex->GetBlockHash() == Params().HashGenesisBlock());
// Hash previous checksum with flags, hashProofOfStake and nStakeModifier
CDataStream ss(SER_GETHASH, 0);
if (pindex->pprev)
ss << pindex->pprev->nStakeModifierChecksum;
ss << pindex->nFlags << pindex->hashProofOfStake << pindex->nStakeModifier;
uint256 hashChecksum = Hash(ss.begin(), ss.end());
hashChecksum >>= (256 - 32);
return hashChecksum.Get64();
}
// Check stake modifier hard checkpoints
bool CheckStakeModifierCheckpoints(int nHeight, unsigned int nStakeModifierChecksum)
{
if (fTestNet) return true; // Testnet has no checkpoints
if (mapStakeModifierCheckpoints.count(nHeight)) {
return nStakeModifierChecksum == mapStakeModifierCheckpoints[nHeight];
}
return true;
}
| [
"root@localhost"
] | root@localhost |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.