예제 #1
0
    def run(self, py_file):
        self.py_file = py_file
        #use the current executing version of IPY to launch the debug process
        ipy = Assembly.GetEntryAssembly().Location
        cmd_line = "\"%s\" -D \"%s\"" % (ipy, py_file)
        self.process = self.debugger.CreateProcess(ipy, cmd_line)

        self.process.OnCreateAppDomain += self.OnCreateAppDomain
        self.process.OnProcessExit += self.OnProcessExit
        self.process.OnUpdateModuleSymbols += self.OnUpdateModuleSymbols
        self.process.OnBreakpoint += self.OnBreakpoint
        self.process.OnStepComplete += self.OnStepComplete
        self.process.OnClassLoad += self.OnClassLoad

        self.terminate_event = AutoResetEvent(False)
        self.break_event = AutoResetEvent(False)

        self.initial_breakpoint = None
        self.breakpoints = []
        self.source_files = dict()

        handles = Array.CreateInstance(WaitHandle, 2)
        handles[0] = self.terminate_event
        handles[1] = self.break_event

        while True:
            if hasattr(self, 'active_thread'): delattr(self, 'active_thread')
            if hasattr(self, 'active_appdomain'):
                delattr(self, 'active_appdomain')
            self.process.Continue(False)
            i = WaitHandle.WaitAny(handles)
            if i == 0:
                break
            self._input()
예제 #2
0
def startInteractive():
	global are
	are = AutoResetEvent(False)
	
	t = Thread(ThreadStart(appStart))
	t.ApartmentState = ApartmentState.STA
	t.Start()
	
	are.WaitOne()
	IronPython.Hosting.PythonEngine.ConsoleCommandDispatcher = DispatchConsoleCommand
예제 #3
0
 def __init__(self):
     logger.debug('Here we go')
     self.auto = Automation(True, List[String]())
     self.application = self.auto.LightFieldApplication
     self.experiment = self.application.Experiment
     self.file_manager = self.application.FileManager
     self.acquireCompleted = AutoResetEvent(False)
     self.dataset = Dataset()
     time.sleep(3)
     logger.debug('Loaded')
예제 #4
0
        global called, globalSelf, globalArg
        called = True
        globalSelf = self
        globalArg = arg


if is_cli:
    import clr

    if is_netcoreapp:
        clr.AddReference("System.Threading.Thread")

    from System import EventArgs
    from System.Threading import AutoResetEvent

    are = AutoResetEvent(False)


@skipUnlessIronPython()
class DelegateTest(IronPythonTestCase):
    def setUp(self):
        super(DelegateTest, self).setUp()
        global selph
        self.load_iron_python_test()
        import IronPythonTest

        selph = self

    def test_SimpleHandler(self):
        import IronPythonTest
        dlgTst = IronPythonTest.DelegateTest()
예제 #5
0
# Create the LightField Application (true for visible)
# The 2nd parameter forces LF to load with no experiment
auto = Automation(True, List[String]())

# Get LightField Application object
application = auto.LightFieldApplication

# Get experiment object
experiment = application.Experiment

# Get file manager object
file_manager = application.FileManager

# Notifies a waiting thread that an event has occurred
acquireCompleted = AutoResetEvent(False)

# Check for device and inform user if one is needed
if (device_found() == True):
    # Hook the experiment completed handler
    experiment.ExperimentCompleted += experiment_completed

    try:
        # Acquire image in LightField
        experiment.Acquire()

        # Wait for acquisition to complete
        acquireCompleted.WaitOne()

    finally:
        # Cleanup handler
예제 #6
0
from System.Threading import ThreadStart
from System.Threading import AutoResetEvent
import IronPython

