Opens the matlab process.
968933
def open(self, print_matlab_welcome=False):
        ''''''
        if self.process and not self.process.returncode:
            raise MatlabConnectionError('Matlab(TM) process is still active. Use close to '
                                            'close it')
        self.process = subprocess.Popen(
                [self.matlab_process_path, '-nojvm', '-nodesktop'],
                stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        flags = fcntl.fcntl(self.process.stdout, fcntl.F_GETFL)
        fcntl.fcntl(self.process.stdout, fcntl.F_SETFL, flags| os.O_NONBLOCK)

        if print_matlab_welcome:
            self._sync_output()
        else:
            self._sync_output(None)
50442
def open_sensor(
        self, input_source: str, extra_cmd: Optional[str] = None
    ) -> Coroutine:
        
        command = [
            "-an",
            "-filter:v",
            "select=gt(scene\\,{0})".format(self._changes / 100),
        ]

        # run ffmpeg, read output
        return self.start_worker(
            cmd=command,
            input_source=input_source,
            output="-f framemd5 -",
            extra_cmd=extra_cmd,
            pattern=self.MATCH,
            reading=FFMPEG_STDOUT,
        )
1349640
def open(self):
        
        if not self.handle:
            self.lvm.open()
            self.__vgh = lvm_vg_open(self.lvm.handle, self.name, self.mode)
            if not bool(self.__vgh):
                raise HandleError("Failed to initialize VG Handle.")
1165471
def main(_):
  """"""
  eps = FLAGS.max_epsilon / 255.0
  batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]

  with tf.Graph().as_default():
    x_input = tf.placeholder(tf.float32, shape=batch_shape)
    noisy_images = x_input + eps * tf.sign(tf.random_normal(batch_shape))
    x_output = tf.clip_by_value(noisy_images, 0.0, 1.0)

    with tf.Session(FLAGS.master) as sess:
      for filenames, images in load_images(FLAGS.input_dir, batch_shape):
        out_images = sess.run(x_output, feed_dict={x_input: images})
        save_images(out_images, filenames, FLAGS.output_dir)
95164
async def open(
        self,
        cmd: List[str],
        input_source: Optional[str],
        output: Optional[str] = "-",
        extra_cmd: Optional[str] = None,
        stdout_pipe: bool = True,
        stderr_pipe: bool = False,
    ) -> bool:
        """"""
        stdout = subprocess.PIPE if stdout_pipe else subprocess.DEVNULL
        stderr = subprocess.PIPE if stderr_pipe else subprocess.DEVNULL

        if self.is_running:
            _LOGGER.warning("FFmpeg is already running!")
            return True

        # set command line
        self._generate_ffmpeg_cmd(cmd, input_source, output, extra_cmd)

        # start ffmpeg
        _LOGGER.debug("Start FFmpeg with %s", str(self._argv))
        try:
            proc_func = functools.partial(
                subprocess.Popen,
                self._argv,
                bufsize=0,
                stdin=subprocess.PIPE,
                stdout=stdout,
                stderr=stderr,
            )
            self._proc = await self._loop.run_in_executor(None, proc_func)
        except Exception as err:  # pylint: disable=broad-except
            _LOGGER.exception("FFmpeg fails %s", err)
            self._clear()
            return False

        return self._proc is not None
1012765
private function open() {
         if (!is_resource($this->handler)) {
             $this->handler = fsockopen($this->options['host'], $this->options['port'], $_, $_, $this->options['timeout']);
         }
     }
1163259
def build_matlab(static=False):
    
    cfg = get_config()
    # To deal with spaces, remove quotes now, and add
    # to the full commands themselves.
    if 'matlab_bin' in cfg and cfg['matlab_bin'] != '.':
        matlab_bin = cfg['matlab_bin'].strip('"')
    else:  # attempt to autodetect MATLAB filepath
        matlab_bin = which_matlab()
        if matlab_bin is None:
            raise ValueError("specify 'matlab_bin' in cfg file")
    # Get the extension
    extcmd = esc(os.path.join(matlab_bin, "mexext"))
    extension = subprocess.check_output(extcmd, shell=use_shell)
    extension = extension.decode('utf-8').rstrip('\r\n')

    # Build the mex file
    mex = esc(os.path.join(matlab_bin, "mex"))
    paths = "-L%(zmq_lib)s -I%(zmq_inc)s" % cfg
    make_cmd = '%s -O %s -lzmq ./src/messenger.c' % (mex, paths)
    if static:
        make_cmd += ' -DZMQ_STATIC'
    do_build(make_cmd, 'messenger.%s' % extension)
604247
def find_matlab_root():
    
    matlab_root = None

    path_dirs = os.environ.get("PATH").split(os.pathsep)
    for path_dir in path_dirs:
        candidate = realpath(join(path_dir, 'matlab'))
        if isfile(candidate) or isfile(candidate + '.exe'):
            matlab_root = dirname(dirname(candidate))
            break

    return matlab_root
