Segmentation fault while using smart pointers - c++11

I get an error of ->
Segmentation fault while accessing address 0x00007ff8bf611980 (_ZNSt10_weakptrIN10prometheus11CollectableELN9_gnu_cxx12_Lock_policyE2EEC1ERKS4_+0x1b) [0x7fff8bee28215]
My code lies below-
Also I am sure the source of the error is the line "ex->register(registry);"(commented as problematic line) as when I comment it the error dosen't occur.
void Family::MakeGauge3(std::string s1, std::string s2, const
std::map<string,string>& labels, MyExposer* ex)
{ auto registry = make_shared<prometheus::Registry>();
gauge_family= &(prometheus::BuildGauge().Name(s1).Help(s2).
Labels(labels).Register(*registry));
ex->register(registry); //problematic line
}
The register function in the MyExposer class is->
void MyExposer::register(std::shared_ptr<prometheus::Registry> reg)
{
exp ->RegisterCollectable(reg);
}
exp is a private member of class MyExposer defined as->
Exposer* exp; //Exposer is another class
Also class Registry is publicly inherited from my class called Collectable.
void Exposer::RegisterCollectable(const
std::weak_ptr<prometheus::Collectable>&
collectable)
{ collectables_.push_back(collectable);
}
where collectable_is a private member defined in Exposer class as->
std::vector<std::weak_ptr<prometheus::Collectable>> collectables_;

Related

How to retrieve the value from the event listener from another class in java?

