Load and return `libeng` and `libmx`.  Start and return MATLAB
    engine.

    Returns
    -------
    engine
    libeng
    libmx
493805
def load_engine_and_libs(matlab_root, options):
    
    if sys.maxsize > 2**32:
        bits = '64bit'
    else:
        bits = '32bit'

    system = platform.system()

    if system == 'Linux':
        if bits == '64bit':
            lib_dir = join(matlab_root, "bin", "glnxa64")
        else:
            lib_dir = join(matlab_root, "bin", "glnx86")

        check_python_matlab_architecture(bits, lib_dir)

        libeng = Library(
            join(lib_dir, 'libeng.so')
        )
        libmx = Library(
            join(lib_dir, 'libmx.so')
        )

        command = "{executable} {options}".format(
            executable=join(matlab_root, 'bin', 'matlab'),
            options=options
        )

        ### Check for /bin/csh
        if not os.path.exists("/bin/csh"):
            warnings.warn("MATLAB engine requires /bin/csh.  Please install it on your system or matlab_wrapper will not work properly.")

    elif system == 'Windows':
        if bits == '64bit':
            lib_dir = join(matlab_root, "bin", "win64")
        else:
            lib_dir = join(matlab_root, "bin", "win32")

        check_python_matlab_architecture(bits, lib_dir)

        ## We need to modify PATH, to find MATLAB libs
        if lib_dir not in os.environ['PATH']:
            os.environ['PATH'] = lib_dir + ';' + os.environ['PATH']

        libeng = Library('libeng')
        libmx = Library('libmx')

        command = None

    elif system == 'Darwin':
        if bits == '64bit':
            lib_dir = join(matlab_root, "bin", "maci64")
        else:
            unsupported_platform(system, bits)

        check_python_matlab_architecture(bits, lib_dir)

        libeng = Library(
            join(lib_dir, 'libeng.dylib')
        )
        libmx = Library(
            join(lib_dir, 'libmx.dylib')
        )

        command = "{executable} {options}".format(
            executable=join(matlab_root, 'bin', 'matlab'),
            options=options
        )

    else:
        unsupported_platform(system, bits)

    ### Check MATLAB version
    try:
        version_str = c_char_p.in_dll(libeng, "libeng_version").value
        version = tuple([int(v) for v in version_str.split('.')[:2]])

    except ValueError:
        warnings.warn("Unable to identify MATLAB (libeng) version.")
        version = None

    if (system == 'Linux') and (version == (8, 3)) and (bits == '64bit'):
        warnings.warn("You are using MATLAB version 8.3 (R2014a) on Linux, which appears to have a bug in engGetVariable().  You will only be able to use arrays of type double.")

    elif (system == 'Darwin') and (version == (8, 3)) and (bits == '64bit'):
        warnings.warn("You are using MATLAB version 8.3 (R2014a) on OS X, which appears to have a bug in engGetVariable().  You will only be able to use arrays of type double.")

    ### Start the engine
    engine = libeng.engOpen(command)

    return engine, libeng, libmx, version
388426
def import_lib(self):
        """"""

        try:
            import ambry.build
            module = sys.modules['ambry.build']
        except ImportError:
            module = imp.new_module('ambry.build')
            sys.modules['ambry.build'] = module

        bf = self.record

        if not bf.has_contents:
            return

        try:
            exec (compile(bf.contents, self.path, 'exec'), module.__dict__)

        except Exception:
            self._bundle.error("Failed to load code from {}".format(self.path))
            raise

        # print(self.file_const, bundle.__dict__.keys())
        # print(bf.contents)

        return module
1359659
async def main():
    """"""
    pyvlx = PyVLX('pyvlx.yaml')
    # Alternative:
    # pyvlx = PyVLX(host="192.168.2.127", password="velux123", timeout=60)

    await pyvlx.load_devices()
    print(pyvlx.devices[1])
    print(pyvlx.devices['Fenster 4'])

    await pyvlx.load_scenes()
    print(pyvlx.scenes[0])
    print(pyvlx.scenes['Bath Closed'])

    # opening/ closing windows by running scenes, yay!
    await pyvlx.scenes[1].run()

    await pyvlx.disconnect()
577020
def execute_notebook_with_engine(self, engine_name, nb, kernel_name, **kwargs):
        """"""
        return self.get_engine(engine_name).execute_notebook(nb, kernel_name, **kwargs)
556884
def get(self, name):
        
        pm = self._libeng.engGetVariable(self._ep, name)

        out = mxarray_to_ndarray(self._libmx, pm)


        self._libmx.mxDestroyArray(pm)

        return out
761316
def main():
    

    components_paths = []
    for path in (os.path.join(umbra.__path__[0], Constants.factory_components_directory),
                 os.path.join(umbra.__path__[0], Constants.factory_addons_components_directory)):
        os.path.exists(path) and components_paths.append(path)
    return umbra.engine.run(umbra.engine.Umbra,
                            umbra.engine.get_command_line_parameters_parser().parse_args(
                                [unicode(argument, Constants.default_codec, Constants.codec_error) for argument in
                                 sys.argv]),
                            components_paths,
                            ("factory.script_editor", "factory.preferences_manager", "factory.components_manager_ui"))