1290567
def run(self):
        '''
        

        '''

        try:

            # Load raw data
            log.info("Loading target data...")
            self.load_tpf()
            self.mask_planets()
            self.plot_aperture([self.dvs.top_right() for i in range(4)])
            self.init_kernel()
            M = self.apply_mask(np.arange(len(self.time)))
            self.cdppr_arr = self.get_cdpp_arr()
            self.cdpp_arr = np.array(self.cdppr_arr)
            self.cdppv_arr = np.array(self.cdppr_arr)
            self.cdppr = self.get_cdpp()
            self.cdpp = self.cdppr
            self.cdppv = self.cdppr

            log.info("%s (Raw): CDPP = %s" % (self.name, self.cdpps))
            self.plot_lc(self.dvs.left(), info_right='Raw', color='k')

            # Loop
            for n in range(self.pld_order):
                self.lam_idx += 1
                self.get_outliers()
                if n > 0 and self.optimize_gp:
                    self.update_gp()
                self.cross_validate(self.dvs.right(), info='CV%d' % n)
                self.cdpp_arr = self.get_cdpp_arr()
                self.cdppv_arr *= self.cdpp_arr
                self.cdpp = self.get_cdpp()
                self.cdppv = np.nanmean(self.cdppv_arr)
                log.info("%s (%d/%d): CDPP = %s" %
                         (self.name, n + 1, self.pld_order, self.cdpps))
                self.plot_lc(self.dvs.left(), info_right='LC%d' % (
                    n + 1), info_left='%d outliers' % len(self.outmask))

            # Save
            self.finalize()
            self.plot_final(self.dvs.top_left())
            self.plot_info(self.dvs)
            self.save_model()

        except:

            self.exception_handler(self.debug)
508853
def open(self):
        """"""
        self._serial.port = self._port
        self._serial.baudrate = self._baud
        self._serial.timeout = self._timeout
        self._serial.open()
        self._serial.flushInput()
        self._serial.flushOutput()
930730
def open(self):
        """"""

        self.hwman = HardwareManager(port=self._port)
        self.opened = True

        if self._connection_string is not None:
            try:
                self.hwman.connect_direct(self._connection_string)
            except HardwareError:
                self.hwman.close()
                raise

        elif self._connect_id is not None:
            try:
                self.hwman.connect(self._connect_id)
            except HardwareError:
                self.hwman.close()
                raise
86099
def launch():
  """"""
  validate_flags()
  job_spec = configure_job()
  job_name = job_spec["jobId"]
  tf.logging.info("Launching job %s with ML Engine spec:\n%s", job_name,
                  pprint.pformat(job_spec))
  assert confirm()
  train_dir = FLAGS.output_dir
  t2t_tar = tar_and_copy_t2t(train_dir)
  configure_trainer_package(job_spec, t2t_tar)
  if FLAGS.t2t_usr_dir:
    usr_tar = tar_and_copy_usr_dir(FLAGS.t2t_usr_dir, train_dir)
    configure_usr_dir(job_spec, usr_tar)
  launch_job(job_spec)
  tf.logging.info("Launched %s. See console to track: %s.", job_name,
                  CONSOLE_URL)
  tf.logging.info("Interact with the training job from the command line:")
  tf.logging.info("Abort job: gcloud ml-engine jobs cancel %s", job_name)
  tf.logging.info("Stream logs: gcloud ml-engine jobs stream-logs %s", job_name)
  tf.logging.info("Open tensorboard: tensorboard --logdir %s", train_dir)
1267497
def main():
    
    fmt,plot='svg',0
    if '-h' in sys.argv: # check if help is needed
        print(main.__doc__)
        sys.exit() # graceful quit
    elif '-f' in sys.argv: # ask for filename
        ind=sys.argv.index('-f')
        file=sys.argv[ind+1]
        f=open(file,'r')
        input=f.readlines()
    Data=[]
    for line in input:
        line.replace('\n','')
        if '\t' in line:   # read in the data from standard input
            rec=line.split('\t') # split each line on space to get records
        else:
            rec=line.split() # split each line on space to get records
        Data.append(float(rec[0]))
    
#
    if len(Data) >=10: 
        QQ={'unf1':1}
        pmagplotlib.plot_init(QQ['unf1'],5,5)
        pmagplotlib.plot_qq_unf(QQ['unf1'],Data,'QQ-Uniform') # make plot
    else:
        print('you need N> 10')
        sys.exit()
    pmagplotlib.draw_figs(QQ) 
    files={}
    for key in list(QQ.keys()):
        files[key]=key+'.'+fmt 
    if pmagplotlib.isServer:
        black     = '#000000'
        purple    = '#800080'
        titles={}
        titles['eq']='Equal Area Plot'
        EQ = pmagplotlib.add_borders(EQ,titles,black,purple)
        pmagplotlib.save_plots(QQ,files)
    elif plot==1:
        files['qq']=file+'.'+fmt 
        pmagplotlib.save_plots(QQ,files)
    else:
        ans=input(" S[a]ve to save plot, [q]uit without saving:  ")
        if ans=="a": pmagplotlib.save_plots(QQ,files)
