Firebreath plugin, how to read <param > values - plugins

I want to read the <param> values of custom plugin
I could not find answer on the internet, what I found was:
https://github.com/firebreath/FireBreath/blob/master/src/NpapiCore/NpapiPlugin.cpp#L76
I see params are stored in pluginMain->setParams(paramList);
Can you point how can I access this paramList later? or pluginMain
Is there pluginMain->getParams()? I could not find reference
Nor I could locate the source for setParams().
The question is, how do I get that parameters from PluginWindowXXX or FB::NpapiPluginXXX ?
I exported m_npHost to PluginWindowXXX, set breakpoint in it with gdb but still no success.
All I can think of was:
(gdb) p ((FB::Npapi::NpapiBrowserHost)this->m_npHost)->GetValue
$17 = {NPError (const FB::Npapi::NpapiBrowserHost * const, NPNVariable, void *)} 0x7fe435adeff8 <FB::Npapi::NpapiBrowserHost::GetValue(NPNVariable, void*) const>
Obviously what I do is wrong but I am stuck,
I am passing this host from NpapiPluginX11.cpp
pluginWin->setHost(m_npHost);

taxilian's answer is the most correct one as always but I'll give a try. I'm reading params in my MyPluginAPI constructor.
MyPluginAPI::MyPluginAPI(const MyPluginPtr& plugin, const FB::BrowserHostPtr& host) : m_plugin(plugin), m_host(host)
{
string settings; //<param name="settings" value="{'foo':'bar'}">
settings = plugin->getParam("settings");
}

Inside your PluginCore-derived class, you can use either the getParam method or the getParamVariant method.
From the FireBreath Source:
boost::optional<std::string> PluginCore::getParam(const std::string& key) {
boost::optional<std::string> rval;
FB::VariantMap::const_iterator fnd = m_params.find(key.c_str());
if (fnd != m_params.end())
rval.reset(fnd->second.convert_cast<std::string>());
return rval;
}
FB::variant FB::PluginCore::getParamVariant( const std::string& key )
{
FB::VariantMap::const_iterator fnd = m_params.find(key.c_str());
if (fnd != m_params.end())
return fnd->second;
return FB::variant();
}
So if it's for sure a string (which it pretty much is, unless it starts with on, in which case it might have been converted to a referenced function), you can use:
boost::optional<std::string> mystr = getParam("mystr");
if (mystr) {
call_fn_with_string(*mystr);
}
Alternately, you can get it as a variant and convert it:
FB::variant mystrVal = getParamVariant("mystr");
try {
call_fn_with_string(mystrVal.convert_cast<std::string>());
} catch (FB::bad_variant_cast &err) {
// What to do if the cast to string fails
}

Related

local rest api controller does not receive data from repository function-call