I have a program to get the values from a Bar code scanner(using jssc library) and it returns value as expected using event listener but I need to access that value from another class.
I tried to instantiate BarcodeScanner class to main method (ProcessTicket class) and called scannerHandler method and also called the getter method of model class to retrieve value but the getter method runs before the scan is completed. Could you please help me to achieve this?
public class BarcodeScanner {
public static Object SerialPortReader;
static SerialPort serialPort;
public void scannerHandler() {
serialPort = new SerialPort("COM4");
try{
serialPort.openPort();//Open serial port
//Set params. Also set params by this string:
serialPort.setParams(9600, 8, 1, 0);
serialPort.setParams(9600, 8, 1, 0);
serialPort.writeString(new String(new byte[]{0x02})); //triggers barcode scanner
serialPort.addEventListener(new SerialPortReader());//Add SerialPortEventListenerS
} catch (SerialPortException ex) {
System.out.println(ex);
}
}
public static class SerialPortReader implements SerialPortEventListener {
String str;
String value;
public void serialEvent(SerialPortEvent event) {
if (event.isRXCHAR() && event.getEventValue() > 0) {//If data is available
//Check bytes count in the input buffer
try {
byte[] bytesCont = serialPort.readBytes(14);
str = new String(bytesCont);
ModelClass modelClass = new ModelClass();
modelClass.setBarcodeValue(str);
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}
My ProcessTicket.java Class
public class ProcessTicket {
public static void main(String[] args) throws SQLException, SerialPortException {
BarcodeScanner bSC = new BarcodeScanner();
bSC.scannerHandler();
BarcodeScanner.SerialPortReader portReader = new BarcodeScanner.SerialPortReader();
ModelClass modelClass = new ModelClass();
String value = modelClass.getBarcodeValue();
System.out.println(value);
}
}
The main problem here is that you're treating an inherently asynchronous operation (reading from an external sensor in the real world) as if it's synchronous.
I simulated that external sensor stuff to make a standalone app that tests your business logic:
HowToRetrieveTheValueFromTheEventListenerFromAnotherClassInJava.java
package com.stackoverflow;
/**
* https://stackoverflow.com/questions/57452205/how-to-retrieve-the-value-from-the-event-listener-from-another-class-in-java
*/
public class HowToRetrieveTheValueFromTheEventListenerFromAnotherClassInJava {
public static void main(String[] args) {
BarcodeScanner barcodeScanner = new BarcodeScanner((String barcode) -> {
System.out.println("Barcode scanned: " + barcode);
});
barcodeScanner.startScan();
MockUser.startScanningStuffLol();
}
}
That call to MockUser.startScanningStuffLol() is only necessary because I'm testing this just in code, without using a real barcode scanner. Please don't focus on it. I'll post its implementation if you ask, but otherwise I'm assuming that your OS/Java/hardware are working the way they were designed to work, and you can just test this with those tools instead of my MockUser software simulation.
Here are the rest of the classes that you need to implement this:
BarcodeScannedCallback.java
package com.stackoverflow;
public interface BarcodeScannedCallback {
void callback(String barcode);
}
Since we're dealing with an asynchronous operation, we can't just start it and then check for a return value, like we would with a synchronous operation. Instead, we need to pass in a function that will be called once the operation is complete, and just wait for it to finish. BarcodeScannedCallback is the signature of that function (in other words, a description of how that function needs to be structured). It takes one string parameter, and returns nothing.
The implementation of BarcodeScannedCallback is this function that I've already mentioned above, which I'm passing into the BarcodeScanner constructor:
(String barcode) -> {
System.out.println("Barcode scanned: " + barcode);
}
As you can see, this function takes one string parameter, and returns nothing. So, it's an implementation of the BarcodeScannedCallback interface.
Now for the last class: the one that bridges our main method and the serial port, using the above interface.
BarcodeScanner.java
package com.stackoverflow;
public class BarcodeScanner implements SerialPortEventListener {
private SerialPort serialPort;
private final BarcodeScannedCallback callback;
public void startScan() {
try {
serialPort = new SerialPort("COM4");
serialPort.openPort();
serialPort.addEventListener(this);
// Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);
serialPort.setParams(9600, 8, 1, 0);
// Triggers barcode scanner.
serialPort.writeString(new String(new byte[]{0x02}));
} catch (SerialPortException ex) {
System.out.println(ex);
}
}
#Override
public void serialEvent(SerialPortEvent event) {
boolean isDataAvailable = event.isRXCHAR() && event.getEventValue() > 0;
if (isDataAvailable) {
try {
byte[] bytesCont = serialPort.readBytes(14);
String barcode = new String(bytesCont);
callback.callback(barcode);
} catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
public BarcodeScanner(BarcodeScannedCallback callback) {
this.callback = callback;
}
}
So here's the full lifecycle of these events:
You create a BarcodeScanner.
You tell the BarcodeScanner, via the implementation of BarcodeScannedCallback that you pass into its constructor, what code to run once it receives a barcode over the serial port.
You call startScan on the BarcodeScanner, which opens the serial port and starts waiting for the user to scan a barcode.
The user scans a barcode. This data is transmitted over the serial port. The operating system's implementation of SerialPort calls BarcodeScanner.serialEvent.
Your implementation of serialEvent does its validations, pulls the data from the serial port and converts it from bytes to a string, and calls the BarcodeScannedCallback function that was passed in at the beginning.
When I run this (with my MockUser class setting up a background thread that "scans" a barcode every 3 seconds), I get this output:
Barcode scanned: 420L0L
Barcode scanned: 007
Barcode scanned: 12345
In your case, you should be able to scan 3 barcodes with your real-world barcode scanner, and get the same results.
Note that you may need to do something to keep the main method's thread from ending prematurely, depending on the context that you're running this in.
If you're running it in an Android app or a web server, those frameworks keep their main thread running indefinitely, until you kill the app/server.
But if you're running it as a custom command-line app (which it seems like you're doing, based on the existence of a main method), you will need to do something to keep it alive until you decide to kill it. The simplest way is to put an infinite loop like while (true); on the last line of your main method.

IronPyhton System.MissingMemberException object has no attribute 'ChangeType'

I'm writing a Python script in IronPython that uses a C# DLL implementing the observer/observable pattern, the C# library has the observable class and I want to implement the observer in Python.
I'm registering my Python function as the observer method, but when it gets called, I get an "System.MissingMemberException: 'PeripheralDiscoveredEventArgs' object has no attribute 'ChangeType' exception thrown.
I can't find any documentation on how to use custom arguments with C# events when using IronPython, looked here, here, here and here.
My Python code is:
central = None
def MyCallback(sender, event_args):
print event_args.ChangeType, event_args.Name
def main():
global central
central = objFactory.GetCentral();
d = System.EventHandler[CustomEventArgs](MyCallback)
central.myHandler += d
(do something)
if __name__ == "__main__":
main()
I also tried to do just this:
central.myHandler += MyCallback
But I got the same exception.
The central variable as a Central instantance and the central.myHandler property in the is defined in the Central class as:
public event EventHandler<CustomEventArgs> myHandler = delegate { };
The CustomEventArgs class is defined as:
public class CustomEventArgs: EventArgs
{
public CustomEventArgs(Class1 obj1, int i, Class2 obj2, bool tf);
public Class1 Obj1 { get; }
public int I{ get; }
public Class2 Obj2t { get; }
public bool Tf{ get; }
}
The observable class method that calls my callback is:
internal abstract class EventHelper
{
internal static void TriggerEvent<T>(EventHandler<T> eventHandler, object source, T args)
{
// event handle no used ?
if (eventHandler == null) return;
try
{
// call event handler
eventHandler(source, args);
}
catch (Exception ex)
{
var target = eventHandler.Target != null ? eventHandler.Target : "unknown";
var methodName = (eventHandler.Method != null && eventHandler.Method.Name != null) ? eventHandler.Method.Name : "unknown";
Log.Error(string.Format("Exception in event handler '{0}' in '{1}'", methodName, target), ex);
}
}
The whole exception is:
"System.MissingMemberException: 'CustomEventArgs' object has no attribute 'ChangeType'
at IronPython.Runtime.Binding.PythonGetMemberBinder.FastErrorGet`1.GetError(CallSite site, TSelfType target, CodeContext context)
at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
at __main__$1.MyCallback$74(PythonFunction $function, Object sender, Object event_args) in C:\\code\\Launcher.py:line 51
at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at _Scripting_(Object[] , Object , CustomEventArgs )
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at EventHelper.TriggerEvent[T](EventHandler`1 eventHandler, Object source, T args) in C:\\code\\Utility\\EventHelper.cs:line 27"
Any pointers on how to use custom event arguments in C# with IronPython? Thanks!!
Environment:
Windows 7 Enterprise 64 bits
IronPython 2.7.8 (2.7.8.0) on .NET 4.0.30319.42000 (32-bit)
.NET Framework 4.5.2
Nevermind, it was my mistake (as usual). Trying to access a non-existent member of a class usually leads to errors/exceptions...
Just changing the observer code to :
def centralOnPeripheralDiscovered_callback(sender, event_args):
print sender
print event_args
Solves the problem. Thanks for the help!

Mockito: Verifying a method was called with a functional parameter

I have a simple scenario in which am trying to verify some behavior when a method is called (i.e. that a certain method was called with given parameter, a function pointer in this scenario). Below are my classes:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
AppBootStrapper bootStrapper = context.getBean(AppBootStrapper.class);
bootStrapper.start();
}
}
#Component
public class AppBootStrapper {
private NetworkScanner networkScanner;
private PacketConsumer packetConsumer;
public AppBootStrapper(NetworkScanner networkScanner, PacketConsumer packetConsumer) {
this.networkScanner = networkScanner;
this.packetConsumer = packetConsumer;
}
public void start() {
networkScanner.addConsumer(packetConsumer::consumePacket);
networkScanner.startScan();
}
}
#Component
public class NetworkScanner {
private List<Consumer<String>> consumers = new ArrayList<>();
public void startScan(){
Executors.newSingleThreadExecutor().submit(() -> {
while(true) {
// do some scanning and get/parse packets
consumers.forEach(consumer -> consumer.accept("Package Data"));
}
});
}
public void addConsumer(Consumer<String> consumer) {
this.consumers.add(consumer);
}
}
#Component
public class PacketConsumer {
public void consumePacket(String packet) {
System.out.println("Packet received: " + packet);
}
}
#RunWith(JUnit4.class)
public class AppBootStrapperTest {
#Test
public void start() throws Exception {
NetworkScanner networkScanner = mock(NetworkScanner.class);
PacketConsumer packetConsumer = mock(PacketConsumer.class);
AppBootStrapper appBootStrapper = new AppBootStrapper(networkScanner, packetConsumer);
appBootStrapper.start();
verify(networkScanner).addConsumer(packetConsumer::consumePacket);
verify(networkScanner, times(1)).startScan();
}
}
I want to verify that bootStrapper did in fact do proper setup by registering the packet consumer(there might be other consumers registered later on, but this one is mandatory) and then called startScan. I get the following error message when I execute the test case:
Argument(s) are different! Wanted:
networkScanner bean.addConsumer(
com.spring.starter.AppBootStrapperTest$$Lambda$8/438123546#282308c3
);
-> at com.spring.starter.AppBootStrapperTest.start(AppBootStrapperTest.java:24)
Actual invocation has different arguments:
networkScanner bean.addConsumer(
com.spring.starter.AppBootStrapper$$Lambda$7/920446957#5dda14d0
);
-> at com.spring.starter.AppBootStrapper.start(AppBootStrapper.java:12)
From the exception, clearly the function pointers aren't the same.
Am I approaching this the right way? Is there something basic I am missing? I played around and had a consumer injected into PacketConsumer just to see if it made a different and that was OK, but I know that's certainly not the right way to go.
Any help, perspectives on this would be greatly appreciated.
Java doesn't have any concept of "function pointers"; when you see:
networkScanner.addConsumer(packetConsumer::consumePacket);
What Java actually compiles is (the equivalent of):
networkScanner.addConsumer(new Consumer<String>() {
#Override void accept(String packet) {
packetConsumer.consumePacket(packet);
}
});
This anonymous inner class happens to be called AppBootStrapper$$Lambda$7. Because it doesn't (and shouldn't) define an equals method, it will never be equal to the anonymous inner class that the compiler generates in your test, which happens to be called AppBootStrapperTest$$Lambda$8. This is regardless of the fact that the method bodies are the same, and are built in the same way from the same method reference.
If you generate the Consumer explicitly in your test and save it as a static final Consumer<String> field, then you can pass that reference in the test and compare it; at that point, reference equality should hold. This should work with a lambda expression or method reference just fine.
A more apt test would probably verify(packetConsumer, atLeastOnce()).consumePacket(...), as the contents of the lambda are an implementation detail and you're really more concerned about how your component collaborates with other components. The abstraction here should be at the consumePacket level, not at the addConsumer level.
See the comments and answer on this SO question.

C++/CLI - Managed class to C# events

I have a c++ class that triggers some method like an event.
class Blah {
virtual void Event(EventArgs e);
}
How can I wrap it so whenever the method is called a C# (managed) event will be called?
I thought of inheriting that class and overloading the event method, and then somehow call the managed event.
I'm just not sure how to actually do it.
Something like this (now compile-tested):
#include <vcclr.h>
struct blah_args
{
int x, y;
};
struct blah
{
virtual void Event(const blah_args& e) = 0;
};
public ref class BlahEventArgs : public System::EventArgs
{
public:
int x, y;
};
public ref class BlahDotNet
{
public:
event System::EventHandler<BlahEventArgs^>^ ItHappened;
internal:
void RaiseItHappened(BlahEventArgs^ e) { ItHappened(this, e); }
};
class blah_event_forwarder : public blah
{
gcroot<BlahDotNet^> m_managed;
public:
blah_event_forwarder(BlahDotNet^ managed) : m_managed(managed) {}
protected:
virtual void Event(const blah_args& e)
{
BlahEventArgs^ e2 = gcnew BlahEventArgs();
e2->x = e.x;
e2->y = e.y;
m_managed->RaiseItHappened(e2);
}
};
You need to do some work to reflect the Event() method call so it can be hooked by a managed class. Lets implement a concrete blah class that does so:
#pragma managed(push, off)
struct EvenAtrgs {};
class blah {
public:
virtual void Event (EvenAtrgs e) = 0;
};
typedef void (* CallBack)(EvenAtrgs);
class blahImpl : blah {
CallBack callback;
public:
blahImpl(CallBack fp) {
this->callback = fp;
}
virtual void Event(EvenAtrgs e) {
callback(e);
}
};
#pragma managed(pop)
You can now construct a blahImpl and pass it a function pointer that is called when the Event() method is called. You can use Marshal::GetFunctionPointerForDelegate() to get such a function pointer, it creates a stub for a delegate that makes the transition from unmanaged code to managed code and can store a instance as well. Combined with the boilerplate code to wrap an unmanaged class:
public ref class blahWrapper {
blahImpl* instance;
delegate void managedCallback(EvenAtrgs e);
managedCallback^ callback;
void fireEvent(EvenAtrgs e) {
// Todo: convert e to a managed EventArgs derived class
//...
Event(this, EventArgs::Empty);
}
public:
event EventHandler<EventArgs^>^ Event;
blahWrapper() {
callback = gcnew managedCallback(this, &blahWrapper::fireEvent);
instance = new blahImpl((CallBack)(void*)System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegate(callback));
}
~blahWrapper() { delete instance; }
!blahWrapper() { delete instance; }
};
The C# code can now write an event handler for the Event event. I left the spelling error in tact, you need to do some work to convert EvenAtrgs to a managed class that derives from EventArgs. Modify the managed Event accordingly.
Create a class that inherits from blah and have it take a reference to your managed wrapper in the constructor. Override the Event() method and when it gets called you can just forward that method on to the managed wrapper class instance you are storing.
Note that you can't raise an event from outside of the containing class, so you'll have to either make it a plain delegate or call a helper method on the managed class to raise it for you.

Plug-in Development: Creating Problem Marker for a Given Resource

I seem to be having a problem with associating a problem marker with a resource; in my case, I'm trying to create a problem marker for the editor.
To achieve this, I've tried to do the following:
public class MyEditor extends TextEditor{
private ColorManager colorManager;
public MyEditor() {
super();
...
IResource resource = (IResource) getEditorInput().getAdapter(IResource.class);
try
{
marker = resource.createMarker(IMarker.PROBLEM);
}
catch (CoreException e)
{
e.printStackTrace();
}
}
However, the problem is getEditorInput() keeps returning null. I assume I am not calling it at the right location. I thought it would be ideal to create the marker once I'm setting up the editor, but this proves otherwise.
Does anyone have any advice to obtaining the proper resource I want so that I may create the problem marker? I would like to show errors and such within the editor.
I've looked at samples online for creating the marker, but most just show methods that pass the ITextEditor object without showing where the method call is. (for example: Creating Error Marker for Compiler -- see reportError method)
Thank you.
Paul
Edit:
I have also viewed the following link regarding problem markers, but again, it calls createMarker from a resource(res, in this case), but does not show the setup for it.
See Show Syntax Errors in An Eclipse Editor Plugin
EditorInput is initialize in init method
You can override init or
public class MyEditor extends TextEditor{
private ColorManager colorManager;
public MyEditor() {
super();
...
}
public void init(IEditorSite site, IEditorInput input)
throws PartInitException {
super.init(site, input);
IResource resource = (IResource) getEditorInput().getAdapter(IResource.class);
try
{
marker = resource.createMarker(IMarker.PROBLEM);
}
catch (CoreException e)
{
e.printStackTrace();
}
}
I create a marker (including a call to getEditorInput()) from the run() method of an Action object.
public class MyAction extends Action {
...
public void run() {
...
int line = ...;
IEditorInput ei = editor.getEditorInput()
if (ei != null)
createMarkerAt(line, ei);
}
}
Addition (Following Paul's comment) How to get an Editor?
Well, In my app I am subclassing AbstractRulerActionDelegate, by overriding the createAction(ITextEditor e, IVerticalRulerInfo ri) method (which, BTW, Is a must - this method is abstract) my app can get the relevant ITextEditor object.

Resources