# We support interactive development of Windows Forms by creating another
# thread on which we execute all of the IronPython console's input.  This
# allows the form to execute on another thread where a message pump can
# independently handle input and allow the form to repaint.  To make this work
# we do two things.  First we create a dummy hidden form on the other thread
# which gives us a handle for marshalling the execution of console input onto
# the thread where we will develop our real form.  Second, we supply an
# alternative function for the IronPython console to run for executing console
# input.  Our alternative function simply invokes the input on the other
# thread.

are = AutoResetEvent(False)


def thread_proc():
    try:
        global dispatcher
        global are
        # Create the dummy control, and show then hide it to get Windows Forms
        # to initialize it.
        dispatcher = Form(Size=Size(0, 0))
        dispatcher.Show()
        dispatcher.Hide()
        # Signal that the thread running thread_proc is ready for the main
        # thread to send input to it.
        are.Set()
        # Start the message loop.
예제 #7
0
    def testMultipleSaveRestoreMultiThread(self, mapper,
                                           _):  # order of execution (intended)
        mapper.ReleaseGIL()
        lock = GetGIL(mapper)

        oneThreadActed = AutoResetEvent(False)
        anotherThreadActed = AutoResetEvent(False)

        def OneThread():
            wait = lambda: anotherThreadActed.WaitOne()
            signal = lambda: oneThreadActed.Set()

            mapper.PyGILState_Ensure()  # 1
            signal()
            wait()

            pe_token = mapper.PyEval_SaveThread()  # 3
            self.assertNotEquals(pe_token, IntPtr.Zero)
            signal()
            wait()

            self.assertFalse(lock.TryAcquire())  # 5
            signal()
            wait()

            self.assertTrue(lock.TryAcquire())  # 7
            lock.Release()
            signal()
            wait()

            self.assertTrue(lock.TryAcquire())  # 9
            lock.Release()
            signal()
            wait()

            self.assertTrue(lock.TryAcquire())  # 11
            lock.Release()
            signal()
            wait()

            self.assertFalse(lock.TryAcquire())  # 13
            signal()
            wait()

            mapper.PyEval_RestoreThread(pe_token)  # 15
            signal()
            wait()

            mapper.PyGILState_Release(0)  # 17

        def AnotherThread():
            wait = lambda: oneThreadActed.WaitOne()
            signal = lambda: anotherThreadActed.Set()
            wait()

            self.assertFalse(lock.TryAcquire())  # 2
            signal()
            wait()

            mapper.PyGILState_Ensure()  # 4
            signal()
            wait()

            pe_token = mapper.PyEval_SaveThread()  # 6
            self.assertNotEquals(pe_token, IntPtr.Zero)
            signal()
            wait()

            x = mapper.PyEval_SaveThread()  # 8
            self.assertEquals(x, IntPtr.Zero)
            signal()
            wait()

            mapper.PyEval_RestoreThread(x)  # 10
            signal()
            wait()

            mapper.PyEval_RestoreThread(pe_token)  # 12
            signal()
            wait()

            mapper.PyGILState_Release(0)  # 14
            signal()
            wait()

            self.assertFalse(lock.TryAcquire())  # 16
            signal()

        t = Thread(ThreadStart(AnotherThread))
        t.Start()
        OneThread()
        t.Join()

        mapper.EnsureGIL()
예제 #8
0
import Apollo.Core.Base
import Apollo.Core.Base.Activation
import Apollo.Core.Scripting

from System.Diagnostics import Process
from System.Management import (ManagementObject, ManagementObjectSearcher)
from System.Threading import AutoResetEvent
from Apollo.Core.Base.Activation import DistributionLocations
from Apollo.Core.Scripting.Projects import DistributionSuggestionProxy


def SelectFrom(options):
    return options[0]


activateevent = AutoResetEvent(False)


def switchonactivate(sender, eventargs):
    activateevent.Set()


deactivateevent = AutoResetEvent(False)


def switchondeactivate(sender, eventargs):
    deactivateevent.Set()