Our VS-2022 development project is Blazor WASM Core-6 with local REST-API for data. Using Postman, my testing is not getting data from the controller call to a repository function -- using breakpoints and local debugging -- as one would expect.
The repository function return statement is return Ok(vehicleTrips);. The IEnumerable vehicleTrips data variable contains the correct four records as expected from the DB fetch.
From the controller the call to the repository function is:
var result = (await motripRepository.GetMOTripsByDateRange((int)eModelType.Vehicle, pVehicleList, pDateFrom, pDateTo)!)!;
The controller function signature is:
[HttpGet("byDateRange/{pVehicleList}/{pDateFrom}/{pDateTo}")]
[ActionName(nameof(GetVehicleMOTripsByDateRange))]
public async Task<ActionResult<IEnumerable<MOTRIP>>> GetVehicleMOTripsByDateRange([FromRoute] string pVehicleList, [FromRoute] string pDateFrom, [FromRoute] string pDateTo) {
This is my problem. The result return value from the repository has a return.Value of null -- NOT four trip records as we should.
Additionally, the VS-Studio's 'local'-debugger shows that there are other properties of return such as .Return and .Return.Value.Count as 4 (four).
My question is "what could be causing this"? All of my other rest-api calls and controller calls with Postman work correctly as one would expect.
Did I select the wrong type of "controller" from Visual-Studio? I am not experienced at all in coding classic MVC web-applications. VS-Blazor offer a number of controller-types. In the past, I "copied" a working controller and "changed the code" for a different "model".
Your assistance is welcome and appreciated. Thanks...John
I found out what actually happened to cause the result.Value is null and had nothing to do with the controller-type -- it was in the interpretation of the return value from the repository function.
I found an SO link Get a Value from ActionResult<object> in a ASP.Net Core API Method that explains how to respond to a ActionResult<objecttype> return value in the reply/answer section with the word "actual" is first defined. You will see this word "actual" in my revised code below.
My revised code is posted here with comments both inside the code section and below the code section. My comment inside the code begins with "<==" with text following until "==>"
// Initialize.
MOTRIP emptyMoTrip = new MOTRIP();
MOTRIP? resultMoTrip = new MOTRIP();
IEnumerable<MOTRIP> allTrips = Enumerable.Empty<MOTRIP>();
int daysPrevious = (int)(pTripType == eTripType.Any ? eDateRangeOffset.Week : eDateRangeOffset.Month);
// convert DateRangeOffset to 'dateonly' values.
DateOnly dtTo = DateOnly.FromDateTime( DateTime.Today);
DateOnly dtFrom = dtTo.AddDays(daysPrevious);
// Fetch the vehicle trips by date-range.
var result = await GetVehicleMOTripsByDateRange(UID_Vehicle.ToString(), dtFrom.ToString(), dtTo.ToString());
if ((result.Result as OkObjectResult) is null) { **<== this is the fix from the SO link.==>**
return StatusCode(204, emptyMoTrip);
}
var statusCode = (result.Result as OkObjectResult)!.StatusCode;
if (statusCode==204) {
return StatusCode(204, emptyMoTrip);
}
**<== this next section allows code to get the result's DATA for further processing.==>**
var actual = (result.Result as OkObjectResult)!.Value as IEnumerable<MOTRIP>;
allTrips = (IEnumerable<MOTRIP>)actual!;
if ((allTrips is not null) && (!allTrips.Any())) {
return StatusCode(204, emptyMoTrip);
}
<== this next section continues with business-logic related to the result-DATA.==>
if (allTrips is not null && allTrips.Any()) {
switch (blah-blah-blah) {
**<== the remainder of business logic is not shown as irrelevant to the "fix".==>**
Please use browser search for "<==" to find my code-comments.
Please use browser search for "actual" and "OkObjectResult" to see the relevant code fix sentences.

store data persistent for learn app with unity

I'm currently working on a language learn app with unity. I want to implement that when you guessed a work (e.g. a number) incorrect, you need to guess the word again in the next iteration. I thought of a way that you store for each word in every play mode a value between +10 to -10 and when an item has a big negative number the word occurrence more often than if it has a big positiv number.
My Problem is that I don't know how to store the data properly. PlayerPrefs are too inconvenient for this problem, and I don't know how to modify a JSON file properly.
Currently, I store the data for the items in a class.
Maybe you could have a structure like:
Numbers
write
zero: -5
one: +3
match
zero: +5
one: +4
Alphabet
write:
A: -10
match:
A: +5
Does anyone have an idea how to solve this problem?
One of the best JSON serialization libraries is Newtonsoft.Json.
You can use your class and serialize an object to JSON object, and then save it as a string to file.
public static string Serialize(object obj)
{
var settings = new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore
};
return JsonConvert.SerializeObject(obj, settings);
}
After that you can save it to file in the Application.persistentDataPath directory.
var text = Serialize(data);
var tmpFilePath = Path.Combine(Application.persistentDataPath, "filename");
Directory.CreateDirectory(Path.GetDirectoryName(tmpFilePath));
if (File.Exists(tmpFilePath))
{
File.Delete(tmpFilePath);
}
File.WriteAllText(tmpFilePath, text);
After that you can read the file at any time using File.ReadAllText and deserialize it to an object.
public static T Deserialize<T>(string text)
{
var settings = new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore
};
try
{
var result = JsonConvert.DeserializeObject<T>(text, settings);
return result ?? default;
}
catch (Exception e)
{
Debug.Log(e);
}
return default;
}
T result = default;
try
{
if (File.Exists(path))
{
var text = File.ReadAllText(path);
result = Deserialize<T>(text);
}
}
catch (Exception e)
{
Debug.LogException(e);
}
return result;
Unfortunately, there is no easy way to store data persistently between play sessions in Unity. PlayerPrefs and creating your own JSON file are the simplest ways of doing this.
The good news is that JSON files are quite easy to make and modify, thanks to the builtin JSONUtility Unity provides.
If you make a separate class or struct to hold your scores, give that clas a [Serializable] tag and keep a reference to that in your current setup (which is probably a MonoBehaviour).
You can use the File class (specifically File.CreateText() and File.OpenText()) to write to/read from a file. If you do this every time a value changes, you should end up with persistent saved data across multiple play sessions.

How to select symbols onWorkspaceSymbol

I am developing an extension for visual studio code using language server protocol, and I am including the support for "Go to symbol in workspace". My problem is that I don't know how to select the matches...
Actually I use this function I wrote:
function IsInside(word1, word2)
{
var ret = "";
var i1 = 0;
var lenMatch =0, maxLenMatch = 0, minLenMatch = word1.length;
for(var i2=0;i2<word2.length;i2++)
{
if(word1[i1]==word2[i2])
{
lenMatch++;
if(lenMatch>maxLenMatch) maxLenMatch = lenMatch;
ret+=word1[i1];
i1++;
if(i1==word1.length)
{
if(lenMatch<minLenMatch) minLenMatch = lenMatch;
// Trying to filter like VSCode does.
return maxLenMatch>=word1.length/2 && minLenMatch>=2? ret : undefined;
}
} else
{
ret+="Z";
if(lenMatch>0 && lenMatch<minLenMatch)
minLenMatch = lenMatch;
lenMatch=0;
}
}
return undefined;
}
That return the sortText if the word1 is inside the word2, undefined otherwise. My problem are cases like this:
My algorithm see that 'aller' is inside CallServer, but the interface does not mark it like expected.
There is a library or something that I must use for this? the code of VSCode is big and complex and I don't know where start looking for this information...
VSCode's API docs for provideWorkspaceSymbols() provide the following guidance (which I don't think your example violates):
The query-parameter should be interpreted in a relaxed way as the editor will apply its own highlighting and scoring on the results. A good rule of thumb is to match case-insensitive and to simply check that the characters of query appear in their order in a candidate symbol. Don't use prefix, substring, or similar strict matching.
These docs were added in response to this discussion, where somebody had very much the same issue as you.
Having a brief look at VSCode sources, internally it seems to use filters.matchFuzzy2() for the highlighting (see here and here). I don't think it's exposed in the API, so you would probably have to copy it if you wanted the behavior to match exactly.