1365412
def buildWorkbenchWithLauncher():
    
    workbench = ui.Workbench()

    tools = [exercises.SearchTool()]
    launcher = ui.Launcher(workbench, tools)
    workbench.display(launcher)

    return workbench, launcher
784558
def main():
    """"""
    init_logging()

    # Get Dask client
    arlexecute.set_client(get_dask_Client())
    arlexecute.run(init_logging)

    LOG.info('Results dir = %s', RESULTS_DIR)
    LOG.info("Starting imaging-modeling")

    # Read parameters
    PARFILE = 'parameters.json'
    if len(sys.argv) > 1:
       PARFILE = sys.argv[1]
    LOG.info("JSON parameter file = %s", PARFILE)

    try: 	
       with open(PARFILE, "r") as par_file:
             jspar = json.load(par_file)       
    except AssertionError as error:
       LOG.critical('ERROR %s', error)
       return

    # Model parameters
    configuration= jspar["modeling"]["configuration"]["name"]
    num_freq_win = jspar["modeling"]["configuration"]["num_freq_win"] # 7
    num_times    = jspar["modeling"]["configuration"]["num_times"] # 11
    r_max        = jspar["modeling"]["configuration"]["r_max"] # 300.0
    fstart	 = jspar["modeling"]["configuration"]["fstart"]
    fend	 = jspar["modeling"]["configuration"]["fend"]
    timestart_pi = jspar["modeling"]["configuration"]["timestart_pi"] # -1/3
    timeend_pi   = jspar["modeling"]["configuration"]["timeend_pi"] # 1/3
    polframe     = jspar["modeling"]["configuration"]["PolarisationFrame"] # StokesI

    frequency = numpy.linspace(fstart, fend, num_freq_win)
    channel_bw = numpy.array(num_freq_win * [frequency[1] - frequency[0]]) # 0.9e8 ... 1.1e8
    times = numpy.linspace(numpy.pi * timestart_pi, numpy.pi * timeend_pi, num_times)

    phase_centre = SkyCoord(	ra     =jspar["modeling"]["phasecentre"]["RA"] * u.deg, 
				dec    =jspar["modeling"]["phasecentre"]["Dec"] * u.deg,
                            	frame  =jspar["modeling"]["phasecentre"]["frame"], 
				equinox=jspar["modeling"]["phasecentre"]["equinox"])

    # Simulate visibilities
    vis_list = simulate_arlexecute(configuration,
                                  frequency=frequency,
                                  channel_bandwidth=channel_bw,
                                  times=times,
                                  phasecentre=phase_centre,
                                  order=jspar["modeling"]["simulate"]["order"],
                                  rmax=r_max)

    LOG.info('%d elements in vis_list', len(vis_list))
    LOG.info('About to make visibility')
    vis_list = arlexecute.compute(vis_list, sync=True)
    LOG.debug('vis_list type: %s', type(vis_list))
    LOG.debug('vis_list element type: %s', type(vis_list[0]))
    try:
        export_blockvisibility_to_hdf5(vis_list,
                                       '%s/%s' % (RESULTS_DIR, jspar["files"]["vis_list"]))
    except AssertionError as error:
        LOG.critical('ERROR %s', error)
        return

    wprojection_planes = jspar["advice"]["wprojection_planes"]
    guard_band_image   = jspar["advice"]["guard_band_image"]
    delA               = jspar["advice"]["delA"]
    advice_low = advise_wide_field(vis_list[0], guard_band_image=guard_band_image,
                                   delA=delA,
                                   wprojection_planes=wprojection_planes)
    advice_high = advise_wide_field(vis_list[-1], guard_band_image=guard_band_image,
                                    delA=delA,
                                    wprojection_planes=wprojection_planes)


    vis_slices = advice_low['vis_slices']
    num_pixels = advice_high['npixels2']
    cellsize = min(advice_low['cellsize'], advice_high['cellsize'])

    # Create GLEAM model
    gleam_model = [
        arlexecute.execute(create_low_test_image_from_gleam)(
            npixel=num_pixels,
            frequency=[frequency[f]],
            channel_bandwidth=[channel_bw[f]],
            cellsize=cellsize,
            phasecentre=phase_centre,
            polarisation_frame=PolarisationFrame(polframe),
            flux_limit=jspar["modeling"]["gleam_model"]["flux_limit"], # 1.0,
            applybeam =jspar["modeling"]["gleam_model"]["applybeam"])  # True
        for f, freq in enumerate(frequency)
    ]


    LOG.info('About to make GLEAM model')
    gleam_model = arlexecute.compute(gleam_model, sync=True)
    # future_gleam_model = arlexecute.scatter(gleam_model)

    # Get predicted visibilities for GLEAM model
    LOG.info('About to run predict to get predicted visibility')
    future_vis_graph = arlexecute.scatter(vis_list)
    predicted_vis_list = predict_arlexecute(future_vis_graph, gleam_model,
                                           context=jspar["modeling"]["predict"]["context"],  #'wstack'
                                           vis_slices=vis_slices)
    predicted_vis_list = arlexecute.compute(predicted_vis_list, sync=True)
    corrupted_vis_list = corrupt_arlexecute(predicted_vis_list, phase_error=jspar["modeling"]["corrupt"]["phase_error"]) #1.0

    LOG.info('About to run corrupt to get corrupted visibility')
    corrupted_vis_list = arlexecute.compute(corrupted_vis_list, sync=True)

    LOG.info('About to output predicted_vislist.hdf')
    export_blockvisibility_to_hdf5(predicted_vis_list,
                                   '%s/%s' % (RESULTS_DIR,jspar["files"]["predicted_vis_list"]))

    LOG.info('About to output corrupted_vislist.hdf')

    export_blockvisibility_to_hdf5(corrupted_vis_list,
                                   '%s/%s' % (RESULTS_DIR, jspar["files"]["corrupted_vis_list"]))
    # Close Dask client
    arlexecute.close()
