Gtksourceviewmm syntax highlighting not working - c++

I'm trying to use the C++ wrapper gtksourceview, I made this a long time ago and I remember that it was working, but now everything works except the higlight syntax. And I'm not pretty sure what it is. I hope you can help me, I read a lot about this library on internet but I can find a solution. Here is a simple code. Thanks in advance.
#include "twindow.h"
#include <iostream>
TWindow::TWindow() {
add(m_SourceView);
m_SourceView.set_size_request(640, 480);
m_SourceView.set_show_line_numbers();
m_SourceView.set_tab_width(4);
m_SourceView.set_auto_indent();
m_SourceView.set_show_right_margin();
m_SourceView.set_right_margin_position(80);
m_SourceView.set_highlight_current_line();
m_SourceView.set_smart_home_end(gtksourceview::SOURCE_SMART_HOME_END_ALWAYS);
gtksourceview::init ();
Glib::RefPtr<gtksourceview::SourceBuffer> buffer = m_SourceView.get_source_buffer () ;
if (!buffer) {
std::cerr << "gtksourceview::SourceView::get_source_buffer () failed" << std::endl ;
}
buffer->begin_not_undoable_action();
buffer->set_text(Glib::file_get_contents("main.c"));
buffer->end_not_undoable_action();
buffer->set_highlight_syntax(true);
Glib::RefPtr<gtksourceview::SourceLanguageManager> language_manager = gtksourceview::SourceLanguageManager::create();
Glib::RefPtr<gtksourceview::SourceLanguage> language = gtksourceview::SourceLanguage::create();
language = language_manager->get_language("c");
buffer->set_language(language);
show_all_children();
}

So you want to use the c++ wrapper of gtksourceview, so I guess you want to use gtksourceviewmm.
Why you create the LanguageManager, you can use the default one.
If you using 3.2 of gtksourceviewmm, then look at the docs.
You should also check out this function.
So an example would look like;
Glib::ustring file_path = "/home/user/whatever/main.c";
Glib::RefPtr<Gsv::LanguageManager> language_manager = Gsv::LanguageManager::get_default();
Glib::RefPtr<Gsv::Language> language = language_manager->guess_language(file_path, Glib::ustring());
Another thing I want to mention is that you should create a buffer to show the content of the file, as in my projects I got a seg fault when I wanted to use get_source_buffer(), so it seems to be null by default.
Glib::RefPtr<Gsv::Buffer> buffer = Gsv::Buffer::create(language);
buffer->set_text(Glib::get_file_contents(file_path));
this->m_SourceView.set_source_buffer(buffer);

Related

Using Json.cpp in Cocos2dx v4

