clang-format: empty line before and after control statements - c++

Is there any possibility to achieve inserting an empty line before and after control statemets (for, if etc.)?
E.g. I have the following source code:
if(bCondition)
{
// some code
}
for(int i : vecOfInts)
{
// some code
}
if(bAnotherCondition)
{
// some code
}
and this is what I want:
if(bCondition)
{
// some code
}
for(int i : vecOfInts)
{
// some code
}
if(bAnotherCondition)
{
// some code
}

Reading the official documentation, https://clang.llvm.org/docs/ClangFormatStyleOptions.html , there seems to be no such option.

Related

How to create json using rapidjson::Writer without creating document in C++?

I am trying to create json using rapidjson::Writer without creating document but it just give json text but don't create full json output like below,
{ "data": { "dataIn": { "hello":"world", "t":true, "f":false }, "dataOut": { "n":null, "i":123, "pi":3.1416 } } }
On rapidjson documents as well not enough info given. Can please help with it. How I can achieve this?
On rapidjson documents as well not enough info given. Can please help with it. How I can achieve this? - That is not true if I correctly understood your intentions.
At RapidJSON:Sax look for paragraph Writer - example given there is almost the same as the one you're asking for.
I wrote It myself to check if it is working .. and it is:
#include <iostream>
#include <rapidjson/writer.h>
// {
// "data":
// {
// "dataIn":
// {
// "hello":"world",
// "t":true,
// "f":false
// },
// "dataOut":
// {
// "n":null,
// "i":123,
// "pi":3.1416
// }
// }
// }
int main(int argc, char** argv)
{
rapidjson::StringBuffer lStringBuffer;
rapidjson::Writer lWriter(lStringBuffer);
lWriter.StartObject();
lWriter.Key("data");
lWriter.StartObject();
lWriter.Key("dataIn");
lWriter.StartObject();
lWriter.Key("hello");
lWriter.String("world");
lWriter.Key("t");
lWriter.Bool(true);
lWriter.Key("f");
lWriter.Bool(false);
lWriter.EndObject();
lWriter.Key("dataOut");
lWriter.StartObject();
lWriter.Key("n");
lWriter.Null();
lWriter.Key("i");
lWriter.Int(123);
lWriter.Key("pi");
lWriter.Double(3.1416);
lWriter.EndObject();
lWriter.EndObject();
lWriter.EndObject();
std::cout << lStringBuffer.GetString() << std::endl;
return 0;
}
The output is:
{"data":{"dataIn":{"hello":"world","t":true,"f":false},"dataOut":{"n":null,"i":123,"pi":3.1416}}}
But if you want to get such a JSON string you might also use raw strings like:
std::string lRawString = R"(
{
"data":
{
"dataIn":
{
"hello":"world",
"t":true, "f":false
},
"dataOut":
{
"n":null,
"i":123,
"pi":3.1416
}
}
}
)";
and then pass it to rapidjson::Document:
rapidjson::Document lDocument;
lDocument.Parse(lRawString.c_str());

Why does this exception appears when reading a file, but not when storing in it?