867262
def open(self):
        
        if self._status == "opened":
            return

        self.reset()
        self._loading = True
        self._status = "opened"

        path = self._topology_file()
        if not os.path.exists(path):
            self._loading = False
            return
        try:
            shutil.copy(path, path + ".backup")
        except OSError:
            pass
        try:
            project_data = load_topology(path)

            #load meta of project
            keys_to_load = [
                "auto_start",
                "auto_close",
                "auto_open",
                "scene_height",
                "scene_width",
                "zoom",
                "show_layers",
                "snap_to_grid",
                "show_grid",
                "show_interface_labels"
            ]

            for key in keys_to_load:
                val = project_data.get(key, None)
                if val is not None:
                    setattr(self, key, val)

            topology = project_data["topology"]
            for compute in topology.get("computes", []):
                yield from self.controller.add_compute(**compute)
            for node in topology.get("nodes", []):
                compute = self.controller.get_compute(node.pop("compute_id"))
                name = node.pop("name")
                node_id = node.pop("node_id", str(uuid.uuid4()))
                yield from self.add_node(compute, name, node_id, dump=False, **node)
            for link_data in topology.get("links", []):
                if 'link_id' not in link_data.keys():
                    # skip the link
                    continue
                link = yield from self.add_link(link_id=link_data["link_id"])
                if "filters" in link_data:
                    yield from link.update_filters(link_data["filters"])
                for node_link in link_data["nodes"]:
                    node = self.get_node(node_link["node_id"])
                    port = node.get_port(node_link["adapter_number"], node_link["port_number"])
                    if port is None:
                        log.warning("Port {}/{} for {} not found".format(node_link["adapter_number"], node_link["port_number"], node.name))
                        continue
                    if port.link is not None:
                        log.warning("Port {}/{} is already connected to link ID {}".format(node_link["adapter_number"], node_link["port_number"], port.link.id))
                        continue
                    yield from link.add_node(node, node_link["adapter_number"], node_link["port_number"], label=node_link.get("label"), dump=False)
                if len(link.nodes) != 2:
                    # a link should have 2 attached nodes, this can happen with corrupted projects
                    yield from self.delete_link(link.id, force_delete=True)
            for drawing_data in topology.get("drawings", []):
                yield from self.add_drawing(dump=False, **drawing_data)

            self.dump()
        # We catch all error to be able to rollback the .gns3 to the previous state
        except Exception as e:
            for compute in list(self._project_created_on_compute):
                try:
                    yield from compute.post("/projects/{}/close".format(self._id))
                # We don't care if a compute is down at this step
                except (ComputeError, aiohttp.web.HTTPNotFound, aiohttp.web.HTTPConflict, aiohttp.ServerDisconnectedError):
                    pass
            try:
                if os.path.exists(path + ".backup"):
                    shutil.copy(path + ".backup", path)
            except (PermissionError, OSError):
                pass
            self._status = "closed"
            self._loading = False
            if isinstance(e, ComputeError):
                raise aiohttp.web.HTTPConflict(text=str(e))
            else:
                raise e
        try:
            os.remove(path + ".backup")
        except OSError:
            pass

        self._loading = False
        # Should we start the nodes when project is open
        if self._auto_start:
            # Start all in the background without waiting for completion
            # we ignore errors because we want to let the user open
            # their project and fix it
            asyncio.async(self.start_all())
766060
private function open()
    {
        if (null === ($this->handle = fopen($this->file, 'rb'))) {
            $this->handle = null;

            throw new RuntimeException(
                sprintf(
                    'The file "%s" could not be opened for reading.',
                    $this->file
                )
            );
        }
    }
1228502
def open(self, mode=None):
        

        if mode is None:
            mode = self.mode
        elif mode not in ['r', 'w', 'a']:
            raise ValueError('Invalid mode! Modes: [\'a\', \'r\', \'w\']')

        if self._file is None:
            self._file = h5py.File(self.path, mode=mode)
430671
def main():
    """"""
    # Initialization variables - update to change your model and execution context
    model_prefix = "FCN8s_VGG16"
    epoch = 19

    # By default, MXNet will run on the CPU. Change to ctx = mx.gpu() to run on GPU.
    ctx = mx.cpu()

    fcnxs, fcnxs_args, fcnxs_auxs = mx.model.load_checkpoint(model_prefix, epoch)
    fcnxs_args["data"] = mx.nd.array(get_data(args.input), ctx)
    data_shape = fcnxs_args["data"].shape
    label_shape = (1, data_shape[2]*data_shape[3])
    fcnxs_args["softmax_label"] = mx.nd.empty(label_shape, ctx)
    exector = fcnxs.bind(ctx, fcnxs_args, args_grad=None, grad_req="null", aux_states=fcnxs_args)
    exector.forward(is_train=False)
    output = exector.outputs[0]
    out_img = np.uint8(np.squeeze(output.asnumpy().argmax(axis=1)))
    out_img = Image.fromarray(out_img)
    out_img.putpalette(get_palette())
    out_img.save(args.output)