When annotation an observer method with AFTER_SUCCESS, the events are received in the reverse order they actually have been fired during the transaction.
Example pseudo code:
#Transactional
void test(){
pushEvent.fire( new PushEvent(10) );
pushEvent.fire( new PushEvent(20) );
pushEvent.fire( new PushEvent(30) );
}
Observer:
void onPushEvent( #Observes( during = TransactionPhase.AFTER_SUCCESS ) PushEvent event ){
System.out.println(event.getValue())
}
Unexpected, but observed result:
30
20
10
Can this be changed?
Fixed this in my project with a thread-local buffer of events which gets flushed on AFTER_SUCCESS and replays the events in the order they appeared in first place
ThreadLocal<List<PushEvent>> threadEventBufferHolder = ThreadLocal.withInitial( ArrayList::new );
void onPushEvent( #Observes( during = TransactionPhase.IN_PROGRESS ) PushEvent event ){
threadEventBufferHolder.get().add( event );
}
void onPushEventFailure( #Observes( during = TransactionPhase.AFTER_FAILURE ) PushEvent event ){
buffer.clear();
}
void onPushEventCommit( #Observes( during = TransactionPhase.AFTER_SUCCESS ) PushEvent event ){
List<PushEvent> buffer = threadEventBufferHolder.get();
buffer.forEach( this::doPrintlnValue );
buffer.clear();
}
Unrelated code removed for easier reading
Related
I have a listener that captures the location every 10 seconds or 100 meters or so. I am using
xam.plugin.geolocator
to implement the listener. My problem is the location listener is not working(meaning the changes in location were not capturing or saved in the location cache) when my application is minimized or the application is opened but the phone is locked.
Here is my code:
async Task StartListening()
{
if (!CrossGeolocator.Current.IsListening)
{
var defaultgpsaccuracy = Convert.ToDouble(Preferences.Get("gpsaccuracy", String.Empty, "private_prefs"));
await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(10), defaultgpsaccuracy, false, new Plugin.Geolocator.Abstractions.ListenerSettings
{
ActivityType = Plugin.Geolocator.Abstractions.ActivityType.Other,
AllowBackgroundUpdates = true,
DeferLocationUpdates = true,
DeferralDistanceMeters = 1,
DeferralTime = TimeSpan.FromSeconds(1),
ListenForSignificantChanges = true,
PauseLocationUpdatesAutomatically = false
});
}
}
I place this code in the first view/page of my application in my login.xaml.cs
Here are my questions:
How can I implement the listener properly so that when the application minimized or the phone/device is locked it still captures the changes of location?
What is the best GPS settings I need to capture the changes in location faster and accurately? Right now, my current settings are capturing the location every 10 seconds or 100 meters.
First you need to init StartListening then create event handlers for position changes and error handling
public Position CurrentPosition { get; set; }
public event EventHandler PositionChanged;
Don't forget to init it in your constructor :
CurrentPosition = new Position();
await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(20), 10, true);
CrossGeolocator.Current.PositionChanged += PositionChanging;
CrossGeolocator.Current.PositionError += PositionError;
Functions :
`private void PositionChanging(object sender, PositionEventArgs e)
{
CurrentPosition = e.Position;
if (PositionChanged != null)
{
PositionChanged(this, null);
}
}
private void PositionError(object sender, PositionErrorEventArgs e)
{
Debug.WriteLine(e.Error);
}`
You can now call PositionChanged when ever you want the latest position
Don't forget to stop listening :
`public async Task StopListeningAsync()
{
if (!CrossGeolocator.Current.IsListening)
return;
await CrossGeolocator.Current.StopListeningAsync();
CrossGeolocator.Current.PositionChanged -= PositionChanging;
CrossGeolocator.Current.PositionError -= PositionError;
}`
I have a one fragment activity and one background service which implements SensorEventListener. service is working perfectly even when the screen is off and calls my fragment activity after a right argument. the only problem is when i disconnect my wearable from debugger or cellphone (can not see the logcat anymore). the service stops working! and the service wont trigger the fragment activity anymore. any help could be lifesaver. Thanx in advance
public class myService extends Service implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
...
public int onStartCommand(Intent intent, int flags, int startId) {
//USING SENSOR MANAGER
mSensorManager = mSensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, mSensorManager.SENSOR_DELAY_FASTEST);
return START_STICKY;
}
...
public void onSensorChanged(SensorEvent event) {
...
if(event.sensor.getStringType().equals(Sensor.STRING_TYPE_ACCELEROMETER)) {
//CONVERTING VALUES
mXValuesAcc = (float)(((int)(event.values[0] * 100)) / 100.0);
mYValuesAcc = (float)(((int)(event.values[1] * 100)) / 100.0);
mZValuesAcc = (float)(((int)(event.values[2] * 100)) / 100.0);
//ADDING THREE ACCELEROMETER DATA TOGETEHR
sumXYZ = Math.abs(mXValuesAcc) + Math.abs(mYValuesAcc) + Math.abs(mZValuesAcc);
//MAKING READY TO CALL THE MAIN FRAGMENT ACTIVITY
Intent MainIntent = new Intent(this, myActivity.class);
MainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//SENDING THE sumXYZ VALUE TO THE winLooseState FUNCTION
WinLooseState winLooseState = myAlgo(sumXYZ, eventTimestamp);
//AS A RESULT STATE OF EVENT WILL BE DEFINED
switch (winLooseState) {
case WIN:
...
break;
case LOOSE:
//MAKING PowerManager READY
PowerManager TempPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock TempWakeLock = TempPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "TempWakeLock");
// LCD ON
TempWakeLock.acquire();
//DATA TO SEND TO myActivity
MainIntent.putExtra(...);
//CALLING myActivity
startActivity(MainIntent);
// LCD off
TempWakeLock.release();
break;
case DRAW:
...
}
}
}
}
Sorry for the late answer.
so the solution is nothing more than the second wakelock() actually. as i found the solution i was beating my self for a week(inside my own head). it was a stupid mistake but so sweet when it was solved :)
so :
#Override
public void onCreate() {
PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "systemService");
}
and under onStartCommand(..)
just add:
mWakelock.acquire();
so at the end two wakelocks
hope it helps!
In MQL4, I know how to set stopLoss and takeProfit.
However, I would like to do something else when such events actually take place.
Is there any event listener associated with such?
Unfortunately, there are no trade-events in MQL4.
However, it can be simulated as such ( logic-only-code, may not compile ):
#property copyright "No copyright, can be used freely, Joseph Lee"
#property link "https://www.facebook.com/joseph.fhlee"
int vaiTicketList[];
int start() {
int viIndex;
// -----------------------------------------------------------
// EVENT CHECK SECTION:
// Check vaiTicketList (populated in the previous cycle) to see if
// each of the (previously) open ticket is still currently open.
// -----------------------------------------------------------
for( viIndex=0; viIndex<ArrayRange(vaiTicketList,0); viIndex++) {
// Check if Ticket which was previously opened in the last
// cycle is no longer open now.
if(!OrderSelect( vaiTicketList[viIndex], SELECT_BY_TICKET ) ) {
// -----------------------------------
// EVENT CATEGORIZATION:
// -----------------------------------
// Handle possible events here:
// -- Close event: (OrderSelect( ticket, SELECT_BY_TICKET, MODE_HISTORY) == true)
if( OrderSelect(vaiTicketList[viIndex], SELECT_BY_TICKET, MODE_HISTORY) )
eventTrade_Closed( vaiTicketList[viIndex] );
// -- StopLoss ( Buy: When OrderClosePrice() <= OrderStopLoss(),
// Sell: When OrderClosePrice() >= OrderStopLoss() )
// -- TakeProfit (Buy: When OrderClosePrice() >= OrderTakeProfit(),
// Sell: When OrderClosePrice() <= OrderTakeProfit() )
// -- Expiration, Cancel, etc, etc
}
}
// -----------------------------------------------------------
// Store a list of all currently OPEN trade tickets into array.
// This is used to be compared in the next tick.
// -----------------------------------------------------------
ArrayResize( vaiTicketList, OrdersTotal() );
for ( viIndex=0; viIndex<OrdersTotal(); viIndex++) {
if(OrderSelect(viIndex, SELECT_BY_POS, MODE_TRADES)) {
vaiTicketList[viIndex] = OrderTicket();
}
}
// -----------------------------------------------------------
};
// ---------------------------------------
// This is the Trade Close event handler
// ---------------------------------------
bool eventTrade_Closed( int pviTicket ) {
bool vbIsEventBubble = true;
// Do something here to handle the event.
// FEATURE: vbIsEventBubble TRUE will allow event bubbles.
return( vbIsEventBubble);
}
bool eventTrade_otherPossibleEvents1() {};
bool eventTrade_otherPossibleEvents2() {};
bool eventTrade_otherPossibleEvents3() {};
bool eventTrade_otherPossibleEventsN() {};
Something along this line. Hope it helps.
you can use OrdersHistoryTotal() with a static variable to recognize this event. if this value is increased means that a position has closed.
No, there is no such direct event listener.
But:
we may create one such and test it's activation on an OnTick() event-bound handler basis.
void OnTick(){ // MQL4 system-initiated event-handler
// ---
myOnTickStealthTP_EventMONITOR(); // my Event Monitor
myOnTickStealthSL_EventMONITOR(); // my Event Monitor
// ---
// other code
}
Extending, upon not2qubit's conjecture ( irrespective how on-topic, weak or wrong one might consider that ):
You just posted an artificial non-existing function. What good is that? It would have been far more helpful if you could have provided as partially working code snippet for what you suggest. Recalling that most users of MQL4 are not programmers. – not2qubit 47 mins ago
void myOnTickStealthTP_EventMONITOR(){ // HERE put everything,
// TP_Event // what the "something else"
// ( when such events
// actually take place
// )
// meant - that's fair, isn't it ?
...
}
void myOnTickStealthSL_EventMONITOR(){ // HERE put everything,
// SL_Event // what the "something else"
// ( when such events
// actually take place
// )
// meant - that's fair, isn't it ?
...
}
I'm trying to get the basic autocomplete functionality from Google's Places Api working with Xamarin Android.
I'm using version 25.0.0.0 of Xamarin's Google Play Services - Location lib.
I've managed to get to the point of returning results of a query while following this example code
This is the Fragment I'm using to test the code
public class PlaceAutocomplete: BaseFragment, IGoogleApiClientOnConnectionFailedListener {
IGoogleApiClient client;
public override void OnCreate( Bundle savedInstanceState ) {
base.OnCreate( savedInstanceState );
client = new GoogleApiClientBuilder( Activity )
.EnableAutoManage( Activity as BaseFragmentActivity, 0, this )
.AddOnConnectionFailedListener( OnConnectionFailed )
.AddApi( Places.GEO_DATA_API )
.Build();
}
public override View OnCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
Places.GeoDataApi.GetAutocompletePredictions( client, "cul",
new LatLngBounds( new LatLng( 33.515071, -118.796427 ), new LatLng( 34.435985, -117.127371 ) ), null )
.SetResultCallback<AutocompletePredictionBuffer>( AutocompleteResult );
return base.OnCreateView( inflater, container, savedInstanceState );
}
public void AutocompleteResult( AutocompletePredictionBuffer buffer ) {
if( !buffer.Status.IsSuccess ) {
Toast.MakeText( Activity, buffer.Status.StatusMessage, ToastLength.Long ).Show();
return;
}
var a = new List<IAutocompletePrediction>();
for( var i = 0; i < buffer.Count; i++ ) {
var item = buffer.Get( i );
if( item is IAutocompletePrediction ) {
a.Add( (IAutocompletePrediction) item );
} else {
//all the results go in here
}
}
Toast.MakeText( Activity, a.Count.ToString(), ToastLength.Long ).Show();
}
public void OnConnectionFailed( ConnectionResult result ) {
}
}
There are 5 returned results from GetAutocompletePredictions method but all of them of type named com.google.android.gms.location.places.internal.zzb, cannot be cast to IAutocompletePrediction and I did not find any way to use them.
Did I do something wrong or this part of Xamarin's Google Play library is not fully implemented?
Edit - New Information
This is not a bug. The IAutocompletePrediction is not currently implemented by Xamarin so you must cast it like this
item.JavaCast<IAutocompletePrediction>()
in order to use it.
Older informaton
I've talked to Xamarin Support and they've confirmed that this is a bug.
More info on the bug fix can be found here https://bugzilla.xamarin.com/show_bug.cgi?id=31878
As of
Xamarin 4.0.0.1717 /
Xamarin.Android 6.0.0.35 /
Xamarin Google Play Services Location component v 27.0.0.0
, it seems there's been a bit of work in this space.
The IEnumerable interface now provides a way to get a typed response, and the following snippet (replacing part of AutocompleteResult) works:
var a = new List<IAutocompletePrediction>();
String t = "";
foreach (IAutocompletePrediction x in buffer)
{
a.Add(x);
t += "\n" + x.GetFullTextFormatted(new StyleSpan(TypefaceStyle.Normal)).ToString();
}
Toast.MakeText(Activity, t /* a.Count.ToString() */, ToastLength.Long).Show();
I would like to capture all events within a GWT frame. I've found several ways to do this, but they only return mousemove and mouseout events. I also need keypresses, input, etc. The goal is to capture the events and send them to another client by using websockets, and then replicate them on the other side (co-browsing).
I am using a page on the same domain within the frame.
public class ESinkFrame extends Frame implements EventListener {
public ESinkFrame(String src){
super(src);
DOM.sinkEvents(getElement(), Event.KEYEVENTS);
DOM.sinkEvents(getElement(), Event.MOUSEEVENTS);
}
public void onBrowserEvent(Event event) {
System.out.println( "sunk event: " + DOM.eventGetTypeString(event) );
}
}
And when I use it, I also try to attach a different way of grabbing the events.
ESinkFrame frame = new ESinkFrame("http://127.0.0.1:8888/other.html");
RootPanel.get().add(frame);
FrameElement frameElt = frame.getElement().cast();
Document frameDoc = frameElt.getContentDocument();
BodyElement body = frameDoc.getBody();
Element el = body.cast();
DOM.setEventListener(el, new EventListener()
{
public void onBrowserEvent(Event event)
{
Window.alert("test");
}
});
DOM.sinkEvents(el, Event.KEYEVENTS);
Event.addNativePreviewHandler(new NativePreviewHandler(){
public void onPreviewNativeEvent(NativePreviewEvent event) {
String eventName = event.getNativeEvent().getType();
if (event.isFirstHandler() /* && (event.getTypeInt() & Event.MOUSEEVENTS) == 0*/)
System.out.println("PreviewHandler: " + eventName);
}
});