# Verify that we don't have an active project
hasactiveproject = projects.HasActiveProject()
예제 #9
0
class Operations:

    # INITIALIZATION
    def __init__(self):
        logger.debug('Here we go')
        self.auto = Automation(True, List[String]())
        self.application = self.auto.LightFieldApplication
        self.experiment = self.application.Experiment
        self.file_manager = self.application.FileManager
        self.acquireCompleted = AutoResetEvent(False)
        self.dataset = Dataset()
        time.sleep(3)
        logger.debug('Loaded')

    # ACQUISITION
    def acquire(self, *args):
        logger.debug('Called acquire directly! Args: ' + str(args))
        if self.device_found():
            self.experiment.ExperimentCompleted += self.experiment_completed
            try:
                self.experiment.Acquire()
                self.acquireCompleted.WaitOne()
            finally:
                self.experiment.ExperimentCompleted -= self.experiment_completed

            directory = self.experiment.GetValue(
                ExperimentSettings.FileNameGenerationDirectory)
            self.open_saved_image(directory)
            self.open_calib(directory)

            for file in os.listdir(
                    directory
            ):  # this is an absolute shit patch to the mem error
                if os.path.splitext(file)[1] == '.spe':
                    os.remove(os.path.join(directory, file))

        # print(self.dataset.x)
        # print(self.dataset.y)

        size = len(self.dataset.x)
        datapack = np.zeros((2, size))
        for i in range(size):
            datapack[0][i] = float(self.dataset.x[i])
            datapack[1][i] = float(self.dataset.y[i])

        return datapack.tolist()

    def acquire2(self, *args):
        logger.debug('Called acquire directly! Args: ' + str(args))
        if self.device_found():
            self.experiment.ExperimentCompleted += self.experiment_completed
            try:
                self.experiment.Acquire()
                self.acquireCompleted.WaitOne()
            finally:
                self.experiment.ExperimentCompleted -= self.experiment_completed

            directory = self.experiment.GetValue(
                ExperimentSettings.FileNameGenerationDirectory)
            self.open_saved_image(directory)
        print(self.dataset.x)
        size = len(self.dataset.x)
        datapack = np.zeros(size)
        for i in range(size):
            datapack[i] = self.dataset.x[i]
        return datapack.tolist()

    def calibrate2(self, *args):
        logger.debug('Called calibrate2 directly! Args: ' + str(args))
        if self.device_found():
            self.experiment.ExperimentCompleted += self.experiment_completed
            try:
                self.experiment.Acquire()
                self.acquireCompleted.WaitOne()
            finally:
                self.experiment.ExperimentCompleted -= self.experiment_completed

            directory = self.experiment.GetValue(
                ExperimentSettings.FileNameGenerationDirectory)
            self.open_calib(directory)
        print(self.dataset.y)
        size = len(self.dataset.y)
        datapack = np.zeros(size)
        for i in range(size):
            datapack[i] = self.dataset.y[i]
        return datapack.tolist()

    def abort(self, *args):
        logger.debug('Called abort directly! Args: ' + str(args))
        if self.device_found():
            self.experiment.Abort()

    # DATA MANAGEMENT
    def open_saved_image(self, directory):
        # Access previously saved image
        if os.path.exists(directory):
            print("\nOpening .spe file...")
            # Returns all .spe files
            files = glob.glob(directory + '/*.spe')
            # Returns recently acquired .spe file
            last_image_acquired = max(files, key=os.path.getctime)

            try:
                # Open file
                # TROUBLE IS HERE   V
                file_name = self.file_manager.OpenFile(last_image_acquired,
                                                       FileAccess.Read)
                # Access image
                self.get_image_data(file_name)
                file_name.Dispose()
            except IOError as e:
                print("Error: can not find file or read data")

        else:
            print(".spe file not found...")

    def move_spe(self, *args):
        home_directory = r'C:\Users\PHOTNCS03.LAB\Documents\LightField'
        new_directory = r'C:\Users\PHOTNCS03.LAB\Desktop\LIGHTFIELD SCANS'
        for filename in os.listdir(home_directory):
            if os.path.splitext(filename)[1] == '.spe':
                print('Moving: ' + filename)
                os.rename(os.path.join(home_directory, filename),
                          os.path.join(new_directory, filename))

    def open_calib(self, directory):
        if os.path.exists(directory):
            print("\nOpening calibration file...")
            files = glob.glob(directory + '/*.spe')
            last_image_acquired = max(files, key=os.path.getctime)
            try:
                self.get_calib(last_image_acquired)
            except IOError:
                print("Error: can not find file or read data")
        else:
            print(".spe file not found...")

    def get_image_data(self, file):
        # Get the first frame
        image_data = file.GetFrame(0, 0)
        buffer = image_data.GetData()
        # SHOULD FIND CORRESPONDING METHODS FOR IMG_DATA
        self.dataset.x = np.zeros(len(buffer))
        for i in range(len(buffer)):
            self.dataset.x[i] = buffer[i]
        self.dataset.x.tolist()  # list necessary for json sterilization

    def get_calib(self, directory):
        file = open(directory, 'r', errors='ignore')
        stringy = file.read()
        stringy2 = stringy.split('<Wavelength xml:space="preserve">')[1]
        stringy3 = stringy2.split('</Wavelength>')[0]
        str_wavelength = stringy3.split(',')
        self.dataset.y = np.zeros(len(str_wavelength))
        for i in range(len(str_wavelength)):
            self.dataset.y[i] = float(str_wavelength[i])
        self.dataset.y.tolist()

    def experiment_completed(self, sender, event_args):
        print("Experiment Completed")
        self.acquireCompleted.Set()

    def device_found(self):
        # Find connected device
        for device in self.experiment.ExperimentDevices:
            if device.Type == DeviceType.Camera:
                return True

        # If connected device is not a camera inform the user
        print("Camera not found. Please add a camera and try again.")
        return False

    # SETTING VALUES

    def set_value(self, setting, value):
        if self.experiment.Exists(setting):
            if type(value[0][0]) == int:
                self.experiment.SetValue(setting, value[0][0])
            else:
                return

    def set_exposure_time(self, *args):
        logger.debug('Called set_exposure_time directly! Args: ' + str(args))
        self.set_value(CameraSettings.ShutterTimingExposureTime, args)
        return "Function Completed"

    def set_center_wavelength(self, *args):
        logger.debug('Called set_center_wavelength directly! Args: ' +
                     str(args))
        self.set_value(SpectrometerSettings.GratingCenterWavelength, args)
        return "Function Completed"

    # GETTING VALUES
    def get_spectrometer_info(self, *args):
        logger.debug('Called get_spectrometer_info directly! Args: ' +
                     str(args))
        print(
            String.Format(
                "{0} {1}", "Center Wave Length:",
                str(
                    self.experiment.GetValue(
                        SpectrometerSettings.GratingCenterWavelength))))
        print(
            String.Format(
                "{0} {1}", "Grating:",
                str(self.experiment.GetValue(SpectrometerSettings.Grating))))
        return "Function Completed"

    def get_value(self, setting):
        return self.experiment.GetValue(setting)

    def get_grating(self, *args):
        logger.debug('Called get_grating directly! Args: ' + str(args))
        return self.get_value(SpectrometerSettings.GratingSelected)

    def get_center_wavelength(self, *args):
        logger.debug('Called get_center_wavelength directly! Args: ' +
                     str(args))
        return self.get_value(SpectrometerSettings.GratingCenterWavelength)

    def get_exposure_time(self, *args):
        logger.debug('Called get_exposure_time directly! Args: ' + str(args))
        return self.get_value(CameraSettings.ShutterTimingExposureTime)

    def all_methods(self, cls):
        method_list = [
            func for func in dir(cls) if callable(getattr(cls, func))
        ]
        return method_list