I'm currently working on a project with MFC and I noticed something weird that apparently has been there for a couple of years. When I launch the .exe of the program, it will do n number of things including reading a .DAT file and storing it as well. If the file doesn't exists, the program will try to find it with no luck throwing this CFile exception: The file could not be located. Which is correct because it doesn't exists. I have to do some operations first to generate that file, the storing process works fine. When the file exists and I run the program again, it's supposed read the file but this CArchive exception shows up: Invalid file format. And I don't understand why.
This is the Serialize():
//Fruits.cpp
void CFruits::Serialize(CArchive &ar)
{
int nVersion = 0;
CObject::Serialize(ar);
ar.SerializeClass(GetRuntimeClass());
if(ar.IsStoring())
{
ar.Write(&m_bInit,sizeof(bool));
ar.Write(&m_bYummy,sizeof(bool));
ar.Write(&m_bAcid, sizeof(bool));
ar.Write(&m_bFresh,sizeof(bool));
...
...
...
ar<<m_cType;
ar<<m_cColour;
ar<<m_cFlavor;
ar<<m_cPrice;
ar<<m_cQuantity;
}
else
{
nVersion = ar.GetObjectSchema();
ar.Read(&m_bInit,sizeof(bool));
ar.Read(&m_bYummy,sizeof(bool));
ar.Read(&m_bAcid, sizeof(bool));
ar.Read(&m_bFresh,sizeof(bool));
...
...
...
if( nVersion >= 2 || nVersion < 0)
ar<<m_cType;
else
m_cType=0;
if (nVersion >= 3 || nVersion < 0)
ar<<m_cColour;
else
m_cColour=0;
if (nVersion >= 4 || nVersion < 0)
ar<<m_cFlavor;
else
ar<<m_cFlavor=0;
if( nVersion >= 5 || nVersion < 0)
{
ar<<m_cPrice;
ar<<m_cQuantity;
}
else
{
m_cPrice=0;
m_cQuantity=0;
}
}
m_oSales.Serialize(ar);
m_oAdmin.Serialize(ar);
...
...
}
IMPLEMENT_SERIAL(CVehiculo,CObject,VERSIONABLE_SCHEMA | 6)
This is the SerializeElements:
//Fruits.cpp
void AFXAPI SerializeElements(CArchive &ar,CFruits * fruits,int ncount)
{
try
{
for(cont=0;cont<ncount;cont++)
fruits[cont].Serialize(ar);
}
catch(CArchiveException *AE)
{
//Here it stores the exception in a Log. Exception 5
}
}
The serializeElements is used to store and read the file n times, as declared here in the header file of fruits:
//Fruits.h
class CFruits : public CObject
{
public:
CFruits();
CFruits(const CFruits &O);
virtual ~CFruits();
void operator = (const CFruits &O);
void Serialize(CArchive &ar);
protected:
DECLARE_SERIAL(CFruits)
};
void AFXAPI SerializeElements(CArchive &ar,CFruits * fruits,int ncount);
typedef CArray<CFruits, CFruitso&> TArrayFruits;
The values of this Array, and the methods used to call the serialize are defined here in my main function:
//main.h
#include "CFruits.h"
class CMain : public CDialog
{
// Construction
public:
enum T_Fruits { eFruitsOnLine, eFruitsIng, eFruitsTra, eFruitsAnt, eFruitsP3, eFruitsP2, eFruitsP1, eFruitsC1, eFruitsC0, eFruitsEscape, eFruitsVideo};
private:
void StoreFruits();
void ReadFruits();
The SerializeElements for-loop is supposed to run 11 times, but I noticed that it only does it 1 time, then the Schema version changes to -1, (originally 6 cause I managed to trace the value). This happens only when reading the file.
I've tried the following:
I can't use debug so I have to use Logs, I placed a Log after every sentence in the Serialize() function, I found what seems to be the issue, this line:
ar.SerializeClass(GetRuntimeClass());
I used a try-catch and found that when that sentence happens, it throws the exception so, it doesn't continue reading. That is the moment where the version changes to -1. I tried to change that to:
ar.SerializeClass(RUNTIME_CLASS(CFruits));
Is the same result, I've read many forums trying to find the answer but I can't seem to do so. I've read the documentation and I found this here:
https://learn.microsoft.com/en-us/cpp/mfc/reference/carchive-class?view=vs-2019#serializeclass
Like ReadClass, SerializeClass verifies that the archived class
information is compatible with your runtime class. If it is not
compatible, SerializeClass will throw a CArchiveException.
But it doesn't make sense to me, because it doesn't fail storing. Should I look into something else?
Thank you
EDIT:
I'm posting the Store and Read methods
void CMain::ReadFruits()
{
CString CSerror, sFileName;
CString sDebug;
try
{
sFileName.Format("FRUITS%03d.DAT",GetNumT());
CFile fFruitsTag(sFileName,CFile::modeRead);
CArchive ar(&fFruitsTag,CArchive::load);
m_vFruits.Serialize(ar);
ar.Close();
fFruitsTag.Close();
}
catch(CFileException *FE)
{
...
}
catch(CArchiveException *AE)
{
...
}
}
void CMain::StoreFruits()
{
CString CSerror, sFileName;
try
{
if(!m_bStoringFruits)
{
sFileName.Format("FRUITS%03d.DAT",GetNumT());
m_bStoringFruits=true;
CFile fFruitsTag(sFileName,CFile::modeCreate|CFile::modeWrite);
CArchive ar(&fFruitsTag,CArchive::store);
m_vFruits.Serialize(ar);
ar.Close();
fFruitsTag.Close();
m_bStoringFruits=false;
}
}
catch(CFileException *FE)
{
...
}
catch(CArchiveException *AE)
{
...
}
catch(CException *e)
{
...
}
}

How to fix scanner while error

Back again with CacheScript, this time an easier question.
Here is the problem code:
while (open.hasNext() == true) {
String code = open.nextLine();
if (code.equals("CacheScript")) {
JOptionPane.showMessageDialog(this, "Package Successfully Loaded.");
txtBar.setText("Cache Script 2014");
}
if (code.equals("cache.color.orange")) {
map.setBackground(Color.orange);
}
}
For some reason, when I run this, the scanner (open) does not follow through... How can I fix the while code so each line can be tested to see if it equals one of the commands?
Try this;
while (open.hasNext() == true) {
if (code.equals("CacheScript")) {
JOptionPane.showMessageDialog(this, "Package Successfully Loaded.");
txtBar.setText("Cache Script 2014");
}
if (code.equals("cache.color.orange")) {
map.setBackground(Color.orange);
}
String code = open.nextLine();
continue;
}

How to run code even when an exception happens

I have a code like this:
try
{
do_some_processing();
// Write Log to appropriate place.
}
catch
{
// add debug info to log
// Write Log to appropriate place.
processException();
}
As you can see I need to write log when there is an exception and when there is not.
Is there any way that I can do in one place? and not copy it twice?
as far as I know, finally is called after exception is processed and not before it. Am I right?
I'd use RAII idiom
class RaiiLogger {
public:
RaiiLogger() : exception_fired_(true) {}
void set_success() {
exception_fired_ = false;
}
~RaiiLogger() {
if (exception_fired_) {
// log it
} else {
// log it
}
}
private:
bool exception_fired_;
};
void do_work() {
RaiiLogger logger;
try {
// do some work
logger.set_success();
} catch(...) {
// handle exception
}
}
int main() {
// your code goes here
do_work();
return 0;
}
Just move it outside of the try-catch block:
try
{
do_some_processing();
}
catch
{
// add debug info to log
processException();
}
// Write Log to appropriate place.
How about:
try{
do_some_processing();
}catch{
// add debug info to log
processException();
}
// write log to appropriate place

Weka XRFFSaver including missing sparse values

I'm using the XRFFSaver class in the current weka dev version. I'm using xrff rather than arff as I have extremely sparse data and the specs here indicate that sparse instances are handled nicely and efficiently (i.e. not included in output).
However using XRFFSaver they are included in the output like this:
<value index="1" missing="yes"/>
<value index="2" missing="yes"/>
...
Which defeats the purpose of the whole exercise. Anyone know if this is operator error or will I need to write my own saver?
I had a quick look at the source and I could not find any way of toggling this behaviour in either XRFFSaver or XMLInstances, however it was a quick look.
tnx
I quickly hacked up a solution to this:
Note: This is in C# (I use weka through ikvm). However, this should be very simple for anyone to convert to Java.
Note2: The only important line is this one: if (sparse) continue which I also highlighted below with comments. Everything else is a straight copy of the weka source which I found through grepcode and google. Not even sure if its the latest version I copied so please use with discretion.
I also tested to ensure that the standard XRFFLoader handles this correctly and it appears it does.
Tnx
// Usage
var saver = new EfficientXRFFSaver();
saver.setCompressOutput(file.EndsWith(".gz"));
saver.setInstances(Instances);
saver.setFile(new java.io.File(file));
saver.writeBatch();
// Implementation
public class EfficientXRFFSaver : XRFFSaver
{
public override void resetOptions() {
base.resetOptions();
setFileExtension(getCompressOutput() ? XRFFLoader.FILE_EXTENSION_COMPRESSED : XRFFLoader.FILE_EXTENSION);
try { m_XMLInstances = new EfficientXMLInstances(); }
catch { m_XMLInstances = null; }
}
}
public class EfficientXMLInstances : XMLInstances
{
protected override void addInstance(Element parent, Instance inst) {
var node = m_Document.createElement(TAG_INSTANCE);
parent.appendChild(node);
var sparse = inst is SparseInstance;
if (sparse) { node.setAttribute(ATT_TYPE, VAL_SPARSE); }
if (inst.weight() != 1.0) { node.setAttribute(ATT_WEIGHT, Utils.doubleToString(inst.weight(), m_Precision)); }
for (var i = 0; i < inst.numValues(); i++) {
var index = inst.index(i);
var value = m_Document.createElement(TAG_VALUE);
if (inst.isMissing(index)) {
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!! IMPORTANT !!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// This line will not add this element if its missing and sparse.
if (sparse) continue;
value.setAttribute(ATT_MISSING, VAL_YES);
} else {
if (inst.attribute(index).isRelationValued()) {
var child = m_Document.createElement(TAG_INSTANCES);
value.appendChild(child);
for (var n = 0; n < inst.relationalValue(i).numInstances(); n++) {
addInstance(child, inst.relationalValue(i).instance(n));
}
} else {
value.appendChild(inst.attribute(index).type() == weka.core.Attribute.NUMERIC ?
m_Document.createTextNode(Utils.doubleToString(inst.value(index), m_Precision)) :
m_Document.createTextNode(validContent(inst.stringValue(index))));
}
}
node.appendChild(value);
if (sparse) { value.setAttribute(ATT_INDEX, "" + (index + 1)); }
}
}
}