g_main_context_invoke And to improve the performance - glib

There are X and Y.
X is a daemon.
Y is a so lib.
X call the function A in Y lib.
It takes long time to finish A function.
So X has big problem.
I want to improve it to make another thread... or etc..
(It's impossible to reduce time of A.)
A is
bool A (callback)
{
... /* some dbus init */
... /* some other job init */
...
g_main_context_invoke(NULL, _functionA, callback);
return true;
}
So I change it like below.
I make A1 function. And change X call the A1 function instead of A.
int A1(callback)
{
g_idle_add(A, callback);
return true;
}
Result is A doesn't finish.
I don't know why.. I assume because of "g_main_context_invoke(NULL, _functionA, callback);"
Is there any one to improve this problem ??

Related

Vaadin get/set cursor position / selection start/end in Textfield

I know there was in Vaadin7 (8) some methods the get / set the cursor position of the textfield from server side.
I'm using Vaadin Flow v21, but there are no such methods. How can I get/set the cursor position from server side synchronously? To set it seens to work fine using some javascript, but I cannot read the actual cursor position, since it is only going async. How to do it sync?
I try to read like this:
public int getSelectionStart() throws InterruptedException
{
Future<Integer> value = UI.getCurrent().getPage().executeJs(
"return $0.shadowRoot.querySelector('[part=\"value\"]').selectionStart;"
, getElement()).toCompletableFuture(Integer.class);
final int[] val = new int[1];
Thread t = new Thread(() ->
{
Integer result = null;
try
{
result = value.get();
}
catch (Exception e)
{
e.printStackTrace();
}
val[0] = result == null ? 0 : result;
});
t.start();
t.join();
return val[0];
};
But above method gives me exception, that the ongoing UI session request has not been closed yet, so basically it cannot execute the javascript, unless I end the request.
This is how I set cursor position, which seems to work since I don't want to get any return value back, so ending the request is going to execute the script and set the proper cursor position.
public void setSelectionStart(int pos)
{
UI.getCurrent().getPage().executeJs("$0.shadowRoot.querySelector('[part=\"value\"]').setSelectionRange($1, $1);", getElement(), pos);
}
Thanks for any help / suggestion!
I hope the documentation for RPC return values could help here: https://vaadin.com/docs/latest/flow/element-api/client-server-rpc/#return-values

What can be done by void functions in MQL4?

A question by an MQL4 newbie.
What are the limits of what a void function can do in MQL4?.
I mean what can be done by a void function code and what can not be done?.
"void" only means that there is no return value from such function. So "returning a value" can not be done by a void function.
Hope that help....
you can put everything in a void function that you can put in a double, int, string, bool, ... function. What changes is what type of variable the function returns.
For instance, the following int function returns the sum of two values.
int sum( int a, int b )
{
return( a + b );
}
you could turn this function into a void function and instead of returning the value, you can print the value to the console.
void printsum( int a, int b )
{
Print( a + b );
}
In your follow up answer you ask about creating a void function that does something to a moving average. The following void function will accept different periods as input and print the MA. The function can't directly return the value of anything ( unless you use global variables / pass variables by reference ), but it can still accept values and do stuff based on those values.
void PrintMA( int period )
{
Print( iMA( NULL, 0, period, 8, MODE_SMMA, PRICE_MEDIAN, 1 ) );
}
The int function in your follow up answer only ever returns 0, so you could swap it to a void function and remove return(0) and it will work as before. Just change the function name first as start is a function name you should avoid using.
If you read the compile log, you'll be able to see why your above answer won't compile.
The only thing a void function(...) cannot do is to ever participate in an MQL4 assignment statement, i.e.:
someVariable = aVoidDeclaredFUNCTION();
Except this, one can do literally everything imaginable.
How that can be useful?
void aVoidDeclaredFUNCTION( const int thisParameterWillNeverChangeItsVALUE,
int &thisParameterWillBeAbleToChangeVALUE
){...}
Using a technique to pass by-Value, resp. to pass by-reference ( &passVariableByREF ) , even a void function(...) can process and "return"-results, if it is not enough to cause some actions in the void function(...){...} body, per-se.
"Void" just means the function doesn't return anything. These are useful for segmenting any stand alone sections of code (to make the code more organized for example, or to prevent repeating code... etc).
See this short video (not made by me) on the topic: Void Functions

Is there a way in CppUtest that can call mock and real function at runtime in the same test file?

For example:
Production.cpp
int func1()
{
return 7;
}
void func2()
{
printf("func2");
}
void productionCode()
{
int x = func1();
if(x==7) func2();
}
TestProduction.cpp
int func1()
{
return mock().actualCall("func1").
returnIntValue();
}
void setExpFunc1(int x)
{
mock().expectOneCall("func1")
andReturnValue(x);
}
TEST(testGroupSample, testMockFunc1)
{
setExpFunc1(8);
// this will call mock func1()
productionCode();
}
TEST(testGroupSample, testRealFunc2)
{
// this will call real func1()
productionCode();
}
From my understanding, when func1() was mocked, there's no way to test the actual function.
Below sample code is just an idea on what I'm trying to do.
Because I have to test many functions that calls many functions inside.
Sometimes, I don't care on the actual result of those other function so I mocked it, but when I want to test the behavior of the real function when calling inside a function that I'm testing, I cannot do it since that function is already mocked.
Also I hope I can do this without modifying the production code, only the tests code.
No. You mocked using the linker, so, for the whole file context, the real functions do not exist.
You may achieve this by using function pointers (or std::function, …) to set the implementation used by productionCode() at runtime.
Pseudocode
int func1() { /* Production }
int func1_mock() { /* Mock */ }
std::function<int()> impl; // Use a function ptr for C
void productionCode()
{
int x = impl(); // Call current implementation
// ...
}
TEST(...)
{
impl = func1; // Use production code
productionCode();
impl = func1_mock; // Use mock instead
productionCode();
}

Controlling while loops in Dart

I am stuck trying to do something simple. I want to be able to count upwards until I click on the screen at which point i want the counting to stop. In reality the code itself will be carrying out complex AI calculations for a game, but first I want to understand how to control the while loop. In android this would be trivial.
Here is what my code looks like
bool OK = true;
main() async{
html.querySelector('#content').onMouseUp.listen((e){
OK = false;
});
await for(int i in naturals){
print(i);
await sleep();
}
}
Stream get naturals async* {
int k = 0; while (OK) { yield await k++; }
}
Future sleep() {
return new Future.delayed(const Duration(milliseconds: 1), () => "1");
}
I put the sleep() method in as a way to ensure that control is passed to the event loop.
Is it possible to control a while loop without the sleep() method?
update
Just enqueue to allow the event queue to process outstanding events without additional delay use
Future sleep() {
return new Future.delayed(Duration.ZERO);
}
original
JavaScript and therefore can't Dart have threads in the browser and you need to pass control back to the event queue to allow it to process other events like you do with sleep().
Another approach would be to use webworkers and run the heavy calculation in a background task (webworker) to keep the UI thread free to process user events. This way even additional CPU cores can be utilized which isn't possible when all code runs in the browsers UI thread.
I don't know how to create webworkers in Dart though except with Angular2 Dart Web workers in Angular 2 Dart where Angular does the initialization.
I don't think it's too difficult but I don't know any docs.
To provide a more general answer - instead of a loop, you want to schedule a sequence of future tasks that each executes one iteration or step of your AI code (or whatever background process you want to have running).
You can have the step task recursively schedule itself:
dynamic doSomething(_) {
print('Doing something ...');
if(!stop) {
new Future.delayed(delay, (){}).then(doSomething);
}
return null;
}
main() async {
doSomething(null);
}
Although I don't recommend doing this. It's awkward to control - the step code has to check a flag variable to see if it should continue or stop and it's free running.
Alternatively you could use a Timer:
void doSomething(Timer timer) {
print('Doing something ...');
}
main() async {
new Timer.periodic(delay, doSomething);
}
This is throttled at a constant rate and has a uniform time step, and is easier to stop (call cancel() on the timer).
Another approach might be to synchronize with the browser's draw refresh cycle by requesting future animation frames:
import 'dart:html';
doSomething(num delta) {
print('Doing something ...');
window.animationFrame.then(doSomething);
}
void main() {
window.animationFrame.then(doSomething);
}
Time steps are not constant but you get the time delta. The advantage of this approach is that animation frame futures will not be scheduled if the browser window is hidden.
See How do I drive an animation loop at 60fps with Dart?
Those are very simple examples. Setting up proper background processes for physics simulation and AI in web games is actually surprisingly (to me at least) non-trivial. Here are two resources I found helpful.
http://gameprogrammingpatterns.com/ - a nice free online book of game programming patterns. http://gameprogrammingpatterns.com/game-loop.html - chapter on game loops.
http://gafferongames.com/game-physics/fix-your-timestep/ - part of a sequence of articles on physics simulation in games.
Following all suggestions this is the code I have ended up with, putting the heavy lifting in a worker, with controllable stopping and starting. I have used simple counting to get this working, but this is being replaced with my complex AI game calculations.
This uses time slices of 100ms within a worker isolate, which can only be interrupted after it has finished the batch. This allows me complete freedom to have complex animations on the screen while all this hard work is being done.
import 'dart:html' as html;
import 'dart:isolate';
import 'dart:math';
SendPort worker;
bool working = false;
main() async{
await startWorker();
html.querySelector('#stage').onMouseUp.listen((e){
if(working)worker.send('stop');
else worker.send('go');
});
}
startWorker() async{
var response = new ReceivePort();
await Isolate.spawnUri(Uri.parse("worker.dart"), null ,response.sendPort)
.then((_) => response.listen((msg){
if(msg is SendPort) {
worker = msg;
}
else {
messageReceived(msg);
}
}));
}
messageReceived(String message){
switch (message){
case 'working': working = true;
break;
case 'idle': working = false;
break;
default : print(message);
break;
}
}
worker.dart
import 'dart:isolate';
import 'dart:async';
SendPort replyTo;
bool OK = false;
const timeSlice = 100;
main(List<String> args, SendPort reply) async{
var response = new ReceivePort();
reply.send(response.sendPort);
replyTo = reply;
response.listen((msg) => messageReceived(msg));
replyTo.send("Hello from worker. Click to start and stop me");
}
messageReceived(String message){
switch(message){
case 'stop':
replyTo.send('idle');
OK = false;
break;
case 'go':
replyTo.send('working');
go();
break;
}
}
go()async {
OK = true;
int i = 0;
batchJob(){
int startTime = new DateTime.now().millisecondsSinceEpoch;
int elapsed = 0;
while(elapsed < timeSlice){
i ++; // the central routine
elapsed = new DateTime.now().millisecondsSinceEpoch - startTime;
}
}
while(OK){
batchJob();
replyTo.send(i.toString());
await new Future.delayed(const Duration(milliseconds: 0), () {});
}
}

How do I implement the "game loop" in Erlang?

I want to implement a game loop (that is acting as a server) in Erlang, but I dont know how to deal with the lack of incrementing variables.
What I want to do, described in Java code:
class Game {
int posX, posY;
int wall = 10;
int roof = 20;
public void newPos(x,y) {
if(!collision(x,y)) {
posX = x;
posY = y;
}
}
public boolean collision(x,y) {
if(x == wall || y == roof) {
// The player hit the wall.
return true;
}
return false;
}
public sendStateToClient() {
// Send posX and posY back to client
}
public static void main(String[] args) {
// The game loop
while(true) {
// Send current state to the client
sendStateToClient();
// Some delay here...
}
}
}
If the client moves, then the newPos() function is called. This function changes some coordinate variables if a collision do not occur. The game loop is going on forever and is just sending the current state back to the client so that the client can paint it.
Now I want to implement this logic in Erlang but I dont know where to begin. I can't set the variables posX and posY in the same way as here... My only thaught is some kind of recursive loop where the coordinates is arguments, but I don't know if that is the right way to go either...
Your intuition is correct: a recursive loop with the state as a parameter is the standard Erlang approach.
This concept is often abstracted away by using one of the server behaviors in OTP.
Simple example, may contain errors:
game_loop(X, Y) ->
receive
{moveto, {NewX, NewY}} ->
notifyClient(NewX, NewY),
game_loop(NewX, NewY)
end.

Resources