99166
function Engine() {
      var _this;

      var ua = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
      var flags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var cssFlagsPrefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'engine';

      _classCallCheck(this, Engine);

      _this = _possibleConstructorReturn(this, _getPrototypeOf(Engine).call(this, ua, flags, cssFlagsPrefix));
      _this.version = 'n/a';
      return _this;
    }
618461
def get_engine_from_session(dbsession: Session) -> Engine:
    
    engine = dbsession.bind
    assert isinstance(engine, Engine)
    return engine
666826
def start(self):
        
        engine = self.current_engine()
        if not engine.running:
            if self._settings["vmname"] is None:
                return
            log.info("")
            engine.vmname = self._settings["vmname"]
            engine.ram = self._settings["ram"]
            engine.vcpus = self._settings["vcpus"]
            engine.headless = self._settings["headless"]
            compute = yield from self._controller.add_compute(compute_id="vm",
                                                              name="GNS3 VM is starting ({})".format(engine.vmname),
                                                              host=None,
                                                              force=True,
                                                              connect=False)

            try:
                yield from engine.start()
            except Exception as e:
                yield from self._controller.delete_compute("vm")
                log.error("Can't start the GNS3 VM: {}".format(str(e)))
                yield from compute.update(name="GNS3 VM ({})".format(engine.vmname))
                raise e
            yield from compute.connect()  # we can connect now that the VM has started
            yield from compute.update(name="GNS3 VM ({})".format(engine.vmname),
                                      protocol=self.protocol,
                                      host=self.ip_address,
                                      port=self.port,
                                      user=self.user,
                                      password=self.password)

            # check if the VM is in the same subnet as the local server, start 10 seconds later to give
            # some time for the compute in the VM to be ready for requests
            asyncio.get_event_loop().call_later(10, lambda: asyncio.async(self._check_network(compute)))
1023794
def executable(self):
        """"""
        if not hasattr(self.local, 'conn'):
            self.local.conn = self.engine.connect()
        return self.local.conn
11946
def _load_lib():
    """"""
    lib_path = _find_lib_path()
    lib = ctypes.cdll.LoadLibrary(lib_path[0])
    # DMatrix functions
    lib.MXGetLastError.restype = ctypes.c_char_p
    return lib
550472
def example_compute(self):
        
        a = matmul(self.x, self.w1)
        y = matmul(a, self.w2)

        sess = Session()
        sess.run(self.w1.initializer)
        sess.run(self.w2.initializer)
        print('第一种：', sess.run(y))
        sess.close()
527212
def simxStart(connectionAddress, connectionPort, waitUntilConnected, doNotReconnectOnceDisconnected, timeOutInMs, commThreadCycleInMs):
    '''
    
    '''

    if (sys.version_info[0] == 3) and (type(connectionAddress) is str):
        connectionAddress=connectionAddress.encode('utf-8')
    return c_Start(connectionAddress, connectionPort, waitUntilConnected, doNotReconnectOnceDisconnected, timeOutInMs, commThreadCycleInMs)
285335
def example_2_compute(self):
        
        a = matmul(self.x, self.w1) # 计算神经网络的第一层的输出向量
        y = matmul(a, self.w2) # 以第一层的输出作为第二层的输入再次计算第二层的输出

        sess = Session()
        initOp = global_variables_initializer() # 初始化所有变量
        sess.run(initOp)
        #print('第二种：', sess.run(y, feed_dict={self.x: [[0.7, 0.9]]}))
        print('第二种：', sess.run(y, feed_dict={self.x: [[0.7, 0.9], [0.1, 0.4], [0.5, 0.8]]}))
        sess.close()
1341109
def load_tf_lib():
    
    from os.path import join as pjoin
    import pkg_resources

    import tensorflow as tf

    path = pjoin('ext', 'rime.so')
    rime_lib_path = pkg_resources.resource_filename("montblanc", path)
    return tf.load_op_library(rime_lib_path)