In Visual Studio, How to prevent my useful function being optimized by the compiler?

I did a template string operation class which can operate std::string and MFC CString.
It workes fine on the Debug version.
It does work on the Release version.
By my investigation, I found that at least one useful function is optimized.
checkChars is optimized which is supposed to be called in the split. (checkChars isn't being called.)
static bool checkChars(const TCHARTYPE& c, const TCHARTYPE* chrs)
{
for ( ;*chrs ;chrs++)
{
if (c == *chrs)
{
return true;
}
}
return false;
}
void split(const TSTRING& s, vector<TSTRING>& v, const TCHARTYPE* separator, bool bKeepEmptyParts = false)
{
...
//here at() is called, but checkChars isn't
if (checkChars(at(s, i), separator))
...
}
The VS Optimization is
Maximize Speed (/O2)
. I found use
Custom
can prevent the Optimization of my useful function.
But I want to know why, and I don't want to change the project settings, Can I just modify my code to make it work?
Edit:
After a long time, I realized that the real problem is not Optimization, is that "at()" fuction doesn't return the expected char reference. TSTRING here is CString MFC which does not return a TCHAR reference. The compiler found this would not work, so "optimized" it.
is there any way to disable compiler optimisation for a specific line of code?
http://msdn.microsoft.com/en-us/library/chh3fb0k.aspx
#pragma optimize( "", off )
.
.
.
#pragma optimize( "", on )

Meteor.js : How to run check() when arguments are Mongodb ObjectId's?

In some of my Meteor methods, I'm sending Mongodb ObjectId's from the client as arguments. I'd like to run these through Meteor's check() system but I can't seem to find anything that matches successfully with them.
I've tried
var someObjectId = Meteor.Collection.ObjectId();
check(someObjectId, Meteor.Collection.ObjectId()) // fails
check(someObjectId, { _str : String }) //fails
check(someObjectId, String) //fails
any help much appreciated !
Instead of:
check(someObjectId, Meteor.Collection.ObjectID());
Try without the parentheses:
check(someObjectId, Meteor.Collection.ObjectID);
Edit-
Note that the error message for this check isn't ideal.
check({}, Meteor.Collection.ObjectID);
// Error: Match error: Expected
You could assume the message should be something like
// Error: Match error: Expected ObjectId, got object
You can see why this happens in this snippet from the check package.
https://github.com/meteor/meteor/blob/devel/packages/check/match.js
if (pattern instanceof Function) {
if (value instanceof pattern)
return;
// XXX what if .name isn't defined
throw new Match.Error("Expected " + pattern.name);
}
Meteor.Collection.ObjectID does not have name property.
As an alternative solution, you could simply pass the hexadecimal string as an argument instead of the ObjectID.
var idValidator = Match.Where(function (id) {
check(id, String);
return /[0-9a-fA-F]{24}/.test(id);
});
check(new Meteor.Collection.ObjectID()._str, idValidator);
// success
check('', idValidator);
// Error: Match error: Failed Match.Where validation
check({}, idValidator);
// Error: Match error: Expected string, got object
check([], idValidator);
// Error: Match error: Expected string, got object <--- bug? I expect array
Note, this regular expression is pulled from here.
https://github.com/mongodb/js-bson/blob/master/lib/bson/objectid.js
You should use following to generate a random ObjectID:
var someObjectId = new Meteor.Collection.ObjectID();
As Cuberto said, you can then check it by Meteor.Collection.ObjectID:
check(someObjectId, Meteor.Collection.ObjectID)
Normally when using check() you're not in a position to generate a new Meteor _id. Here's an alternative using Match.check()
First extend the Match object with:
Match._id = Match.Where(function (id) {
check(id, String);
return /[a-zA-Z0-9]{17,17}/.test(id);
});
This is useful because you're likely to be checking _ids in many of your methods.
Now simply:
check(_id,Match._id);
more on this pattern
Complete answer to the original question:
First, define a matcher for a single object in your array of arguments:
Match._id = Match.Where(function (id) {
check(id, String);
return /[a-zA-Z0-9]{17,17}/.test(id);
});
Then you can call:
check(MyArrayOfArguments, [Match._id])