How to solve the deployment issue about QT creator? - windows

I am going to deploy the QT creator project. But I discovered that some functions of deployment .exe are missing. However, it originally works inside the QT creator. I have no idea about how to solve the current problem, like using what tools to help. The missing function is that the program doesn't show the thumbnails about the video files, where I have assigned the relative images to that.
filemodel.h
#ifndef FILEMODEL_H
#define FILEMODEL_H
#include <QAbstractListModel>
#include <QDirIterator>
#include <QUrl>
#include <QMetaType>
#include <QFuture>
#include <QtConcurrent/QtConcurrent>
#include <iostream>
#include <QImage>
#include <iostream>
#include <fstream>
#include <string>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
struct File
{
Q_GADGET
Q_PROPERTY(QString name MEMBER name)
Q_PROPERTY(QUrl url MEMBER url)
Q_PROPERTY(QImage iconImg MEMBER iconImg)
Q_PROPERTY(QUrl urlicon MEMBER urlicon)
public:
QString name;
QUrl url;
QImage iconImg;
QUrl urlicon;
File(const QString& name=""){
//cout<<name.toStdString();
this->name = QFileInfo(name).fileName();
this->url = QUrl::fromLocalFile(name);
int i = name.toStdString().find(".mp4");
if(i<0)
{
this->urlicon = QUrl::fromLocalFile(name);
}
else{
string temp = QFileInfo(name).fileName().toStdString();
int j = temp.find(".mp4");
//string str = "C:\\Video\\"+ temp.replace(j,4,".jpg");
string str = "C:\\Video\\"+ temp.replace(j,4,".jpg");
this->urlicon = QUrl::fromLocalFile(QString::fromStdString(str));
}
}
};
Q_DECLARE_METATYPE(File)
class FileModel : public QAbstractListModel
{
enum dashBoardRoles {
NameRole=Qt::UserRole+1,
URLRole,
ICONRole,
URLICONRole
};
Q_OBJECT
Q_PROPERTY(QString folder READ folder WRITE setFolder NOTIFY folderChanged)
Q_PROPERTY(QStringList nameFilters READ nameFilters WRITE setNameFilters NOTIFY nameFiltersChanged)
public:
FileModel(QObject *parent=Q_NULLPTR):QAbstractListModel(parent){
}
Q_INVOKABLE QVariant get(int index){
return QVariant::fromValue(m_all_dirs[index]);
}
int rowCount(const QModelIndex &parent=QModelIndex()) const{
Q_UNUSED(parent)
return m_all_dirs.count();
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const{
if(index.row()<0 && index.row()>= rowCount())
return QVariant();
File file = m_all_dirs[index.row()];
if(role == NameRole)
return file.name;
else if(role == URLRole)
return file.url;
else if(role == ICONRole)
return file.iconImg;
else if(role == URLICONRole)
return file.urlicon;
return QVariant();
}
QHash<int, QByteArray> roleNames() const {
QHash <int,QByteArray> roles;
roles [NameRole]="fileName";
roles [URLRole]="url";
roles [ICONRole]="icon";
roles [URLICONRole]="urlicon";
return roles;
}
QString folder() const{
return mFolder;
}
void setFolder(const QString &folder)
{
if(mFolder == folder)
return;
mFolder = folder;
emit folderChanged();
findFiles();
}
QStringList nameFilters() const{
return mNameFilters;
}
void setNameFilters(const QStringList &nameFilters){
if(mNameFilters == nameFilters)
return;
mNameFilters = nameFilters;
emit nameFiltersChanged();
findFiles();
}
signals:
void folderChanged();
void nameFiltersChanged();
private:
void findFiles(){
beginResetModel();
m_all_dirs.clear();
if(QDir(mFolder).exists()){
QFuture<QStringList> future = QtConcurrent::run([=]() {
QStringList files;
QDirIterator it(mFolder, mNameFilters, QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()){
files<<it.next();
}
ofstream myfile;
myfile.open (mFolder.toStdString()+"\\example.xml");
myfile <<"<files>"<<"\n";
for (int i = 0; i < files.size(); ++i)
myfile << "<"+ std::to_string(i) + ">"<< files.at(i).toStdString()<< "</"+ std::to_string(i) + ">" <<"\n";
//
myfile <<"</files>"<<"\n";
myfile.close();
for (int i = 0; i < files.size(); ++i){
int j = files.at(i).toStdString().find(".mp4");
if(j>0)
{
VideoCapture cap(files.at(i).toStdString());
Mat frame;
cap >> frame;
string str = QFileInfo(files.at(i)).fileName().toStdString();
int k = str.find(".mp4");
str = "C:\\Video\\"+ str.replace(k,4,".jpg");
imwrite(str,frame);
}
}
return files;
});
QStringList fullNames = future.result();
for(const QString& fullName: fullNames){
File file{fullName};
m_all_dirs << file;
}
//return 0;
}
endResetModel();
}
QString mFolder;
QList<File> m_all_dirs;
QStringList mNameFilters;
};
#endif // FILEMODEL_H
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "filemodel.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
qmlRegisterType<FileModel>("com.contentplayermod.filemodel", 1,0, "FileModel");
QQmlApplicationEngine engine;
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
main.qml
import QtQuick 2.9
import QtQuick.Controls 2.2
import QtMultimedia 5.8
import QtQuick.Layouts 1.3
import com.contentplayermod.filemodel 1.0
import QtQuick.Window 2.2
ApplicationWindow {
id:main_win
visible: true
width: 640
height: 480
title: qsTr("Tabs")
property int idx: 0
property bool isActive: true
Component.onCompleted: {
playTimer.start()
subWindow.show();
subWindow.requestActivate();
main_win.hide();
playMusic(grid_main.currentIndex)
}
GridView {
id:grid_main
anchors.fill: parent
cellWidth: 100; cellHeight: 100
focus: true
currentIndex: 0
model: FileModel{
id: myModel
folder: "c:\\test2"//"/mnt/sdcard/app_pictureFrameImage"//
nameFilters: ["*.jpg" ,"*.mp4"] //"*.mp4",
}
highlight: Rectangle { width: 80; height: 80; color: "lightsteelblue" }
delegate: Item {
width: 100; height: 100
Image {
id: myIcon
width: 30
height: 30
y: 20; anchors.horizontalCenter: parent.horizontalCenter
source: urlicon
}
Text {
anchors { top: myIcon.bottom; horizontalCenter: parent.horizontalCenter }
text: fileName
}
MouseArea {
anchors.fill: parent
onClicked: {
parent.GridView.view.currentIndex = index
}
}
}
Keys.onReturnPressed:{
playTimer.start()
subWindow.show();
subWindow.requestActivate();
playMusic(grid_main.currentIndex)
//subWindow.forceActiveFocus();
//event.accepted = true;
grid_main.focus = false;
}
/*
Keys.onPressed: {
if (event.key == 16777220) {//enter
playTimer.start()
subWindow.show();
subWindow.requestActivate();
playMusic(grid_main.currentIndex)
//subWindow.forceActiveFocus();
event.accepted = true;
grid_main.focus = false;
//main_win.hide();
}
}*/
}
Window {
id: subWindow
visible: true
width: 640
height: 480
MediaPlayer {
id: player
}
VideoOutput {
id: video
anchors.fill: parent
source: player
}
Item {
focus: true
Keys.onReturnPressed:{
subWindow.close()
grid_main.forceActiveFocus();
main_win.show();
}
}
}
function playMusic(index){
idx = index
//player.stop()
player.source = myModel.get(index).url
player.play()
}
Timer {
id: playTimer
interval: 2000
repeat: true
running: true
onTriggered: {
var source_name = player.source;
if(source_name.toString().indexOf(".jpg")>0 || source_name.toString().indexOf(".bmp")>0 || source_name.toString().indexOf(".png")>0){ //processing .jpg
if (idx + 1 < grid_main.count){
playMusic(idx + 1);
}else{
idx = 0;
playMusic(idx);
}
}
else if(source_name.toString().indexOf(".mp4")>0){ //processing .mp4
if (player.status == MediaPlayer.EndOfMedia){
if (idx + 1 < grid_main.count){
playMusic(idx + 1);
}else{
idx = 0;
playMusic(idx);
}
}
}
}
}
}

Related

SFML empty white window

i've an issue , im writing a menu to the maze game using SFML lib but something went wrong i wrote a code to redner a window and make a menu code. whem im clicking "Local windows debbuger" in vs2017 proggam opens a white window which shoud not suposed to happen. im pretty new at programing and i dont see all mistakes i made in this code but for me it's written right.
#pragma once
#include <SFML/Graphics.hpp>
#include <iostream>
using namespace std;
using namespace sf;
#define Max_main_menu 4
class Menu
{
public:
Menu(float width, float height);
void draw(RenderWindow& window);
void MoveUp();
void MoveDown();
int MenuPressed()
{
return MenuSelected;
}
~Menu();
private:
int MenuSelected;
Text menu[Max_main_menu];
};
menu.h
_____________________________
#include "Menu.h"
Menu::Menu(float widht, float height)
{
//Graj
menu[0].setFillColor(Color::White);
menu[0].setString("Graj");
menu[0].setCharacterSize(70);
menu[0].setPosition(600, 300);
menu[1].setFillColor(Color::White);
menu[1].setString("Opcje");
menu[1].setCharacterSize(60);
menu[1].setPosition(500, 300);
menu[2].setFillColor(Color::White);
menu[2].setString("Autorzy");
menu[2].setCharacterSize(60);
menu[2].setPosition(400, 300);
menu[3].setFillColor(Color::White);
menu[3].setString("Najlepszy Csas");
menu[3].setCharacterSize(60);
menu[3].setPosition(300, 300);
MenuSelected = -1;
}
Menu::~Menu()
{
}
void Menu::draw(RenderWindow& window) {
for (int i = 0; i < Max_main_menu; i++) {
window.draw(menu[i]);
}
}
void Menu::MoveUp() {
if (MenuSelected - 1 >= 0) {
menu[MenuSelected].setFillColor(Color::White);
MenuSelected--;
if (MenuSelected == -1) {
MenuSelected = 2;
}
menu[MenuSelected].setFillColor(Color::Blue);
}
}
void Menu::MoveDown()
{
if (MenuSelected + 1 <= Max_main_menu)
{
menu[MenuSelected].setFillColor(Color::White);
MenuSelected++;
if (MenuSelected == 4)
{
MenuSelected = 0;
}
menu[MenuSelected].setFillColor(Color::Blue);
}
}
menu.cpp
______________________________________________________
#include <SFML/Graphics.hpp>
#include "D:\Proejkt\Menu.h"
int main()
{
RenderWindow MENU(VideoMode(1280, 720), "Labirynt", Style::Default);
Menu menu(MENU.getSize().x, MENU.getSize().y);
while (MENU.isOpen())
{
Event event;
while (MENU.pollEvent(event))
{
if (event.type == Event::Closed)
{
MENU.close();
}
if (event.type == Event::KeyReleased)
{
if (event.key.code == Keyboard::Up)
{
menu.MoveUp();
break;
}
if (event.key.code == Keyboard::Down)
{
menu.MoveDown();
break;
}
if (event.key.code == Keyboard::Return)
{
RenderWindow Graj(VideoMode(1280, 720), "Labirynt");
RenderWindow Opcje(VideoMode(1280, 720), "Opcje");
RenderWindow Autorzy(VideoMode(1280, 720), "Autorzy");
RenderWindow NajlepszyCzas(VideoMode(1280, 720), "Najlepszy Czas");
int x = menu.MenuPressed();
if (x == 0)
{
while (Graj.isOpen())
{
Event aevent;
while (Graj.pollEvent(aevent))
{
if (aevent.type == Event::Closed)
{
Graj.close();
}
if (aevent.type == Event::KeyPressed)
{
if (aevent.key.code == Keyboard::Escape)
{
Graj.close();
}
}
}
}
Opcje.close();
Autorzy.close();
NajlepszyCzas.close();
Graj.clear();
Graj.display();
}
if (x == 1)
{
while (Opcje.isOpen())
{
Event aevent;
while (Opcje.pollEvent(aevent))
{
if (aevent.type == Event::Closed)
{
Opcje.close();
}
if (aevent.type == Event::KeyPressed)
{
if (aevent.key.code == Keyboard::Escape)
{
Opcje.close();
}
}
}
}
Graj.close();
Autorzy.close();
NajlepszyCzas.close();
Opcje.clear();
Opcje.display();
}
}
}
}
}
MENU.clear();
menu.draw(MENU);
MENU.display();
}
project.cpp
Your Main.clear(), Main.draw() and Main.display() is not in a while loop. Pls put them in a while loop.

Error: NED type 'myApp' could not be fully resolved due to a missing base type or interface?

In my project,
I implement a new class called myApp which inherits from ApplicationBase and UdpSocket classes. When I build my project I get no error, but when I debug C/C++ application with the IDE, it displays the first error in errors section. And the command line display the second error when I run make :
Code of myApp.ned, myApp.h and myApp.cc in what follows :
I did include inet library in project references, and I tried the solution posted in The following NED types could not be fully resolved, due to a missing base type or interface.
import inet.applications.contract.IApp;
simple myApp like IApp
{
parameters:
int localPort = default(-1); // local UDP port number (-1: use ephemeral port)
int destPort; // remote UDP port number
string packetName = default("myApp");
string interfaceTableModule; // The path to the InterfaceTable module
double helloInterval #unit(s) = default(5s); // how often hello messages should be sent out
volatile double sendInterval #unit(s); // should usually be a random value, e.g. exponential(1)
double startTime #unit(s) = default(this.sendInterval); // application start time (start of the first packet)
double stopTime #unit(s) = default(-1s); // time of finishing sending, -1s means forever
double maxVariance = default(1); // This is the maximum of a random value to determine when the first hello message will be sent out
volatile double broadcastDelay #unit(s) = default(uniform(0s,0.01s));
int timeToLive = default(-1); // if not -1, set the TTL (IPv4) or Hop Limit (IPv6) field of sent packets to this value
bool dontFragment = default(false); // if true, asks IP to not fragment the message during routing
int typeOfService = default(-1); // if not -1, set the ToS (IPv4) or Traffic Class (IPv6) field of sent packets to this value
string multicastInterface = default(""); // if not empty, set the multicast output interface option on the socket (interface name expected)
bool receiveBroadcast = default(false); // if true, makes the socket receive broadcast packets
bool joinLocalMulticastGroups = default(false); // if true, makes the socket receive packets from all multicast groups set on local interfaces
#class(myApp);
gates:
input socketIn #labels(UdpControlInfo/up);
output socketOut #labels(UdpControlInfo/down);
}
#ifndef MYAPP_H_
#define MYAPP_H_
#include "inet/common/INETDefs.h"
#include "inet/applications/base/ApplicationBase.h"
#include "inet/transportlayer/contract/udp/UdpSocket.h"
#include "inet/transportlayer/contract/udp/UdpControlInfo_m.h"
#include "inet/common/ModuleAccess.h"
#include "inet/common/TimeTag_m.h"
#include "inet/common/packet/Packet.h"
#include "inet/common/lifecycle/ModuleOperations.h"
#include "inet/common/IProtocolRegistrationListener.h"
#include "inet/common/ProtocolTag_m.h"
#include "inet/linklayer/common/InterfaceTag_m.h"
#include "inet/networklayer/contract/IInterfaceTable.h"
#include "inet/networklayer/contract/ipv4/Ipv4Address.h"
#include "inet/networklayer/ipv4/IIpv4RoutingTable.h"
#include "inet/networklayer/ipv4/Ipv4Header_m.h"
#include "inet/networklayer/ipv4/Ipv4InterfaceData.h"
#include "inet/networklayer/common/FragmentationTag_m.h"
#include "inet/networklayer/common/L3AddressResolver.h"
#include "HelloMsg_m.h"
#include "XedMsg_m.h"
#include <omnetpp.h>
#include <vector>
#include <random>
#include <algorithm>
using namespace omnetpp;
using namespace inet;
using namespace std;
class myApp : public ApplicationBase, public UdpSocket::ICallback
{
protected:
//enum SelfMsgKinds { START = 1, SEND, STOP };
int localPort = -1, destPort = -1;
bool dontFragment = false;
const char *packetName = nullptr;
simtime_t startTime;
simtime_t stopTime;
// state
UdpSocket socket;
cMessage *selfMsg = nullptr;
cModule *host = nullptr;
cMessage *event = nullptr;
cPar *broadcastDelay = nullptr;
unsigned int sequencenumber = 0;
simtime_t helloInterval;
IInterfaceTable *ift = nullptr;
InterfaceEntry *interface80211ptr = nullptr;
int interfaceId = -1;
list<L3Address> neighbors;
Ipv4Address source;
/********** XED **********/
class XED
{
public:
L3Address originatorAddr, destinationAddr;
unsigned int random;
XED(const L3Address& originatorAddr, const L3Address& destinationAddr, unsigned int random)
: originatorAddr(originatorAddr), destinationAddr(destinationAddr), random(random) {};
bool operator==(const XED& other) const
{
return this->originatorAddr == other.originatorAddr && this->destinationAddr == other.destinationAddr
&& this->random == other.random;
}
};
list<XED> lr,ls;
/********** MTLSD **********/
class MTLSD
{
public:
L3Address originatorAddr, destinationAddr;
char *position;
simtime_t time;
MTLSD(const L3Address& originatorAddr, const L3Address& destinationAddr, char *position, simtime_t time)
: originatorAddr(originatorAddr), destinationAddr(destinationAddr), position(position), time(time) {};
bool operator==(const MTLSD& other) const
{
return this->originatorAddr == other.originatorAddr && this->destinationAddr == other.destinationAddr
&& this->position == other.position && this->time == time;
}
};
protected:
virtual int numInitStages() const override { return NUM_INIT_STAGES; }
virtual void initialize(int stage) override;
virtual void handleMessageWhenUp(cMessage *msg) override;
void handleSelfMessage(cMessage *msg);
/*virtual void processStart();
virtual void processSend();
virtual void processStop();*/
// lifecycle
virtual void handleStartOperation(LifecycleOperation *operation) override { start(); }
virtual void handleStopOperation(LifecycleOperation *operation) override { stop(); }
virtual void handleCrashOperation(LifecycleOperation *operation) override { stop(); }
void start();
void stop();
virtual void socketDataArrived(UdpSocket *socket, Packet *packet) override;
virtual void socketErrorArrived(UdpSocket *socket, Indication *indication) override;
virtual void socketClosed(UdpSocket *socket) override;
//virtual void generateMTLSDPacket();
//virtual Packet *generateXEDPacket();
virtual double generateRandom();
public:
myApp() {}
~myApp();
};
#endif /* MYAPP_H_ */
#include "myApp.h"
#include "inet/applications/base/ApplicationPacket_m.h"
#include "inet/applications/udpapp/UdpBasicApp.h"
#include "inet/common/TagBase_m.h"
#include "inet/networklayer/common/L3AddressTag_m.h"
#include <iterator>
using namespace std;
Define_Module(myApp);
myApp::~myApp()
{
EV << "App destructor" << endl;
cancelAndDelete(selfMsg);
}
void myApp::initialize(int stage)
{
ApplicationBase::initialize(stage);
if (stage == INITSTAGE_LOCAL)
{
sequencenumber = 0;
ift = getModuleFromPar<IInterfaceTable>(par("interfaceTableModule"), this);
event = new cMessage("event");
broadcastDelay = &par("broadcastDelay");
helloInterval = par("helloInterval");
localPort = par("localPort");
destPort = par("destPort");
packetName = par("packetName");
startTime = par("startTime");
stopTime = par("stopTime");
}
else if (stage == INITSTAGE_ROUTING_PROTOCOLS)
{
registerService(Protocol::manet, nullptr, gate("socketIn"));
registerProtocol(Protocol::manet, gate("socketOut"), nullptr);
}
}
void myApp::handleSelfMessage(cMessage *msg)
{
if (msg == event)
{
auto hello = makeShared<HelloMsg>();
Ipv4Address source = (interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress());
hello->setChunkLength(b(128));
hello->setSrcAddress(source);
sequencenumber += 2;
hello->setSequencenumber(sequencenumber);
hello->setNextAddress(source);
hello->setHopdistance(1);
auto packet = new Packet("Hello", hello);
packet->addTagIfAbsent<L3AddressReq>()->setDestAddress(Ipv4Address(255, 255, 255, 255));
packet->addTagIfAbsent<L3AddressReq>()->setSrcAddress(source);
packet->addTagIfAbsent<InterfaceReq>()->setInterfaceId(interface80211ptr->getInterfaceId());
packet->addTagIfAbsent<PacketProtocolTag>()->setProtocol(&Protocol::manet);
packet->addTagIfAbsent<DispatchProtocolReq>()->setProtocol(&Protocol::ipv4);
send(packet, "socketOut");
packet = nullptr;
hello = nullptr;
scheduleAt(simTime()+helloInterval+broadcastDelay->doubleValue(), event);
}
}
void myApp::handleMessageWhenUp(cMessage *msg)
{
if (msg->isSelfMessage())
{
handleSelfMessage(msg);
}
else if (check_and_cast<Packet *>(msg)->getTag<PacketProtocolTag>()->getProtocol() == &Protocol::manet)
{
auto recHello = staticPtrCast<HelloMsg>(check_and_cast<Packet *>(msg)->peekData<HelloMsg>()->dupShared());
if (msg->arrivedOn("socketIn"))
{
bubble("Received hello message");
Ipv4Address source = interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress();
Ipv4Address src;
unsigned int msgsequencenumber;
int numHops;
Ipv4Address next;
src = recHello->getSrcAddress();
msgsequencenumber = recHello->getSequencenumber();
next = recHello->getNextAddress();
numHops = recHello->getHopdistance();
if (src == source)
{
EV_INFO << "Hello msg dropped. This message returned to the original creator.\n";
delete msg;
return;
}
else
{
neighbors.push_back(src);
/*list<XED>::iterator findIter = find(ls.begin()->destinationAddr, ls.end()->destinationAddr, src);
if (findIter != ls.end()->destinationAddr)
{
}*/
source = (interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress());
//socket.bind(source, localPort);
auto xed = makeShared<XedMsg>();
xed->setChunkLength(b(128)); ///size of XED message in bits
xed->setSrcAddress(source);
xed->setDstAddress(src);
double random = generateRandom();
xed->setRandom(random);
//XED item = XED(source, src, random);
//ls.push_back(item);
auto packet = new Packet("XED", xed);
packet->addTagIfAbsent<L3AddressReq>()->setDestAddress(src);
packet->addTagIfAbsent<L3AddressReq>()->setSrcAddress(source);
packet->addTagIfAbsent<InterfaceReq>()->setInterfaceId(interfaceId);
packet->addTagIfAbsent<PacketProtocolTag>()->setProtocol(&Protocol::ipv4);
packet->addTagIfAbsent<DispatchProtocolReq>()->setProtocol(&Protocol::ipv4);
socket.setOutputGate(gate("socketOut"));
socket.setCallback(this);
socket.bind(source, localPort);
//emit(packetSentSignal, packet);
socket.sendTo(packet, src, destPort);
//send(packet, "socketOut");
packet = nullptr;
xed = nullptr;
/*Ipv4Address source = (interface80211ptr->getProtocolData<Ipv4InterfaceData>()->getIPAddress());
EV << "I am node " << source << ", my neighbors are : " << endl;
list<L3Address>::iterator it;
for (it = neighbors.begin(); it != neighbors.end(); ++it)
{
EV << it. << endl;
}
for (auto const& i : neighbors)
{
EV << i.str() << endl;
}*/
EV << "I am your neighbor " << src.str();
}
delete msg;
}
else if (check_and_cast<Packet *>(msg)->getTag<PacketProtocolTag>()->getProtocol() == &Protocol::ipv4)
{
EV << "Xed message received" << endl;
//auto recXed = staticPtrCast<XedMsg>(check_and_cast<Packet *>(msg)->peekData<XedMsg>()->dupShared());
}
else
throw cRuntimeError("Message arrived on unknown gate %s", msg->getArrivalGate()->getName());
}
}
void myApp::start()
{
/*socket.setOutputGate(gate("socketOut"));
socket.setCallback(this);*/
int num_80211 = 0;
InterfaceEntry *ie;
InterfaceEntry *i_face;
const char *name;
for (int i = 0; i < ift->getNumInterfaces(); i++)
{
ie = ift->getInterface(i);
name = ie->getInterfaceName();
if (strstr(name, "wlan") != nullptr)
{
i_face = ie;
num_80211++;
interfaceId = i;
}
}
if (num_80211 == 1)
{
interface80211ptr = i_face;
interfaceId = interface80211ptr->getInterfaceId();
}
else
throw cRuntimeError("Node has found %i 80211 interfaces", num_80211);
scheduleAt(simTime() + uniform(0.0, par("maxVariance").doubleValue()), event);
}
double myApp::generateRandom()
{
double lower_bound = 10000;
double upper_bound = 100000;
uniform_real_distribution<double> unif(lower_bound,upper_bound);
default_random_engine re;
double a_random_double = unif(re);
return a_random_double;
}
void myApp::stop()
{
cancelEvent(event);
socket.close();
delayActiveOperationFinish(par("stopOperationTimeout"));
}
void myApp::socketDataArrived(UdpSocket *socket, Packet *packet)
{
emit(packetReceivedSignal, packet);
EV_INFO << "Received packet: " << UdpSocket::getReceivedPacketInfo(packet) << endl;
}
void myApp::socketErrorArrived(UdpSocket *socket, Indication *indication)
{
EV_WARN << "Ignoring UDP error report " << indication->getName() << endl;
delete indication;
}
void myApp::socketClosed(UdpSocket *socket)
{
if (operationalState == State::STOPPING_OPERATION)
startActiveOperationExtraTimeOrFinish(par("stopOperationExtraTime"));
}
Error: NED type 'myApp' could not be fully resolved due to a missing base type or interface, at /home/bocuhra/Downloads/omnetpp-5.4.1/samples/SaaS/myApp.ned:18
myApp.cc
HelloMsg_m.cc
XedMsg_m.cc
Creating executable: out/gcc-release//SaaS
/usr/bin/ld: cannot find -lINET
collect2: error: ld returned 1 exit status
Makefile:104: recipe for target 'out/gcc-release//SaaS' failed
make: *** [out/gcc-release//SaaS] Error 1
I did solve the problem by adding all ned files in my .ini file.
ned-path = .;../inet/src/inet

std::map<my_enum, base_class> insert error: base_class is an inaccessibile base of derived_class

This little program has to write an xml file.
Building the code I get the following error:
K:\Sergio\cpp\xml\sergio\cbp6s\main.cpp|32|error: 'base_tag' is an inaccessible base of 'tag'
In short, I have two classes derived from base_tag (xml_declaration and tag) and I want insert (or emplace) in a std::map some std::pair elements.
Building, the first insert works (std::pair<order::declaration, xml_declaration>), but the second fails (std::pair<order::root, tag_object>).
Between the object are derived from base_tag
Where am I wrong?
File tag.hpp :
#ifndef _TAG_HPP_
#define _TAG_HPP_
#include <string>
#include <vector>
#include <utility>
enum class tag_type
{
closing = -1,
autoclosed = 0,
opening = 1
};
using attribute = std::pair<std::string, std::string>;
class base_tag
{
public:
base_tag();
virtual ~base_tag();
virtual std::string get();
bool attribute_exists(std::string);
std::string get_attribute_value(std::string name);
bool add_attribute(std::string name, std::string value);
protected:
std::vector<std::pair<std::string, std::string>> _attributes;
};
// ------------------------------------------------------------
class xml_declaration : public base_tag
{
public:
xml_declaration();
~xml_declaration();
std::string get();
};
// ----------------------------------------------------------
class tag : base_tag
{
public:
tag(std::string name);
tag(std::string name, tag_type tt );
std::string get();
void set_ident(size_t ident);
protected:
std::string _name;
tag_type _tt;
};
#endif // _TAG_HPP_
File tag.cpp
#include "tag.hpp"
base_tag::base_tag()
{
}
base_tag::~base_tag()
{
_attributes.clear();
}
bool base_tag::attribute_exists(std::string name)
{
bool res = false;
for(auto & i : _attributes)
{
if (i.first == name)
res = true;
}
return res;
}
bool base_tag::add_attribute(std::string name, std::string value)
{
bool res = false;
if(!attribute_exists(name))
{
attribute a = std::make_pair(name, value);
_attributes.push_back(a);
res = true;
}
return res;
}
std::string base_tag::get()
{
return u8"<invalid_tag/>";
}
// -------------------------------------------------------
xml_declaration::xml_declaration(): base_tag()
{
add_attribute("version", "1.0");
add_attribute("encoding", "UTF-8");
add_attribute("standalone", "yes");
}
xml_declaration::~xml_declaration()
{ }
std::string xml_declaration::get()
{
std::string res = u8"<?xml";
for(auto & i : _attributes)
{
res.push_back(' ');
res += i.first;
res += u8"=\"";
res += i.second;
res += u8"\"";
}
res += u8" ?>";
return res;
}
// -------------------------------------------------------------
tag::tag(std::string name):base_tag(), _name(name)
{
_tt = tag_type::autoclosed;
}
tag::tag(std::string name, tag_type tt ): base_tag(), _name(name),
_tt(tt)
{ }
std::string tag::get()
{
std::string res = u8"";
bool with_attributes = !(_attributes.empty());
switch(_tt)
{
case tag_type::autoclosed : {
res = u8"<";
res += _name;
if(with_attributes)
{
for(auto & i : _attributes)
{
res.push_back(' ');
res += i.first;
res += u8"=\"";
res += i.second;
res += u8"\"";
}
};
res += u8"/>";
break;
}
case tag_type::opening : {
res = u8"<";
res += _name;
for(auto & i : _attributes)
{
res.push_back(' ');
res += i.first;
res += u8"=\"";
res += i.second;
res += u8"\"";
}
res += u8">";
break;
}
case tag_type::closing : {
res = u8"</";
res += _name;
res.push_back('>');
}
default : break;
}
return res;
}
File main.cpp
#include <iostream>
#include <map>
#include <utility>
#include "tag.hpp"
using namespace std;
enum class order
{
declaration = 0,
root = 1,
file_version = 4,
project = 10,
project_closing = 998,
root_closing = 1000
};
int main()
{
std::map<order, base_tag> tree;
xml_declaration decl;
cout << decl.get() << endl;
tag t1("project_file", tag_type::opening);
tag t2("project_file", tag_type::closing);
tree.insert(std::pair<order, base_tag>(order::declaration,
decl));
tree.insert(std::pair<order, base_tag>(order::root, t1));
tree.insert(std::pair<order, base_tag>(order::root, t2));
// tree.emplace(std::pair<order, base_tag>(order::root_closing, t1));
cout << tree.size() << endl;
return 0;
}
I'm using Code::Blocks with GCC 5.1.0 (on Windows 10).
As the error message says, tag inherits base_tag privately. If you change its headline into
class tag: public base_tag;
(same as your xml_declaration which inherits base_tag publicly) then it will officially be-a base tag.
A more serious problem is that you try to store instances of inherited classes in a container of a base class by value. What happens then is, objects get sliced and lose their whole derived functionality; you put an object of a derived class into a map, but you actually store an object of a based class in it (that's the reason some people tend to say polymorphic base classes should necessarily be abstract.) Use (smart) pointers or reference_wrappers as map's mapped type.

Error with the output of Camera Calibration OPENCV 3.2 with C++ Visual Studio 2015. Cant save output value

i am getting an error when using opencv camera calibration. When i debug my code, it just open the webcam not show the camera calibration value output in Folder Location.
i am using opencv 3.2 with VS 15
My code:
#include "opencv2/core.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/aruco.hpp"
#include "opencv2/calib3d.hpp"
#include <sstream>
#include <iostream>
#include <fstream>
using namespace std;
using namespace cv;
const float calibrationSquareDimension = 0.01905f; //meters
const float arucoSquareDimension = 0.1016f; //meters
const Size chessboardDimensions = Size(9,6);
void createArucoMarkers()
{
Mat outputMarker;
Ptr<aruco::Dictionary> markerDictionary = aruco::getPredefinedDictionary(aruco::PREDEFINED_DICTIONARY_NAME::DICT_4X4_50);
for (int i = 0; i < 50; i++)
{
aruco::drawMarker(markerDictionary, i, 500, outputMarker, 1);
ostringstream convert;
string imageName = "4x4Marker_";
convert << imageName << i << ".jpg";
imwrite(convert.str(), outputMarker);
}
}
void createKnownBoardPosition(Size boardsize, float squareEdgeLength, vector<Point3f>& corners)
{
for (int i = 0; i < boardsize.height; i++)
{
for (int j = 0; j < boardsize.width; j++)
{
corners.push_back(Point3f(j * squareEdgeLength, i * squareEdgeLength, 0.0f));
}
}
}
void getchessboardcorners(vector<Mat> images, vector<vector<Point2f>>& allfoundcorners, bool showresults = false)
{
for (vector<Mat>::iterator iter = images.begin(); iter != images.end(); iter++)
{
vector<Point2f> pointBuf;
bool found = findChessboardCorners(*iter, Size(9, 6), pointBuf, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE);
if (found)
{
allfoundcorners.push_back(pointBuf);
}
if (showresults)
{
drawChessboardCorners(*iter, Size(9, 6), pointBuf, found);
imshow("Looking for Corners", *iter);
waitKey(0);
}
}
}
void cameraCalibration(vector<Mat> calibrationImages, Size boardSize, float squareEdgeLength, Mat& cameraMatrix, Mat& distanceCoefficients)
{
vector<vector<Point2f>> checkerboardImageSpacePoints;
getchessboardcorners(calibrationImages, checkerboardImageSpacePoints, false);
vector<vector<Point3f>> worldSpaceCornerPoints(1);
createKnownBoardPosition(boardSize, squareEdgeLength, worldSpaceCornerPoints[0]);
worldSpaceCornerPoints.resize(checkerboardImageSpacePoints.size(), worldSpaceCornerPoints[0]);
vector<Mat> rVectors, tVectors;
distanceCoefficients = Mat::zeros(8, 1, CV_64F);
calibrateCamera(worldSpaceCornerPoints, checkerboardImageSpacePoints, boardSize, cameraMatrix, distanceCoefficients, rVectors, tVectors );
}
bool saveCameraCalibration(string name, Mat cameraMatrix, Mat distanceCoefficients)
{
ofstream outStream(name);
if (outStream)
{
uint16_t rows = cameraMatrix.rows;
uint16_t columns = cameraMatrix.cols;
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < columns; c++)
{
double value = cameraMatrix.at<double>(r, c);
outStream << value << endl;
}
}
rows = distanceCoefficients.rows;
columns = distanceCoefficients.cols;
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < columns; c++)
{
double value = cameraMatrix.at<double>(r, c);
outStream << value << endl;
}
}
outStream.close();
return true;
}
return false;
}
int main(int argv, char** argc)
{
Mat frame;
Mat drawToFrame;
Mat cameraMatrix = Mat::eye(3, 3, CV_64F);
Mat distanceCoefficients;
vector<Mat> savedImages;
vector<vector<Point2f>> markerCorners, rejectedCandidates;
VideoCapture vid(0);
if (!vid.isOpened())
{
return 0;
}
int framesPersecond = 20;
namedWindow("Webcam", CV_WINDOW_AUTOSIZE);
while (true)
{
if (!vid.read(frame))
break;
vector<Vec2f> foundPoints;
bool found = false;
found = findChessboardCorners(frame, chessboardDimensions, foundPoints, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE );
frame.copyTo(drawToFrame);
drawChessboardCorners(drawToFrame, chessboardDimensions, foundPoints, found);
if (found)
imshow("Webcam", drawToFrame);
else
imshow("Webcam", frame);
char character = waitKey(1000 / framesPersecond);
switch (character)
{
case ' ':
//saving image
if(found)
{
Mat temp;
frame.copyTo(temp);
savedImages.push_back(temp);
}
break;
case 13:
//start calibration
if (savedImages.size() > 15)
{
cameraCalibration(savedImages, chessboardDimensions, calibrationSquareDimension, cameraMatrix, distanceCoefficients);
saveCameraCalibration("CameraCalibration", cameraMatrix, distanceCoefficients);
}
break;
case 27:
//exit
return 0;
break;
}
}
return 0;
}

SDL_types.h file not found using xcode

Getting this error when trying to use SDL_mixer on xcode 4.6...
SDL_types.h file not found.. in the SDL_mixer.h file
I am including all the correct files as far as I can tell and have included the frameworks (both SDL and SDL_mixer) to my /systems/library/frameworks folder and it compiles well until I add SDL_mixer.h to my project. What should I do?
Here is main.cpp
#include <SDL/SDL.h>
#include "SDLMain.h"
#include "SDL_mixer.h"
int main(int argc, char ** argv)
{
SDL_Init(SDL_INIT_EVERYTHING);
Mix_Chunk song;
//Initialize SDL_mixer
if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 )
{
return false;
}
song = Mix_LoadWAV("song.wav");
SDL_SetVideoMode(1000, 500, 32, SDL_SWSURFACE);
SDL_Event event;
bool done = false;
while(!done)
{
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
done = true;
}
if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym == SDLK_UP)
{
Mix_PlayChannel( -1, song, 0 );
}
}
}
}
SDL_Quit();
return 0;
}

Resources