https://github.com/cocos2d/cocos2d-x/blob/v4/cocos/editor-support/spine/Json.cpp
I need help loading a .txt and pulling out some text using cocos for an old App. Can anyone work up a simple example?
The backstory is that I wrote a working app about 5-6 years ago when cocos used a different json library. They changed the library and I can't decipher the new one enough to get it working again. I am not a programmer, but made the app as a favor for a hospital. The json is used to switch between languages for the script. I don't really even know how to ask a technical question about the library. I know the code is all there, but I don't know how to make it work...
Thanks :)
cocos2dx v4 Json implementation
This is what I figured out eventually. Any improvements you can suggest are welcome.
I use this to read json-response from a translation api:
std::vector<char> * buffer = response->getResponseData();
char * concatenated = (char *) malloc(buffer->size() + 1);
std::string s2(buffer->begin(), buffer->end());
strcpy(concatenated, s2.c_str());
CCLOG ("DEBUG |%s|", concatenated);
Json * json = Json_create(concatenated);
Json *responseData = Json_getItem(json, "responseData");
const char * var22 = Json_getString(responseData, "translatedText", "default");
USED JSON response
{"responseData":
{"translatedText":"ni\u00f1o"}, .....
and copyed the old json.c and json.h in my classes dir.
static void readCurve (Json* frame, spCurveTimeline* timeline, int frameIndex) {
Json* curve = Json_getItem(frame, "curve");
if (!curve) return;
if (curve->type == Json_String && strcmp(curve->valueString, "stepped") == 0)
spCurveTimeline_setStepped(timeline, frameIndex);
else if (curve->type == Json_Array) {
Json* child0 = curve->child;
Json* child1 = child0->next;
Json* child2 = child1->next;
Json* child3 = child2->next;
spCurveTimeline_setCurve(timeline, frameIndex, child0->valueFloat, child1->valueFloat, child2->valueFloat,
child3->valueFloat);
}
}

How to transfer and parse snap graph from python to c++

Stanford SNAP is a well-known package for graph mining, and has both Python implementation and C++ implementation.
I have some code in python to do graph mining using SNAP. I also have a C++ function process the snap graph. Now I need to write a wrapper so that this C++ function can be invoked from Python.
The problem is that I don't know how to parse/dereference the snap graph object from Python to C++.
The python code looks like: (More explanations come after the code examples)
import my_module;
import snap;
G = snap.GenRndGnm(snap.PUNGraph, 100, 1000);
print(type(G));
A = my_module.CppFunction(G); # customized function
print(A);
The CPP wrapper my_module_in_cpp.cpp looks like:
// module name: my_module, defined in the setup file
// function to be called from python: CppFunction
#include <Python.h>
//#include "my_file.h" // can be ignored in this minimal working example.
#include "Snap.h"
#include <iostream>
static PyObject *My_moduleError;
// module_name_function, THE CORE FUNCTION OF THIS QUESTION
static PyObject *my_module_CppFunction(PyObject *self, PyObject *args) {
PUNGraph G_py;
int parseOK = PyArg_ParseTuple(args, "O", &G_py);
if (!parseOK) return NULL;
std::cout << "N: " << G_py->GetNodes() << ", E: " << G_py->GetEdges() << std::endl;
fflush(stdout);
if ((G_py->GetNodes()!=100)||(G_py->GetEdges()!=1000)) {
PyErr_SetString(My_moduleError, "Graph reference incorrect.");
return NULL;
}
PyObject *PList = PyList_New(0);
PyList_Append(PList,Py_BuildValue("i",G_py->GetNodes()));
PyList_Append(PList,Py_BuildValue("i",G_py->GetEdges()));
return PList;
}
// To register the core function to python
static PyMethodDef CppFunctionMethod[] = {
{"CppFunction", my_module_CppFunction, METH_VARARGS, "To call CppFunction in C++"},
{NULL,NULL,0,NULL}
};
extern "C" PyMODINIT_FUNC initmy_module(void) {
PyObject *m = Py_InitModule("my_module",CppFunctionMethod);
if (m==NULL) return;
My_moduleError = PyErr_NewException("my_module.error", NULL, NULL);
Py_INCREF(My_moduleError);
PyModule_AddObject(m, "error", My_moduleError);
}
I'm using Ubuntu, python-2.7. In case someone may want to re-produce the problem, the setup.py file is also provided.
from distutils.core import setup, Extension
module1 = Extension('my_module',\
include_dirs = ['/usr/include/python2.7/','/users/<my_local>/Snap-3.0/','/users/<my_local>/Snap-3.0/snap-core','/users/<my_local>/Snap-3.0/glib-core'],
library_dirs = ['/users/<my_local>/Snap-3.0/snap-core/'],
extra_objects = ['/users/<my_local>/Snap-3.0/snap-core/Snap.o'],
extra_compile_args=['-fopenmp','-std=c++11'],
extra_link_args=['-lgomp'],
sources = ['my_module_in_cpp.cpp'])
setup (name = 'NoPackageName', version = '0.1',\
description = 'No description.', ext_modules = [module1])
Every time I run the python code above, the error message "Graph reference incorrect." is displayed.
Apparently G_py->GetNodes() and G_py->GetEdges() cause the problem. This must result from G_py not pointing to the right address/in right format. I tried using TUNGraph in the cpp code as well, it still does not point to the correct address. Is there any way that the pointer in C++ can point to the correct address of the original C++ object?
Although in general it is hard to dereference a PythonObject from C++, but in this case I think it is doable since Snap-Python is also implemented in C++. We just need to unwrap its python wrapper. And the snap authors also provided the SWIG files.
Of course we can write the graph file in the disk, and read from that, but this will result in I/O and incur extra time consumption. And the snap-user-group does not have as much user traffic as stackoverflow.
BTW, there are networkx and stanford-nlp tags, but no stanford-snap or similar tag referring to that tool. Can someone create such a tag?

Can't assert facts in clips embedded application

I'm trying to assert a new fact in CLIPS in embedded application.
I tried two ways:
- The first using assert as in the example in page 74 in the advanced programming guide.
- The second way is using assert-string.
I tried the each way alone and also the two ways together.
I'm using RUN_TIME module. My code outputs the right constructs (defrules and deftemplates) but the new fact is not asserted. Only initial-fact is there. I don't know why!
Here is my code:
#include "clips.h"
int main()
{
void *theEnv, *newFact, *templatePtr;
DATA_OBJECT theValue;
extern void *InitCImage_1();
theEnv = InitCImage_1();
EnvReset(theEnv);
// One way
templatePtr = EnvFindDeftemplate(theEnv, "Navigation");
newFact = EnvCreateFact(theEnv, templatePtr);
if (newFact == NULL) return -1;
theValue.type = SYMBOL;
theValue.value = EnvAddSymbol(theEnv, "Auto");
EnvPutFactSlot(theEnv, newFact, "FlightStatus", &theValue);
EnvAssert(theEnv, newFact);
// The other way
EnvAssertString(theEnv, "(Navigation (FlightStatus Auto))");
EnvRun(theEnv,-1);
EnvListDeftemplates(theEnv, "stdout", NULL);
EnvListDefrules(theEnv, "stdout", NULL);
EnvListDeffacts(theEnv, "stdout", NULL);
}
What is wrong in my code?
Use:
EnvFacts(theEnv,"stdout",NULL,-1,-1,-1);
Rather than:
EnvListDeffacts(theEnv, "stdout", NULL);
Deffacts are constructs that define a list of facts to be asserted when a (reset) command is performed. There is a pre-defined initial-facts deffacts that asserts the (initial-fact) when a reset is performed. That's what you're seeing listed when you call EnvListDeffacts. You want to call EnvFacts instead to see the facts that have actually been asserted (whether created by a deffacts after a reset or directly using assert).

How to convert fs:path to variable

Ok, firstly, I'm new to this. So yell at me as much as you like, but try to be useful at the same time :)
So I'm attempting to build a plugin using C++ to find a log file, and upload to a FTP every few minutes. The idea is to allow administrators to see the logs without needing direct access to the server. The ftp was the easy bit of this, running #include <CkFtp2.h> to do most of this with ease. I then used fs::path to find the latest file edited. Which looked like this:
//finding the latest file
int FindFile() {
fs::path latest;
std::time_t latest_tm {};
for (auto&& entry : boost::make_iterator_range(fs::directory_iterator("."), {})) {
fs::path p = entry.path();
if (is_regular_file(p) && p.extension() == ".txt")
{
std::time_t timestamp = fs::last_write_time(p);
if (timestamp > latest_tm) {
latest = p;
latest_tm = timestamp;
}
}
}
}
I now want to define string localFilename = latest however I get error: no viable conversion from 'fs::path' to 'string. Could someone help me?
Check out my github here to see what I'm working on and how I want this to implement with the rest of the code: https://github.com/TGTGamer/sourcebansLogMonitoring/blob/master/SourcebansToFTP.sp
p.s. If i'm being stupid, tell me the answer then slap me round the face....

Create stored procedure from x++

Got myself into trouble today trying to create a stored procedure from ax.
Here is a simple example:
static void testProcedureCreation(Args _args)
{
MyParamsTable myParams;
SqlStatementExecutePermission perm;
str sqlStatement;
LogInProperty Lp = new LogInProperty();
OdbcConnection myConnection;
Statement myStatement;
ResultSet myResult;
str temp;
;
select myParams;
LP.setServer(myParams.Server);
LP.setDatabase(myParams.Database);
//Lp.setUsername("sa");
//Lp.setPassword("sa");
sqlStatement = #"create procedure testproc
as begin
print 'a'
end";
//sqlStatement = strFmt(sqlStatement, myStr);
info(sqlStatement);
perm = new SqlStatementExecutePermission(sqlStatement);
perm.assert();
try
{
myConnection = new OdbcConnection(LP);
}
catch
{
info("Check username/password.");
return;
}
myStatement = myConnection.createStatement();
myResult = myStatement.executeQuery(sqlStatement);
while (myResult.next())
{
temp = myResult.getString(1);
info(temp);
if (strScan(temp, 'Error', 1, strLen(temp)) > 0)
throw error(temp);
}
myStatement.close();
CodeAccessPermission::revertAssert();
}
To be honest, in my real example I am using BCP and some string concat with a lot of | ' and "".
Anyway, here is what I got:
For a couple of hours I kept changing and retrying a lot of things and, a good thought came into my mind.
"Let's try with a much easier example and check the results!"
OK, no luck, the results were the same, as you can see in the pic above.
But for no reason, I tried to :
exec testproc
in my ssms instance and to my surprise, it worked. My small procedure was there.
It would be so nice if someone could explain this behavior and maybe what should be the correct approach.
This Q/A should provide an answer.
How to get the results of a direct SQL call to a stored procedure?
executeQuery vs executeUpdate