function [sshcmd,bsubcmd,info] = wrapjobcmd_bsub_ssh(jobcmd,varargin)

[info.jobname,info.resfile,info.reserrfile,info.ncores] = myparse(varargin,...
  'jobname',sprintf('job%s',datestr(now,'yyyymmddTHHMMSS')),...
  'resfile',[tempname,'.out'],...
  'reserrfile',[tempname,'.err'],...
  'ncores',1);

bsubcmd = sprintf('bsub -n %d -J %s -o %s -e %s "%s"',info.ncores,info.jobname,info.resfile,info.reserrfile,strrep(jobcmd,'"','\"'));
sshcmd = sprintf('ssh login1 "%s"',strrep(strrep(bsubcmd,'\','\\'),'"','\"'));


function [success] = modelAddOutsideDependencies(dependencyName,varargin)
	% Used to request certain outside dependencies from users.
	% Biafra Ahanonu
	% started: 2017.11.16 [16:50:28]
	% inputs
		%
	% outputs
		%

	[success] = ciapkg.io.modelAddOutsideDependencies(dependencyName,'passArgs', varargin);
end


function ppFlipper(data)
% ppFlipper(data)
%
% write data on the parallelport;
% It assumes the parallelport to be at IO_ADDR.
%

% kraulem 07/07

global IO_ADDR
ppWriteStay(IO_ADDR, data);
return;


function insidepoly_sglengine

error('Please compile MEX files by runing insidepoly_install');


%XOR Datafile overload


function dep = cfg_dep(varargin)

% This is the configuration dependency class
%
% Data structure
% ==============
% Description fields
%    * sname        - display name of dependency source
%    * src_exbranch - subsref/subsasgn struct referencing the dependency
%                     source exbranch
%    * src_output   - subsref/subsasgn struct referencing the dependency
%                     source output item
%    * tname        - display name of dependency target
%    * tgt_exbranch - subsref/subsasgn struct referencing the dependency
%                     target exbranch in the config tree
%    * tgt_input    - subsref/subsasgn struct referencing the dependency
%                     target item in the config tree
%    * tgt_spec     - an cfg_findspec that can be used to restrict matches
%                     of this dependency to certain input items - this will
%                     be checked in subsasgn checks for cfg_items. Defaults
%                     to {} - match all cfg_items.
%    * jtsubs       - subsref/subsasgn struct referencing the dependency
%                     target item in the job tree (this is currently not
%                     used and may be removed in future)
%
% Public Methods
% ==============
%
% Public internal Methods
% =======================
%    * subsasgn
%    * subsref
%    * display
%    * disp
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: cfg_dep.m 4863 2012-08-27 08:09:23Z volkmar $

rev = '$Rev: 4863 $'; %#ok

dep = class(struct('tname','Target', ...
                   'tgt_exbranch', struct('type',{},'subs',{}), ...
                   'tgt_input', struct('type',{},'subs',{}), ...
                   'tgt_spec', {{}}, ...
                   'jtsubs', struct('type',{},'subs',{}), ...
                   'sname','Source', ...
                   'src_exbranch', struct('type',{},'subs',{}), ...
                   'src_output', struct('type',{},'subs',{})), ...
            'cfg_dep');
switch nargin
    case 0
        return;
    case 1
        if isa(varargin{1},'cfg_dep')
            dep = varargin{1};
        else
            dep.sname                          = varargin{1};
        end;
    case 2
        dep.sname                              = varargin{1};
        dep.src_exbranch(1:numel(varargin{2})) = varargin{2};
    case 3
        dep.sname                              = varargin{1};
        dep.src_exbranch(1:numel(varargin{2})) = varargin{2};
        dep.src_output(1:numel(varargin{3}))   = varargin{3};
    case 4
        dep.sname                              = varargin{1};
        dep.src_exbranch(1:numel(varargin{2})) = varargin{2};
        dep.src_output(1:numel(varargin{3}))   = varargin{3};
        dep.tgt_spec                           = varargin{4};
    case 5
        dep.sname                              = varargin{1};
        dep.src_exbranch(1:numel(varargin{2})) = varargin{2};
        dep.src_output(1:numel(varargin{3}))   = varargin{3};
        dep.tgt_spec                           = varargin{4};
        dep.jtsubs(1:numel(varargin{5}))       = varargin{5};
    case 6
        dep.sname                              = varargin{1};
        dep.src_exbranch(1:numel(varargin{2})) = varargin{2};
        dep.src_output(1:numel(varargin{3}))   = varargin{3};
        dep.tgt_spec                           = varargin{4};
        dep.jtsubs(1:numel(varargin{5}))       = varargin{5};
        dep.tname                              = varargin{6};
    case 7
        dep.sname                              = varargin{1};
        dep.src_exbranch(1:numel(varargin{2})) = varargin{2};
        dep.src_output(1:numel(varargin{3}))   = varargin{3};
        dep.tgt_spec                           = varargin{4};
        dep.jtsubs(1:numel(varargin{5}))       = varargin{5};
        dep.tname                              = varargin{6};
        dep.tgt_exbranch(1:numel(varargin{7})) = varargin{7};
    case 8
        dep.sname                              = varargin{1};
        dep.src_exbranch(1:numel(varargin{2})) = varargin{2};
        dep.src_output(1:numel(varargin{3}))   = varargin{3};
        dep.tgt_spec                           = varargin{4};
        dep.jtsubs(1:numel(varargin{5}))       = varargin{5};
        dep.tname                              = varargin{6};
        dep.tgt_exbranch(1:numel(varargin{7})) = varargin{7};
        dep.tgt_input(1:numel(varargin{8}))    = varargin{8};
    otherwise
        cfg_message('matlabbatch:constructor:nargin', 'Wrong number of arguments.');
end;


function setGuidataField(fig,fieldName,x)
% Sets a single field from fig's guidata(), assumed to be a scalar struct,
% to the value x.

g=guidata(fig);
g.(fieldName)=x;
guidata(fig,g);

end


function stop(robot)

    robot.mode('off');


function outputDir = GetOutputDataDir()

file_masterdir = GetMasterFileDir;
outputDir = fullfile(file_masterdir,'\!Proj FishExplorer\output');

end


function h = beagle(varargin)
% BEAGLE Establish connection with BeagleBoard hardware.
%
% C = beagle creates a connection object, C, for communicating with
% BeagleBoard hardware.
%
% C = beagle(hostname, username, password, builddir) allows specification
% of non-default values for the IP address, user name, password, and the
% build directory on the BeagleBoard hardware.
%
% Methods:
%
% [status, msg] = C.connect tests SSH connection to the BeagleBoard
% hardware. If connection is successful, the return value for status is
% zero. Otherwise an error has occurred during connection. The output
% argument msg provides diagnostic messages if the connection fails.
%
% [status, msg] = C.execute('command') executes the Linux command on the
% BeagleBoard hardware and returns the resulting status and standard output.
%
% C.execute('command', true) executes the Linux command on the BeagleBoard
% hardware and forces the output to the MATLAB command window.
%
% C.run(modelName) runs the previously compiled Simulink model on the
% BeagleBoard hardware.
%
% C.stop(modelName) stops the execution of the Simulink model on the
% BeagleBoard hardware.
%
% C.openShell('ssh') launches a SSH terminal session. Once the terminal
% session is started, you can execute commands on the BeagleBoard hardware
% interactively.
%
% C.openShell('serial') launches a serial terminal session. You must have a
% serial connection between your host computer and the BeagleBoard hardware.
% The parameters of the serial connection must be set to the following:
%
% Baud Rate   : 115200
% Data bits   : 8
% Stop bits   : 1
% Parity      : None
% Flow control: None
%
% Examples:
%
%    C = beagle;
%    C.execute('ls -al ~', true);
%
%  lists the contents of the home directory for the current user on the
%  BeagleBoard hardware.
%
%    [st, msg] = C.connect
%
%  tests the SSH connection to the BeagleBoard hardware.
%
%    C.run('beagleboard_gettingstarted')
%
%  runs the model 'beagleboard_gettingstarted' on the BeagleBoard hardware.
%  The model must have run previously on the BeagleBoard hardware for this
%  method to work properly.
%
%    C.openShell('ssh')
%
%  launches a SSH terminal session. You must enter the user name and the
%  password to login to the Linux shell running over SSH. Once logged in,
%  you can execute interactive shell commands.

%   Copyright 2012 The MathWorks, Inc.

narginchk(0, 4);
if nargin > 0
    h = realtime.internal.getLinuxServicesHandle('BeagleBoard', varargin{:});
else
    h = realtime.internal.getLinuxServicesHandle('BeagleBoard');
end

end


function help_mex

d = dir('*.mexsg64');		% ".dll'

for i = 1:length(d)
	n = d(i).name;
	[path,name,ext] = fileparts(n);
	myeval(name, 'disp(lasterr)');
end

function myeval(s1, s2)

disp(s1)
eval(s1, s2)
disp('')


MicroTests;
FemTests;


display('- - - - - - 0 - - - - - -')
display('Closing open figures and clearing variables...')
display('- - - - - - - - - - - - -')
clear all,close all,set(0,'DefaultFigureWindowStyle','docked')

github-repos/MATLAB/Sable-mcbench-benchmarks/mcbench-benchmarks-ba13b2f0296ef49491b95e3f984c7c41fccdb6d8/34985-monte-carlo-simulation-of-three-dimensional-grain-growth-code-version-no-1-basic/Monte Carlo Simulation Q-state Potts model 3D square-lattice - microstructure/InitialThings_3D_QPOTTS.m


%GETDATA Get data of datafile


%ZMQ socket communication via ZMQ
%
% ZMQ is a wrapper for libzmq, which exposes a simple ZMQ REP
% endpoint. You can receive messages from the socket, and send messages
% to the socket.
%
% ZMQ Methods:
%   receive - read a message from the socket
%   send    - write a message to the socket

% Copyright (c) 2016, Bastian Bechtold
% This code is published under the terms of the BSD 3-clause license

classdef ZMQ < handle
    properties (Access=private)
        context
        socket
    end
    methods
        function obj = ZMQ(libname, address)
            ZMQ_REP = 4;
            try
                if not(libisloaded('libzmq'))
                    [notfound, warnings] = ...
                        loadlibrary(libname, 'transplantzmq.h', ...
                                    'alias', 'libzmq');
                    % the library did not contain the functions we need:
                    assert(isempty(notfound), 'Could not load ZMQ library')
                end
                obj.context = calllib('libzmq', 'zmq_ctx_new');
                assert(not(obj.context.isNull), ...
                       'zmq_ctx_new failed: Could not create context');
                obj.socket = calllib('libzmq', 'zmq_socket', obj.context, ZMQ_REP);
                assert(not(obj.socket.isNull), obj.errortext('zmq_socket'));
                err = calllib('libzmq', 'zmq_connect', obj.socket, address);
                assert(err == 0, obj.errortext('zmq_connect'));
            catch exception
                % print exception, since we probably don't have a working connection
                % to the transplant master yet for reporting errors properly:
                disp(['Error loading libzmq: ' exception.message]);
                throw(exception);
            end
        end

        function str = receive(obj)
            msg = libstruct('zmq_msg_t', struct('hidden', zeros(1, 64, 'uint8')));
            calllib('libzmq', 'zmq_msg_init', msg); % always returns 0
            msglen = calllib('libzmq', 'zmq_msg_recv', msg, obj.socket, 0);
            assert(msglen >= 0, obj.errortext('zmq_msg_recv'));
            msgptr = calllib('libzmq', 'zmq_msg_data', msg);
            if not(msgptr.isNull)
                setdatatype(msgptr, 'uint8Ptr', 1, msglen);
                str = uint8(msgptr.Value);
            else
                str = uint8([]);
            end
            err = calllib('libzmq', 'zmq_msg_close', msg);
            assert(err == 0, obj.errortext('zmq_msg_close'));
        end

        function send(obj, data)
            dataptr = libpointer('uint8Ptr', data);
            msglen = calllib('libzmq', 'zmq_send', obj.socket, dataptr, numel(data), 0);
            assert(msglen >= 0, obj.errortext('zmq_send'));
        end

        function delete(obj)
            % if we crashed in the constructor:
            if ~libisloaded('libzmq')
                return
            end
            err = calllib('libzmq', 'zmq_close', obj.socket);
            assert(err == 0, obj.errortext('zmq_close'));
            err = calllib('libzmq', 'zmq_ctx_term', obj.context);
            assert(err == 0, obj.errortext('zmq_ctx_term'));
            unloadlibrary('libzmq');
        end
    end

    methods (Hidden=true)
        function str = errortext(obj, instruction)
            base = 156384712;
            errno = calllib('libzmq', 'zmq_errno');
            switch errno
                case 4 % EINTR
                    if strcmp(instruction, 'zmq_ctx_term')
                        str = 'Termination was interrupted by a signal. It can be restarted if needed.';
                    elseif strcmp(instruction, 'zmq_send')
                        str = 'The operation was interrupted by delivery of a signal before the message was sent.';
                    elseif strcmp(instruction, 'zmq_msg_recv')
                        str = 'The operation was interrupted by delivery of a signal before a message was available.';
                    else
                        str = 'Interrupted system call';
                    end
                case 11 % EAGAIN
                    if strcmp(instruction, 'zmq_send')
                        str = 'Non-blocking mode was requested and the message cannot be sent at the moment.';
                    elseif strcmp(instruction, 'zmq_msg_recv')
                        str = 'Non-blocking mode was requested and no message are available at the moment.';
                    else
                        str = 'Try again';
                    end
                case 22 % EINVAL
                    if strcmp(instruction, 'zmq_socket')
                        str = 'The requested socket *type* is invalid.';
                    elseif strcmp(instruction, 'zmq_connect')
                        str = 'The endpoint supplied is invalid.';
                    else
                        str = 'Invalid argument';
                    end
                case 14 % EFAULT
                    if strcmp(instruction, 'zmq_socket') || strcmp(instruction, 'zmq_ctx_term')
                        str = 'The provided *context* is invalid.';
                    elseif strcmp(instruction, 'zmq_msg_close')
                        str = 'Invalid message';
                    elseif strcmp(instruction, 'zmq_msg_recv')
                        str = 'The message passed to the function was invalid.';
                    else
                        str = 'Invalid argument';
                    end
                case 24 % EMFILE
                    if strcmp(instruction, 'zmq_socket')
                        str = 'The limit on the total number of open ZMQ sockets has been reached.';
                    else
                        str = 'Too many open files';
                    end
                case base + 1 % ENOTSUP
                    str = 'The *zmq_send()* operation is not supported by this socket type.';
                case base + 2 % EPROTONOSUPPORT
                    str = 'The requested *transport* protocol is not supported.';
                case base + 9 % ENOTSOCK
                    str = 'The provided *socket* was invalid.';
                case base + 17 % EHOSTUNREACH
                    str = 'The message cannot be routed.';
                case base + 51 % EFSM
                    if strcmp(instruction, 'zmq_send')
                        str = 'The *zmq_send()* operation cannot be performed on this socket at the moment due to the socket not being in the appropriate state.';
                    else
                        str = 'socket not in appropriate state.';
                    end
                case base + 52 % ENOCOMPATPROTO
                    str = 'The requested *transport* protocol is not compatible with the socket type.';
                case base + 53 % ETERM
                    str = 'The ZMQ *context* associated with the specified *socket* was terminated.';
                case base + 54 % EMTHREAD
                    str = 'No I/O thread is available to accomplish the task.';
                otherwise
                    str = sprintf('Unknown error %d', errno);
            end
            str = sprintf('Error in %s: %s', instruction, str);
        end
    end
end


v=ver('matlab'); Release = v.Release;
switch Release
    case '(R2017a)'
        vivado = '2016.2';
    case '(R2017b)'
        vivado = '2017.4';
    case '(R2018b)'
        vivado = '2017.4';
end

if ispc
    hdlsetuptoolpath('ToolName', 'Xilinx Vivado', ...
        'ToolPath', ['C:\Xilinx\Vivado\',vivado,'\bin\vivado.bat']);
elseif isunix
    hdlsetuptoolpath('ToolName', 'Xilinx Vivado', ...
        'ToolPath', ['/opt/Xilinx/Vivado/',vivado,'/bin/vivado']);
end


% --------------------------------------------------------
% ObjectNet3D
% Copyright (c) 2016 CVGL Stanford University
% Licensed under The MIT License [see LICENSE for details]
% Written by Yu Xiang
% --------------------------------------------------------
function opt = globals()

opt.root = '/datasets/ObjectNet3D';
opt.shapenetcore = '/var/Projects/ShapeNetCore.v1';


function data_dir = GetCurrentDataDir()
    data_dir = 'C:\Users\Xiu\Dropbox (Personal)\Janelia2015\GUI_data';
end


classdef MimRemoveDataset < MimGuiPlugin
    % MimRemoveDataset. Gui Plugin for removing a dataset.
    %
    %     You should not use this class within your own code. It is intended to
    %     be used by the gui of the TD MIM Toolkit.
    %
    %     MimRemoveDataset is a Gui Plugin for the MIM Toolkit.
    %     The gui will create a button for the user to run this plugin.
    %     Running this plugin will delete all results files from the current
    %     dataset results cache folder. Certain internal cache files will not be
    %     removed.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        ButtonText = 'Delete dataset'
        SelectedText = 'Delete dataset'
        ToolTip = 'Remove this dataset from the Toolkit'
        Category = 'Dataset'
        Visibility = 'Dataset'
        Mode = 'Toolbar'
        Icon = 'bin.png'
        Location = 3

        HidePluginInDisplay = false
        PTKVersion = '1'
        ButtonWidth = 6
        ButtonHeight = 1
    end

    methods (Static)
        function RunGuiPlugin(gui_app)
            % Delete files from the disk cache
            gui_app.DeleteThisImageInfo;
        end

        function enabled = IsEnabled(gui_app)
            enabled = gui_app.IsDatasetLoaded;
        end

        function is_selected = IsSelected(gui_app)
            is_selected = false;
        end
    end

end


function hRD = plugin_rd_tx
% Reference design definition

% Call the common reference design definition function
hRD = AnalogDevices.adrv9364z7020.common.plugin_rd('ccbob_lvds','Tx');
AnalogDevices.adrv9364z7020.common.add_io(hRD, 'Tx');


d


function commit = git_hash()
	[temp,commit] = system('git show --format=%H');
end


function color = prtPlotUtilClassColorUnlabeled

color = [0.6 0.6 0.6];


function full_mem(layer_idx)
    global mem;

end


classdef FilterOp < int32
    % enumeration used with the import routines
    % Each import routine takes a first argument that describes the behavior
    enumeration
        getDescription (0)
        getWebpage     (2)
        importCatalog  (1)
    end
end


function userfuncdir = FindUserFuncDir(obj)
global cfg

cfg = InitConfig(cfg);

userfuncdir = {};
dirnameApp = getAppDir();

rootdirRegsitry = [dirnameApp, 'FuncRegistry/UserFunctions/'];
if ~ispathvalid(rootdirRegsitry)
    rootdirRegsitry = filesepStandard([dirnameApp, '../FuncRegistry/UserFunctions/']);
    if ~ispathvalid(rootdirRegsitry)
    	return;
	end
end
userfuncdir{1} = rootdirRegsitry;
dirs = dir([userfuncdir{1}, '*']);
for ii = 1:length(dirs)
    if ~dirs(ii).isdir
        continue
    elseif strcmp(dirs(ii).name, '..') || strcmp(dirs(ii).name, '.')
        continue
    elseif strcmp(dirs(ii).name, 'Archive')
        obj.config = struct('InclArchivedFunctions','');
        obj.config.InclArchivedFunctions = cfg.GetValue('Include Archived User Functions');
        if strcmp(obj.config.InclArchivedFunctions, 'Yes')
            userfuncdir{end+1} = fullpath([userfuncdir{1}, 'Archive/']); %#ok<*AGROW>
        end
    elseif strcmp(dirs(ii).name, 'Sim')
        obj.config = struct('InclArchivedFunctions','');
        obj.config.InclArchivedFunctions = cfg.GetValue('Include Archived User Functions');
        if strcmp(obj.config.InclArchivedFunctions, 'Yes')
            userfuncdir{end+1} = fullpath([userfuncdir{1}, 'Sim/']); %#ok<*AGROW>
        end
    else
        userfuncdir{end+1} = filesepStandard(fullpath([userfuncdir{1}, dirs(ii).name]));
    end
end


function uiwaitvec(h)
while ~isempty(h)
  uiwait(h(1));
  h = h(ishandle(h));
end


%--- help for update_estimated_parameter_names ---
%
%  INTERNAL FUNCTION
%
%


function [ns_RESULT, LastError] = ns_GetLastErrorMsg();

%ns_GetLastErrorMsg   Retrieves the extended error message for the last
%error
%
%   Usage:
%      [ns_RESULT, LastError] = ns_GetLastErrorMsg
%
%   Description:
%       Returns the last error message in text form to LastError. This
%       function should be called immediately following a function whose
%       return value indicates that an error occurred. The maximum size of
%       the error message text is 256 characters.
%
%   Return Values:
%       LastError	Variable to receive the extended last error message.
%       ns_RESULT   This function returns ns_OK if the file is successfully
%                   opened. Otherwise one of the following error codes is
%                   generated:
%
%                       ns_LIBERROR	Library error
%
%   Copyright (C) 2003 Neuroshare Project
%   Author: Almut Branner
%   Last modification: 2/21/2003

[ns_RESULT, LastError] = mexprog(17);


function varargout = AnnotationUI(varargin)
% DATAANNOTATIONUI MATLAB code for AnnotationUI.fig
%      DATAANNOTATIONUI, by itself, creates a new DATAANNOTATIONUI or raises the existing
%      singleton*.
%
%      H = DATAANNOTATIONUI returns the handle to a new DATAANNOTATIONUI or the handle to
%      the existing singleton*.
%
%      DATAANNOTATIONUI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in DATAANNOTATIONUI.M with the given input arguments.
%
%      DATAANNOTATIONUI('Property','Value',...) creates a new DATAANNOTATIONUI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before AnnotationUI_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to AnnotationUI_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help AnnotationUI

% Last Modified by GUIDE v2.5 17-Dec-2019 09:16:07

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @AnnotationUI_OpeningFcn, ...
                   'gui_OutputFcn',  @AnnotationUI_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before AnnotationUI is made visible.
function AnnotationUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to AnnotationUI (see VARARGIN)

% Choose default command line output for AnnotationUI
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes AnnotationUI wait for user response (see UIRESUME)
% uiwait(handles.mainFigure);

% --- Outputs from this function are returned to the command line.
function varargout = AnnotationUI_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

% --- Executes on selection change in classesList.
function classesList_Callback(hObject, eventdata, handles)
% hObject    handle to classesList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns classesList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from classesList

% --- Executes during object creation, after setting all properties.
function classesList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to classesList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on selection change in fileNamesList.
function fileNamesList_Callback(hObject, eventdata, handles)
% hObject    handle to fileNamesList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns fileNamesList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from fileNamesList

% --- Executes during object creation, after setting all properties.
function fileNamesList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to fileNamesList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in showMarkersCheckBox.
function showMarkersCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to showMarkersCheckBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of showMarkersCheckBox

% --- Executes on button press in laxCheckBox.
function laxCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to laxCheckBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of laxCheckBox

% --- Executes on button press in layCheckBox.
function layCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to layCheckBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of layCheckBox

% --- Executes on button press in lazCheckBox.
function lazCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to lazCheckBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of lazCheckBox

% --- Executes on button press in energyCheckBox.
function energyCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to energyCheckBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of energyCheckBox

% --- Executes on button press in saveButton.
function saveButton_Callback(hObject, eventdata, handles)
% hObject    handle to saveButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in findPeaksButton.
function findPeaksButton_Callback(hObject, eventdata, handles)
% hObject    handle to findPeaksButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in loadDataButton.
function loadDataButton_Callback(hObject, eventdata, handles)
% hObject    handle to loadDataButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on selection change in signalsList.
function signalsList_Callback(hObject, eventdata, handles)
% hObject    handle to signalsList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns signalsList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from signalsList

% --- Executes during object creation, after setting all properties.
function signalsList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to signalsList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in visualizeButton.
function visualizeButton_Callback(hObject, eventdata, handles)
% hObject    handle to visualizeButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on selection change in signalComputerList.
function signalComputerList_Callback(hObject, eventdata, handles)
% hObject    handle to signalComputerList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns signalComputerList contents as cell array
%        contents{get(hObject,'Value')} returns selected item from signalComputerList

% --- Executes during object creation, after setting all properties.
function signalComputerList_CreateFcn(hObject, eventdata, handles)
% hObject    handle to signalComputerList (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in addRangeAnnotationButton.
function addRangeAnnotationButton_Callback(hObject, eventdata, handles)
% hObject    handle to addRangeAnnotationButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in peaksCheckBox.
function peaksCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to peaksCheckBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of peaksCheckBox

% --- Executes on button press in myCheckbox.
function myCheckbox_Callback(hObject, eventdata, handles)
% hObject    handle to myCheckbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of myCheckbox

% --- Executes on key press with focus on mainFigure or any of its controls.
function mainFigure_WindowKeyPressFcn(hObject, eventdata, handles)
% hObject    handle to mainFigure (see GCBO)
% eventdata  structure with the following fields (see MATLAB.UI.FIGURE)
%	Key: name of the key that was pressed, in lower case
%	Character: character interpretation of the key(s) that was pressed
%	Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in showRangesCheckBox.
function showRangesCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to showRangesCheckBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of showRangesCheckBox

% --- Executes on button press in showEventsCheckBox.
function showEventsCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to showEventsCheckBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of showEventsCheckBox

% --- Executes on button press in visualizeButton.
function pushbutton6_Callback(hObject, eventdata, handles)
% hObject    handle to visualizeButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in addSignalButton.
function addSignalButton_Callback(hObject, eventdata, handles)
% hObject    handle to addSignalButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in selectAllCheckBox.
function selectAllCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to selectAllCheckBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of selectAllCheckBox

% --- Executes on button press in loadVideoCheckBox.
function loadVideoCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to loadVideoCheckBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of loadVideoCheckBox

% --- Executes on button press in videoSynchronizationButton.
function videoSynchronizationButton_Callback(hObject, eventdata, handles)
% hObject    handle to videoSynchronizationButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in synchronizeVideoCheckBox.
function synchronizeVideoCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to synchronizeVideoCheckBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of synchronizeVideoCheckBox

function currentSampleText_Callback(hObject, eventdata, handles)
% hObject    handle to currentSampleText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of currentSampleText as text
%        str2double(get(hObject,'String')) returns contents of currentSampleText as a double

% --- Executes during object creation, after setting all properties.
function currentSampleText_CreateFcn(hObject, eventdata, handles)
% hObject    handle to currentSampleText (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in suggestAnnotationsCheckBox.
function suggestAnnotationsCheckBox_Callback(hObject, eventdata, handles)
% hObject    handle to suggestAnnotationsCheckBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of suggestAnnotationsCheckBox

% --- Executes on button press in autoAnnotateButton.
function autoAnnotateButton_Callback(hObject, eventdata, handles)
% hObject    handle to autoAnnotateButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% --- Executes on button press in resetButton.
function resetButton_Callback(hObject, eventdata, handles)
% hObject    handle to resetButton (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


function [isValid, errMsg] = validate_patient_module(dcmobj)
%"validate_patient_module"
%   Takes a Java dcmobj that contains the fields representing a patient,
%   and checks the validity of the fields and their contents.  This
%   includes a general check of fields based on type (Class 1,2,3,1C,2C)
%   and individual field check for any fields with special conditions on
%   them.
%
%JRA 06/12/06
%
%Usage:
%   [isValid, errMsg] = validate_patient_module(dcmobj)
%
% Copyright 2010, Joseph O. Deasy, on behalf of the CERR development team.
%
% This file is part of The Computational Environment for Radiotherapy Research (CERR).
%
% CERR development has been led by:  Aditya Apte, Divya Khullar, James Alaly, and Joseph O. Deasy.
%
% CERR has been financially supported by the US National Institutes of Health under multiple grants.
%
% CERR is distributed under the terms of the Lesser GNU Public License.
%
%     This version of CERR is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
%
% CERR is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
% without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
% See the GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with CERR.  If not, see <http://www.gnu.org/licenses/>.

%Set cache buffer to true.
buf = 1;

%Set character set to [] for now.
cs = [];

%Default to valid, no error message.
isValid = 1; errMsg = '';

%Get the parent of the passed dcmobj, in case the validation process
%requires checking tags in other modules.
parent = dcmobj.getParent;
if ~isempty(parent)
    dcmobj = parent;
else
    %Do nothing.  This is the root object.
end

%Get the tags for the patient module.
[Class_1, Class_2, Class_3, Class_1C, Class_2C] = patient_module_tags;

%Send tags and dcmobj for general checking of field format and presence.
%See documentation of validate_general_fields.
[isValid, errMsg] = validate_general_fields(dcmobj, Class_1, Class_2, Class_3, Class_1C, Class_2C);
if ~isValid
    return;
end

%Create an iterator over the dcmobj to inspect each element
it = dcmobj.iterator;

%-----------------------Individual Field Checking-------------------------%
%Switch over top level tags in patient module, with individual handling for
%each tag that requires verification beyond the general field validation
%performed above.
while it.hasNext

    el  = it.next;
    tag = el.tag;
    switch tag
        case hex2dec('00100040')
            %"Patient's Sex" must contain M, F, O or null.
            validValues = {'M', 'F', 'O', ''};
            val = char(el.getString(cs, buf));
            if ~ismember(val, validValues);
               isValid      = 0;
               [name, hex]  = tag2strings(tag, dcmobj);
               errMsg       = [hex ' "' name '" must contain M, F, O or null.'];
               return;
            end

        case hex2dec('00081120')
            %Handle Referenced Patient Sequence here.
            [isValid, errMsg] = validate_referenced_patient_sequence(el, dcmobj);
            if ~isValid
                return;
            end

        case hex2dec('00120062')
            %"Patient Identity Removed" must contain YES, NO or null.
            validValues = {'YES', 'NO', ''};
            val = char(el.getString(cs, buf));
            if ~ismember(val, validValues);
               isValid      = 0;
               [name, hex]  = tag2strings(tag, dcmobj);
               errMsg       = [hex ' "' name '" must contain YES, NO or null.'];
               return;
            end

            %In addition, if YES, at least one of the two "de-identification
            %method" elements must be present.
            if strcmpi(val, 'YES') & ~dcmobj.contains(hex2dec('00120063')) & ~dcmobj.contains(hex2dec('00120064'))
               isValid      = 0;
               [name, hex]  = tag2strings(tag, dcmobj);
               errMsg       = [hex ' "' name '" contains YES, but no de-identification element is present.'];
               return;
            end

        case hex2dec('00120064')
            %Handle de-identification Method Code Sequence here.
            [isValid, errMsg] = validate_deidentification_method_code_sequence(el, dcmobj);
            if ~isValid
                return;
            end

        otherwise
            %Tag does not require special handling or is not in the patient
            %module.
    end

end

function [isValid, errMsg] = validate_deidentification_method_code_sequence(el, dcmobj)
%"validate_deidentification_method_code_sequence"
%   Validates the passed sequence element.
n   = el.countItems;
tag = el.tag;
isValid = 1; errMsg = '';

%Deidentification method code sequence must contain one or more child elements.
if n < 1
    isValid     = 0;
    [name, hex] = tag2strings(tag, dcmobj);
    errMsg      = [hex ' "' name '" must contain one or more elements.'];
end

for i=0:n-1
   childobj = el.getDicomObject(i);
   %Send each child object for independent validation by the macro's
   %validator.
   [isValid, errMsg] = validate_code_sequence_macro(dcmobj);
   if ~isValid
       return;
   end
end

function [isValid, errMsg] = validate_referenced_patient_sequence(el, dcmobj)
%"validate_referenced_patient_sequence"
%   Validates the passed sequence element.
n   = el.countItems;
tag = el.tag;
isValid = 1; errMsg = '';

%Referenced patient sequence must contain exactly one child element.
if n ~= 1
    isValid     = 0;
    [name, hex] = tag2strings(tag, dcmobj);
    errMsg      = [hex ' "' name '" must contain exactly one element.'];
end

%Pass the child elements for general validation, as Class 1 since
%conditions for their existance have been met.
Class_1 = hex2dec({'00081150','00081155'});
for i=0:n-1
    childobj = el.getDicomObject(i);
    [isValid, errMsg] = validate_general_fields(childobj, Class_1, [], [], [], []);
end


function imgExt = getImgExt(seqFolder)
% return image extension including the dot
% e.g.   '.jpg'

imgExt = '.jpg';


function homeDirName=GetUserHomeDirName()

if isunix() || ismac()
  homeDirName=getenv('HOME');
else
  % Windows
  homeDriveName=getenv('%HOMEDRIVE%');
  homeDirName=getenv('%HOMEDIR%');
  homeDirName=fullfile(homeDriveName,homeDirName);
end

end


function movie = close (movie)
% CLOSE (avi class name) closes the class deletes all values
% NOTE: You must set the class equal to this function

fclose (movie.fid);
clear movie;


classdef BadFixture < TestCase

    methods
        function self = BadFixture(name)
            self = self@TestCase(name);
        end

        function setUp(self)
            throw(MException('setUpError:BadFixture', ...
                'BadFixture setUp method always throws exception'));
        end

        function testMethod(self)
        end
    end
end


function urband(varargin)

	query = reshape(transpose([strvcat(varargin{:}),[repmat('+',size(strvcat(varargin{:}),1)-1,1);' ']]),1,[]);

	url = ['''http://www.urbandictionary.com/define.php?term=',query,''''];

	url(url==' ') = [];

	eval(['web ', url ,' -browser'])

end


function v = isglobalpath(path)

v = (~ispc && ~isempty(path) && path(1) == '/') || ...
  (ispc && ~isempty(regexp(path,'^[A-Z]:[\\/]','once')));


%--- help for parameter_parsing_tool ---
%
%  INTERNAL FUNCTION
%
%


function varargout = vertcat(varargin)

% function varargout = vertcat(varargin)
% Prevent vertcat for cfg_item objects.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: vertcat.m 1862 2008-06-30 14:12:49Z volkmar $

rev = '$Rev: 1862 $'; %#ok

cfg_message('matlabbatch:cfg_item:cat', ['Concatenation of cfg_item objects is ' ...
                    'not allowed.']);


classdef BoundaryMeshCreator < handle

    methods (Access = public, Static)

        function obj = create(cParams)
            f = BoundaryMeshCreatorFactory();
            obj = f.create(cParams);
        end

    end

end


function hB = plugin_board(board)
% Use Plugin API to create board plugin object

hB = hdlcoder.Board;

% Target Board Information
hB.BoardName    = sprintf('AnalogDevices ADRV9371 %s', upper(board));

% FPGA Device
hB.FPGAVendor   = 'Xilinx';

% Determine the device based on the board
switch(upper(board))
    case 'ZC706'
        hB.FPGAFamily   = 'Zynq';
        hB.FPGADevice   = sprintf('xc7%s', 'z045');
        hB.FPGAPackage  = 'ffg900';
        hB.FPGASpeed    = '-2';
    case 'ZCU102'
        hB.FPGAFamily   = 'Zynq UltraScale+';
        hB.FPGADevice   = sprintf('xc%s', 'zu9eg-ffvb1156-2-e');
        hB.FPGAPackage  = '';
        hB.FPGASpeed    = '';
    otherwise
        hB.FPGAFamily   = 'Zynq UltraScale+';
        hB.FPGADevice   = sprintf('xc%s', 'zu9eg-ffvb1156-2-e');
        hB.FPGAPackage  = '';
        hB.FPGASpeed    = '';
end

% Tool Info
hB.SupportedTool = {'Xilinx Vivado'};

% FPGA JTAG chain position
hB.JTAGChainPosition = 2;

%% Add interfaces
% Standard "External Port" interface


function fid = logfileinit(logfile)
% fid = logfileinit(logfile)
fid = fopen(logfile,'wt');
fprintf(fid,'Computation: %s\n\n', datestr(now));


function ok = all_set_item(item)

% function ok = all_set_item(item)
% Perform within-item all_set check. For branches, this is always true.
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: all_set_item.m 1716 2008-05-23 08:18:45Z volkmar $

rev = '$Rev: 1716 $'; %#ok
ok = true;


function bearpath = bearroot()
bearpath = fileparts(mfilename('fullpath'));
end


function IEEE80211n_open_graphics(blk, forceClose);
% forceClose: 1 = force figure to close; 0 = toggle open/close
gfig = findobj('type', 'figure', 'tag', blk);
if isempty(gfig)
    if ~forceClose
        gfig = openfig(get_param(blk, 'graphicsName'));
        set(gfig, 'tag', blk);
    end
else
    close(gfig);
end


function hP = plugin_board()
% Zynq Platform PCore
% Use Plugin API to create board plugin object

%   Copyright 2015 The MathWorks, Inc.

% Call the common board definition function
hP = AnalogDevices.adrv9371x.common.plugin_board('ZCU102');


RTW.TargetRegistry.getInstance('reset');


function ft_standalone(varargin)

% FT_STANDALONE is the entry function of the compiled FieldTrip application.
% The compiled application can be used to execute FieldTrip data analysis
% scripts.
%
% This function can be started on the interactive MATLAB command line as
%   ft_standalone script.m
%   ft_standalone script1.m script2.m ...
%   ft_standalone jobfile.mat
% or after compilation on the Linux/macOS command line as
%   fieldtrip.sh <MATLABROOT> script.m
%   fieldtrip.sh <MATLABROOT> script1.m script2.m ...
%   fieldtrip.sh <MATLABROOT> jobfile.mat
%
% It is possible to pass additional options on the MATLAB command line like
% this on the MATLAB command line
%   ft_standalone --option value scriptname.m
% or on the Linux/macOS command line
%   fieldtrip.sh <MATLABROOT> --option value scriptname.m
% The options and their values are automaticallly made available as local
% variables in the script execution environment.
%
% See also FT_COMPILE_STANDALONE

% Copyright (C) 2011-2018 by Robert Oostenveld
%
% This file is part of FieldTrip.
%
% megconnectome is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% megconnectome is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with megconnectome.  If not, see <http://www.gnu.org/licenses/>.

% this function uses assignin/evalin. The alternative is to use assign/eval
% but then the script execution might collide with local variables inside this
% megconnectome function
workspace = 'caller';

if nargin==0
  % show the help for the compiled application
  fprintf('You should start the compiled FieldTrip application like this:\n');
  fprintf('  fieldtrip <MATLABROOT>  script.m\n');
  fprintf('  fieldtrip <MATLABROOT>  script1.m script2.m ...\n');
  fprintf('  fieldtrip <MATLABROOT>  jobfile.mat\n');
  fprintf('\n');
  return
end

% separate the --options from the filenames
[options, varargin] = hcp_getopt(varargin{:});

if any(strcmp(options(1:2:end), 'version'))
  % only show the provenance information, do not run anything
  varargin = {};
end

% get the general provenance information (e.g. user and hostname)
prov = hcp_provenance;

for i=1:length(varargin)
  fname = varargin{i};

  % get the specific provenance information for the script
  % prov.script{i}.filename = fname;
  % prov.script{i}.md5sum   = hcp_md5sum(fname);

  % The following section with "which" does not work in the compiled application
  %
  %   if isempty(which(fname))
  %     error('The file %s cannot be found\n', fname);
  %   end
  %   % ensure that the script name includes the full path and extension
  %   fname = which(fname);

  [p, f, ext] = fileparts(fname);

  switch ext
    case '.m'
      if ~exist(fname, 'file')
        error('The script %s cannot be found\n',fname);
      end

      fid = fopen(fname);
      if fid == -1, error('Cannot open %s',fname); end
      S = fscanf(fid,'%c');
      fclose(fid);

      % store the script content in the provenance
      % prov.script{i}.content  = sprintf('\n%s\n', S);

      % capture all screen output in a diary file
      diary off
      diaryfile = tempname;
      diary(diaryfile);

      try
        % ensure that subsequent scripts do not interfere with each other
        % keep the ft_default global variable
        global ft_default
        localcopy = ft_default;
        evalin(workspace,'clear all');
        global ft_default
        ft_default = localcopy;

        % make the options available as local variables
        for j=1:2:length(options)
          key = options{j};
          val = options{j+1};

          if ismember(val(1), {'[', '{'})
            % the value is a string that represents an array
            evalin(workspace, sprintf('%s = %s;', key, val));
          elseif ismember(val(1), {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '+'}) && all(ismember(cellstr(val(:)), {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '+', '.', 'e'}))
            % the value is a string that represents a number
            evalin(workspace, sprintf('%s = %s;', key, val));
          else
            assignin(workspace, key, val);
          end
        end

        % add some information about the script to the global ft_default variable
        % this will be picked up by hcp_write_provenance
        % ft_default.prov.script = prov.script{i};

        % evaluate this script
        evalin(workspace,S);

        % remove the provenance information about the script
        % ft_default.prov.script = [];

      catch err
        % remove the provenance information about the script
        % ft_default.prov.script = [];

        fprintf('Execution failed: %s\n', fname);
        rethrow(err);
      end

    case '.mat'
      % The job input consists of a file like this
      %   /Users/robert/tmp/robert_mbp_p36978_b1_j001_input.mat
      % which after execution results in an output file
      %   /Users/robert/tmp/robert_mbp_p36978_b1_j001_output.mat

      if length(fname)<10
        error('The jobfile %s is incorrect\n',fname);
      elseif ~strcmp(fname(end-9:end), '_input.mat')
        error('The jobfile %s is incorrect\n',fname);
      end

      jobid = fname(1:end-10);
      [p, jobid] = fileparts(jobid);
      cd(p);

      % read the job input arguments from jobid_input.mat, delete the input file and execute the job
      qsubexec(jobid);

      if isempty(getenv('PBS_ENVIRONMENT'))
        % this suggests that the job is running outside of the torque environment, e.g. for local testing
        % execution of qsubexec is expected to result in a stdout and stderr log file from torque
        logout       = fullfile(p, sprintf('%s.o', jobid));
        logerr       = fullfile(p, sprintf('%s.e', jobid));
        fclose(fopen(logout, 'w'));
        fclose(fopen(logerr, 'w'));
      end

      % read the job results from jobid_output.mat, delete the output file
      % FIXME what to do with the output variable?
      argout = qsubget(jobid);
      disp(argout)

    otherwise
      error('Unknown input format for %s, should be *.m or *.mat\n',fname);
  end % switch type of input argument

  % force close all figures that were created
  close all

  diary off
  fid = fopen(diaryfile);
  if fid == -1, error('Cannot open %s',diaryfile); end
  S = fscanf(fid,'%c');
  fclose(fid);
  delete(diaryfile);

  % add the screen output to the provenance structure
  % prov.script{i}.stdout = sprintf('\n%s\n', S);

end % for each of the input arguments

% display the provenance structure on screen as an XML stream
% disp(fileexchange_struct2xml(struct('megconnectome', prov)));

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function assign(key, val)
assignin('caller', key, val);


cur_dir = pwd;
cd(fileparts(mfilename('fullpath')));

fprintf('Downloading SPP_net_release1_VOC2007_selective_search_data...\n');
urlwrite('https://onedrive.live.com/download?resid=D7AF52BADBA8A4BC!112&authkey=!ALMzBRGL1B9Eqz8&ithint=file%2czip', ...
    'SPP_net_release1_VOC2007_selective_search_data.zip');

fprintf('Unzipping...\n');
unzip('SPP_net_release1_VOC2007_selective_search_data.zip', '.');

fprintf('Done.\n');
system('del SPP_net_release1_VOC2007_selective_search_data.zip');

cd(cur_dir);


function F = set(varargin)
%SET OBSOLETE

disp('SET has been considered obsolete for many years, and the time has come...');
disp('Update your code. https://yalmip.github.io/tutorial/basics/');
error('Obsolete command')


function [err,data] = afni_ni_checkfordata()
   global comm;

   data = [];
   err = 1;
   if (comm.sockcon < 0),
      comm.sockcon = pnet('tcpsocket',sprintf('%d', comm.socknum));
      if (comm.sockcon < 0),
         fprintf(2,'Could not open socket %d\n', comm.socknum);
         return;
      end
      if (comm.dbg ),
         fprintf(1,  'have new socket connection %d\n', comm.sockcon);
      end
   else
      if (comm.dbg > 1) fprintf(1,'have socket %d\n', comm.sockcon); end
   end
   %have socket, try connection
   if (comm.con < 0),
      comm.con = pnet(comm.sockcon,'tcplisten','noblock');  % Don't wait forever
      err = 0;
      if (comm.dbg > 1) fprintf(1,'No connection yet \n'); end
      return;  %nothing yet
   else
      if (comm.dbg > 1) fprintf(1,'have connection handle %d\n', comm.con); end
   end
   status = pnet(comm.con,'status');
   if (status == 0),
      % bad status, perhaps disconnected or first time, reopen socket
      fprintf(2,'Stream closed, attempt to reopen on second pass.\n');
      comm.con = -1;
      err = 0;
      return;
   else
      if (comm.dbg > 1) fprintf(2,'status %d\n', status); end
   end

   %have connection, get data
   pnet(comm.con,'setreadtimeout',0.25);
      % Don't wait forever, I had 3 seconds but that was too slow
      % 0.25 worked just fine on localhost 127.0.0.1

   %check for stuff
   b = pnet(comm.con,'read');
   while (length(b)) data=[data b]; b = pnet(comm.con,'read');  end

   err = 0;
   return


classdef log

methods(Static)

function display(message)
    % compute current time string
    curtime = datestr(now, 'HH:MM:SS');
    disp([curtime, ' ', message]);
end

end

end


function rootPath=mrvTestRootPath()
%Determine path to root of the mrVista unit testing directory.
%
%        rootPath = mrvTestRootPath;
%
% This file and similarly named ones are used to identify the root
% directory of important repositories or files.
%
% This one is used as part of the testing of vistasoft
%
% This function MUST reside in the directory at the base of the vistatest
% directory structure.
%
% mrVista Team

rootPath = which('mrvTestRootPath');

rootPath = fileparts(rootPath);

return


function c=context_menus(obj, tag, createmode, varargin)
    % manages context menus, which avoids repeatedly creating context menus
    % c=context_menus(obj, tag, createmode, varargin)
    % Contexts are attached to the figure, so deleting
    % objects that they are attached to will not delete the context menus.
    %
    % context menus can be reused.
    existing_contexts = findobj(obj.fig,'Type','uicontextmenu');
    c = findobj(existing_contexts, 'Tag',tag);

    switch createmode
        case 'overwrite'
            % delete existing context first, then recreate it and return handle
        case 'reuse'
            % if a context exists, just return a handle to it
    end
    switch tag

    end
end


classdef VideoCapture < handle
    %VIDEOCAPTURE  Class for video capturing from video files or cameras
    %
    % The class provides an API for capturing video from cameras or for
    % reading video files and image sequences.
    %
    % ## Example
    % Here is how the class can be used:
    %
    %     cap = cv.VideoCapture(0);        % open the default camera
    %     pause(3);                        % see note below
    %     if ~cap.isOpened()               % check if we succeeded
    %         error('camera failed to initialized');
    %     end
    %     for t=1:30
    %         frame = cap.read();           % get a new frame from camera
    %         imshow(frame);
    %         pause(0.1);
    %     end
    %     % the camera will be deinitialized automatically in destructor
    %     % when "cap" goes out of scope
    %     % you can also explicitly call cap.release() to close the camera
    %
    % Note: In some environments, there is a concurrency issue during camera
    % initialization. To avoid unexpected crash, pause for a few seconds after
    % the initialization of cv.VideoCapture object.
    %
    % # Video I/O with OpenCV Overview
    %
    % The OpenCV "videoio" module is a set of classes and functions to read
    % and write video or images sequence.
    %
    % Basically, the module provides the cv.VideoCapture and cv.VideoWriter
    % classes as 2-layer interface to many video I/O APIs used as backend.
    %
    % ![image](https://docs.opencv.org/3.3.1/videoio_overview.svg)
    %
    % Some backends such as (`DirectShow`) Direct Show, Video For Windows
    % (`VfW`), Microsoft Media Foundation (`MediaFoundation`), Video 4 Linux
    % (`V4L`), etc... are interfaces to the video I/O library provided by the
    % operating system.
    %
    % Some others backends like OpenNI2 for Kinect, Intel Perceptual Computing
    % SDK, GStreamer, XIMEA Camera API, etc... are interfaces to proprietary
    % drivers or to external library.
    %
    % See the list of supported backends here: cv.VideoCapture.open
    %
    % Warning: Some backends are experimental use them at your own risk.
    % Note: Each backend supports devices properties (cv.VideoCapture.set) in
    % a different way or might not support any property at all.
    %
    % ## Select the backend at runtime
    % OpenCV automatically selects and uses first available backend
    % (`API='Any'`).
    %
    % As advanced usage you can select the backend to use at runtime.
    % Currently this option is available only with cv.VideoCapture.
    %
    % For example to grab from default camera using Direct Show as backend
    %
    %     % declare a capture object
    %     cap = cv.VideoCapture(0, 'API','DirectShow')
    %
    %     % or specify the API preference with open
    %     cap.open(0, 'API','DirectShow');
    %
    % If you want to grab from a file using the Direct Show as backend:
    %
    %     % declare a capture object
    %     cap = cv.VideoCapture(filename, 'API','DirectShow')
    %
    %     % or specify the API preference with open
    %     cap.open(filename, 'API','DirectShow');
    %
    % ### Enable backends
    % Backends are available only if they have been built with your OpenCV
    % binaries.
    %
    % Check in `opencv2/cvconfig.h` to know which APIs are currently available
    % (e.g. `HAVE_MSMF, HAVE_VFW, HAVE_LIBV4L`, etc...).
    %
    % To enable/disable APIs, you have to:
    % 1. re-configure OpenCV using appropriates CMake switches
    %    (e.g. `-DWITH_MSMF=ON -DWITH_VFW=ON ... `) or checking related switch
    %    in cmake-gui
    % 2. rebuild OpenCV itself
    %
    % ### Use 3rd party drivers or cameras
    % Many industrial cameras or some video I/O devices don't provide standard
    % driver interfaces for the operating system. Thus you can't use
    % cv.VideoCapture or cv.VideoWriter with these devices.
    %
    % ## The FFmpeg library
    % OpenCV can use the [FFmpeg](http://ffmpeg.org/) library as backend to
    % record, convert and stream audio and video. FFMpeg is a complete,
    % cross-reference solution. If you enable FFmpeg while configuring OpenCV
    % than CMake will download and install the binaries in
    % `OPENCV_SOURCE_CODE/3rdparty/ffmpeg/`. To use FFMpeg at runtime, you
    % must deploy the FFMepg binaries with your application.
    %
    % Note: FFmpeg is licensed under the GNU Lesser General Public License
    % (LGPL) version 2.1 or later. See
    % `OPENCV_SOURCE_CODE/3rdparty/ffmpeg/readme.txt` and
    % http://ffmpeg.org/legal.html for details and licensing information.
    %
    % See also: cv.VideoCapture.VideoCapture, cv.VideoCapture.read,
    %  cv.VideoWriter, VideoReader, mmreader, aviread, webcam, videoinput,
    %  imaq.VideoDevice, vision.VideoFileReader
    %

    properties (SetAccess = private)
        % Object ID
        id
    end

    properties (Dependent)
        % Current position of the video file in milliseconds or video capture
        % timestamp.
        PosMsec
        % 0-based index of the frame to be decoded/captured next.
        PosFrames
        % Relative position of the video file:
        % 0 - start of the film, 1 - end of the film.
        PosAviRatio
        % Width of the frames in the video stream.
        FrameWidth
        % Height of the frames in the video stream.
        FrameHeight
        % Frame rate.
        FPS
        % 4-character code of codec. See cv.VideoWriter.open.
        FourCC
        % Number of frames in the video file.
        FrameCount
        % Format of the frames returned by cv.VideoCapture.retrieve.
        Format
        % Backend-specific value indicating the current capture mode.
        Mode
        % Brightness of the image (only for those cameras that support it).
        Brightness
        % Contrast of the image (only for cameras).
        Contrast
        % Saturation of the image (only for cameras).
        Saturation
        % Hue of the image (only for cameras).
        Hue
        % Gain of the image (only for those cameras that support it).
        Gain
        % Exposure (only for those cameras that support it).
        Exposure
        % Boolean flags indicating whether images should be converted to RGB.
        ConvertRGB
        % Rectification flag for stereo cameras
        % (note: only supported by DC1394 v2.x backend currently)
        Rectification
    end

    methods
        function this = VideoCapture(varargin)
            %VIDEOCAPTURE  Open video file or a capturing device or a IP video stream for video capturing
            %
            %     cap = cv.VideoCapture()
            %     cap = cv.VideoCapture(index)
            %     cap = cv.VideoCapture(filename)
            %     cap = cv.VideoCapture(..., 'API',apiPreference)
            %
            % ## Output
            % * __cap__ New instance of the VideoCapture
            %
            % Accepts the same inputs and options as the cv.VideoCapture.open
            % method.
            %
            % Creates a new video capture instance. With no argument, it
            % connects to the default camera device found in the system.
            % You can specify camera devices by `index`, an integer value
            % starting from 0. You can also specify a `filename` to open a
            % video file.
            %
            % See also: cv.VideoCapture.open
            %
            this.id = VideoCapture_(0, 'new');
            if nargin > 0
                this.open(varargin{:});
            else
                this.open(0);
            end
        end

        function delete(this)
            %DELETE  Destructor
            %
            %     cap.delete()
            %
            % The method first calls cv.VideoCapture.release to close the
            % already opened file or camera.
            %
            % See also: cv.VideoCapture.release
            %
            if isempty(this.id), return; end
            VideoCapture_(this.id, 'delete');
        end

        function successFlag = open(this, index, varargin)
            %OPEN  Open video file or a capturing device or a IP video stream for video capturing
            %
            %     successFlag = cap.open(index)
            %     successFlag = cap.open(filename)
            %     successFlag = cap.open(..., 'API',apiPreference)
            %
            % ## Input
            % * __index__ id of the video capturing device to open. To open
            %   default camera using default backend just pass 0.
            % * __filename__ it can be:
            %   * name of video file (eg. `video.avi`)
            %   * or image sequence (eg. `img_%02d.jpg`, which will read
            %     samples like `img_00.jpg`, img_01.jpg`, img_02.jpg`, ...)
            %   * or URL of video stream
            %     (eg. `protocol://host:port/script_name?script_params|auth`).
            %     Note that each video stream or IP camera feed has its own
            %     URL scheme. Please refer to the documentation of source
            %     stream to know the right URL.
            %   * or device name (for backends like V4L or gPhoto2)
            %
            % ## Output
            % * __successFlag__ bool, true if the file/camera has been
            %   successfully opened.
            %
            % ## Options
            % * __API__ preferred capture API backend to use. Can be used to
            %   enforce a specific reader implementation if multiple are
            %   available: e.g. 'FFMPEG' or 'Images' or 'DirectShow'. The list
            %   of supported API backends:
            %   * __Any__ Auto detect. This is the default.
            %   * __VfW__ Video For Windows (platform native).
            %   * __V4L__ V4L/V4L2 capturing support via libv4l.
            %   * __V4L2__ Same as V4L.
            %   * __FireWire__ IEEE 1394 drivers.
            %   * __FireWare__ Same as FireWire.
            %   * __IEEE1394__ Same as FireWire.
            %   * __DC1394__ Same as FireWire.
            %   * __CMU1394__ Same as FireWire.
            %   * __QuickTime__ QuickTime.
            %   * __Unicap__ Unicap drivers.
            %   * __DirectShow__ DirectShow (via videoInput).
            %   * __PvAPI__ PvAPI, Prosilica GigE SDK.
            %   * __OpenNI__ OpenNI (for Kinect).
            %   * __OpenNIAsus__ OpenNI (for Asus Xtion).
            %   * __Android__ Android - not used.
            %   * __XIMEA__ XIMEA Camera API.
            %   * __AVFoundation__ AVFoundation framework for iOS
            %     (OS X Lion will have the same API).
            %   * __Giganetix__ Smartek Giganetix GigEVisionSDK.
            %   * __MediaFoundation__ Microsoft Media Foundation
            %     (via videoInput).
            %   * __WinRT__ Microsoft Windows Runtime using Media
            %     Foundation.
            %   * __IntelPerC__ Intel Perceptual Computing SDK.
            %   * __OpenNI2__ OpenNI2 (for Kinect).
            %   * __OpenNI2Asus__ OpenNI2 (for Asus Xtion and Occipital
            %     Structure sensors).
            %   * __gPhoto2__ gPhoto2 connection.
            %   * __GStreamer__ GStreamer.
            %   * __FFMPEG__ Open video file or stream using the FFMPEG
            %     library.
            %   * __Images__ OpenCV Image Sequence (e.g. `img_%02d.jpg`).
            %   * __Aravis__ Aravis GigE SDK.
            %   * __MotionJPEG__ Built-in OpenCV MotionJPEG codec.
            %   * __MediaSDK__ Intel MediaSDK.
            %
            % The method first calls cv.VideoCapture.release to close the
            % already opened file or camera.
            %
            % ## Example
            % Use `API` option to enforce a specific reader implementation
            % if multiple are available like 'FFMPEG' or 'Images' or
            % 'DirectShow'. For example, to open camera 1 using the
            % "MS Media Foundation" API:
            %
            %     cap.open(1, 'API','MediaFoundation')
            %
            % ### Note
            % Backends are available only if they have been built with your
            % OpenCV binaries.
            % Check your build to know which APIs are currently available.
            % To enable/disable APIs, you have to re-configure OpenCV using
            % the appropriates CMake switches and recompile OpenCV itself.
            %
            % See also: cv.VideoCapture.VideoCapture, cv.VideoCapture.isOpened
            %
            if nargin < 1, index = 0; end
            successFlag = VideoCapture_(this.id, 'open', index, varargin{:});
        end

        function retval = isOpened(this)
            %ISOPENED  Returns true if video capturing has been initialized already
            %
            %     retval = cap.isOpened()
            %
            % ## Output
            % * __retval__ bool, return value
            %
            % If the previous call to constructor or cv.VideoCapture.open
            % succeeded, the method returns true.
            %
            % See also: cv.VideoCapture.open
            %
            retval = VideoCapture_(this.id, 'isOpened');
        end

        function release(this)
            %RELEASE  Closes video file or capturing device
            %
            %     cap.release()
            %
            % The method is automatically called by subsequent
            % cv.VideoCapture.open and by destructor.
            %
            % See also: cv.VideoCapture.open
            %
            VideoCapture_(this.id, 'release');
        end

        function frame = read(this, varargin)
            %READ  Grabs, decodes and returns the next video frame
            %
            %     frame = cap.read()
            %     frame = cap.read('OptionName',optionValue, ...)
            %
            % ## Output
            % * __frame__ output image
            %
            % ## Options
            % * __FlipChannels__ in case the output is color image, flips the
            %   color order from OpenCV's BGR to MATLAB's RGB order.
            %   default true
            %
            % The method combines cv.VideoCapture.grab and
            % cv.VideoCapture.retrieve in one call. This is the most
            % convenient method for reading video files or capturing data from
            % decode and return the just grabbed frame. If no frames has been
            % grabbed (camera has been disconnected, or there are no more
            % frames in video file), the function return an empty matrix.
            %
            % See also: cv.VideoCapture.grab, cv.VideoCapture.retrieve
            %
            frame = VideoCapture_(this.id, 'read', varargin{:});
        end

        function successFlag = grab(this)
            %GRAB  Grabs the next frame from video file or capturing device
            %
            %     successFlag = cap.grab()
            %
            % ## Output
            % * __successFlag__ bool, true (non-zero) in the case of success.
            %
            % The function grabs the next frame from video file or camera and
            % returns true (non-zero) in the case of success.
            %
            % The primary use of the function is in multi-camera environments,
            % especially when the cameras do not have hardware synchronization.
            % That is, you call cv.VideoCapture.grab for each camera and after
            % that call the slower method cv.VideoCapture.retrieve to decode
            % and get frame from each camera. This way the overhead on
            % demosaicing or motion jpeg decompression etc. is eliminated and
            % the retrieved frames from different cameras will be closer in
            % time.
            %
            % Also, when a connected camera is multi-head (for example, a
            % stereo camera or a Kinect device), the correct way of retrieving
            % data from it is to call cv.VideoCapture.grab first and then call
            % cv.VideoCapture.retrieve one or more times with different values
            % of the channel parameter `StreamIdx`.
            %
            % See also: cv.VideoCapture.read, cv.VideoCapture.retrieve
            %
            successFlag = VideoCapture_(this.id, 'grab');
        end

        function frame = retrieve(this, varargin)
            %RETRIEVE  Decodes and returns the grabbed video frame
            %
            %     frame = cap.retrieve()
            %     frame = cap.retrieve('OptionName',optionValue, ...)
            %
            % ## Output
            % * __frame__ the video frame is returned here. If no frames has
            %   been grabbed the image will be empty.
            %
            % ## Options
            % * __StreamIdx__ 0-based index (for multi-head camera). It could
            %   be a frame index or a driver specific flag. default 0
            % * __FlipChannels__ in case the output is color image, flips the
            %   color order from OpenCV's BGR to MATLAB's RGB order.
            %   default true
            %
            % The function decodes and returns the just grabbed frame. If no
            % frames has been grabbed (camera has been disconnected, or there
            % are no more frames in video file), the function returns an empty
            % matrix.
            %
            % See also: cv.VideoCapture.read, cv.VideoCapture.grab
            %
            frame = VideoCapture_(this.id, 'retrieve', varargin{:});
        end

        function value = get(this, prop)
            %GET  Returns the specified VideoCapture property
            %
            %     value = cap.get(prop)
            %
            % ## Input
            % * __prop__ Property identifier. It can be specified as a string
            %   (one of the recognized properties), or directly as its
            %   corresponding integer code.
            %
            % ## Output
            % * __value__ Value for the specified property (as a `double`).
            %   Value 0 is returned when querying a property that is not
            %   supported by the backend used by the VideoCapture instance.
            %
            % ### Note
            % Reading/writing properties involves many layers. Some unexpected
            % result might happens along this chain.
            % `VideoCapture -> API Backend -> Operating System -> Device Driver -> Device Hardware`
            % The returned value might be different from what really used by
            % the device or it could be encoded using device dependent rules
            % (eg. steps or percentage). Effective behaviour depends from
            % device driver and API Backend.
            %
            % ## Example
            % All the following are equivalent:
            %
            %     b = cap.Brightness
            %     b = cap.get('Brightness')
            %     b = cap.get(10)  % enum value defined in OpenCV source code
            %
            % See also: cv.VideoCapture.set
            %
            value = VideoCapture_(this.id, 'get', prop);
        end

        function set(this, prop, value)
            %SET  Sets a property in the VideoCapture
            %
            %     cap.set(prop, value)
            %
            % ## Input
            % * __prop__ Property identifier. It can be specified as a string
            %   (one of the recognized properties), or directly as its
            %   corresponding integer code.
            % * __value__ Value of the property (as a `double`).
            %
            % On failure (unsupported property by backend), the function
            % issues a warning.
            %
            % Note: Even if no warning was issued, this doesn't ensure that
            % the property value has been accepted by the capture device.
            % See note in cv.VideoCapture.get.
            %
            % See also: cv.VideoCapture.get
            %
            VideoCapture_(this.id, 'set', prop, value);
        end
    end

    %% Getters/Setters
    methods
        function value = get.PosMsec(this)
            value = VideoCapture_(this.id, 'get', 'PosMsec');
        end
        function set.PosMsec(this, value)
            VideoCapture_(this.id, 'set', 'PosMsec', value);
        end

        function value = get.PosFrames(this)
            value = VideoCapture_(this.id, 'get', 'PosFrames');
        end
        function set.PosFrames(this, value)
            VideoCapture_(this.id, 'set', 'PosFrames', value);
        end

        function value = get.PosAviRatio(this)
            value = VideoCapture_(this.id, 'get', 'PosAviRatio');
        end
        function set.PosAviRatio(this, value)
            VideoCapture_(this.id, 'set', 'PosAviRatio', value);
        end

        function value = get.FrameWidth(this)
            value = VideoCapture_(this.id, 'get', 'FrameWidth');
        end
        function set.FrameWidth(this, value)
            VideoCapture_(this.id, 'set', 'FrameWidth', value);
        end

        function value = get.FrameHeight(this)
            value = VideoCapture_(this.id, 'get', 'FrameHeight');
        end
        function set.FrameHeight(this, value)
            VideoCapture_(this.id, 'set', 'FrameHeight', value);
        end

        function value = get.FPS(this)
            value = VideoCapture_(this.id, 'get', 'FPS');
        end
        function set.FPS(this, value)
            VideoCapture_(this.id, 'set', 'FPS', value);
        end

        function value = get.FourCC(this)
            value = int32(VideoCapture_(this.id, 'get', 'FourCC'));
            %value = char(typecast(value, 'uint8'));  %TODO
        end
        function set.FourCC(this, value)
            VideoCapture_(this.id, 'set', 'FourCC', value);
        end

        function value = get.FrameCount(this)
            value = VideoCapture_(this.id, 'get', 'FrameCount');
        end
        function set.FrameCount(this, value)
            VideoCapture_(this.id, 'set', 'FrameCount', value);
        end

        function value = get.Format(this)
            value = VideoCapture_(this.id, 'get', 'Format');
        end
        function set.Format(this, value)
            VideoCapture_(this.id, 'set', 'Format', value);
        end

        function value = get.Mode(this)
            value = VideoCapture_(this.id, 'get', 'Mode');
        end
        function set.Mode(this, value)
            VideoCapture_(this.id, 'set', 'Mode', value);
        end

        function value = get.Brightness(this)
            value = VideoCapture_(this.id, 'get', 'Brightness');
        end
        function set.Brightness(this, value)
            VideoCapture_(this.id, 'set', 'Brightness', value);
        end

        function value = get.Contrast(this)
            value = VideoCapture_(this.id, 'get', 'Contrast');
        end
        function set.Contrast(this, value)
            VideoCapture_(this.id, 'set', 'Contrast', value);
        end

        function value = get.Saturation(this)
            value = VideoCapture_(this.id, 'get', 'Saturation');
        end
        function set.Saturation(this, value)
            VideoCapture_(this.id, 'set', 'Saturation', value);
        end

        function value = get.Hue(this)
            value = VideoCapture_(this.id, 'get', 'Hue');
        end
        function set.Hue(this, value)
            VideoCapture_(this.id, 'set', 'Hue', value);
        end

        function value = get.Gain(this)
            value = VideoCapture_(this.id, 'get', 'Gain');
        end
        function set.Gain(this, value)
            VideoCapture_(this.id, 'set', 'Gain', value);
        end

        function value = get.Exposure(this)
            value = VideoCapture_(this.id, 'get', 'Exposure');
        end
        function set.Exposure(this, value)
            VideoCapture_(this.id, 'set', 'Exposure', value);
        end

        function value = get.ConvertRGB(this)
            value = VideoCapture_(this.id, 'get', 'ConvertRGB');
        end
        function set.ConvertRGB(this, value)
            VideoCapture_(this.id, 'set', 'ConvertRGB', value);
        end

        function value = get.Rectification(this)
            value = VideoCapture_(this.id, 'get', 'Rectification');
        end
        function set.Rectification(this, value)
            VideoCapture_(this.id, 'set', 'Rectification', value);
        end
    end

end


%GE Datafile overload


classdef MimExportEditedImage < MimGuiPlugin
    % MimExportEditedImage. Gui Plugin
    %
    %     You should not use this class within your own code. It is intended to
    %     be used by the gui of the TD MIM Toolkit.
    %
    %     MimExportEditedImage is a Gui Plugin for the MIM Toolkit.
    %
    %
    %     Licence
    %     -------
    %     Part of the TD MIM Toolkit. https://github.com/tomdoel
    %     Author: Tom Doel, Copyright Tom Doel 2014.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
        ButtonText = 'Export Edits'
        SelectedText = 'Export Edits'
        ToolTip = 'Exports the current edits to an external file'
        Category = 'Save / load edits'
        Visibility = 'Overlay'
        Mode = 'Edit'

        Icon = 'export_overlay.png'
        Location = 28

        HidePluginInDisplay = false
        PTKVersion = '1'
        ButtonWidth = 6
        ButtonHeight = 2
    end

    methods (Static)
        function RunGuiPlugin(gui_app)
            gui_app.GetMode.ExportEdit();
        end

        function enabled = IsEnabled(gui_app)
            enabled = gui_app.IsDatasetLoaded && gui_app.ImagePanel.OverlayImage.ImageExists && ...
                isequal(gui_app.GetCurrentModeName, MimModes.EditMode) && gui_app.IsTabEnabled('Edit');
        end
    end
end


function obj=MOxUnitTestNode(name)
% Initialize MOxUnitTestNode instance
%
% obj=MOxUnitTestNode()
%
% Input:
%   name            name of this TestNode
%
% Output:
%   obj             MOxUnitTestNode instance
%
% Notes:
%   - This class is intended as an 'abstract' superclass, and should not
%     be initialized in typical use cases. Instead, use its subclasses,
%     MoxUnitTestSuite and MoxUnitTestCase.
%
% NNO 2015

    s=struct();
    s.name=name;
    obj=class(s,'MOxUnitTestNode');


%--- help for create_variable_names ---
%
%  INTERNAL FUNCTION
%
%


function stat = memprofile(varargin)

% MEMPROFILE this is a dummy placeholder

if nargout
  stat.mem = [0 0 0 0];
end


function pptClose(op,ppt,pptFile);
% For Windows machines only: Close an ActiveX Server for
% a particular power point file, saving along the way.
%
% Usage:
%   pptClose(op,ppt,pptFile);
%
% ras, 10/2005.
[p f ext] = fileparts(pptFile);
if ~isempty(p),
	callingDir = pwd;
	cd(p);
end

if ~exist(pptFile,'file')
  % Save file as new:
  invoke(op,'SaveAs',pptFile,1);
else
  % Save existing file:
  invoke(op,'Save');
end

% Close the presentation window:
invoke(op,'Close');

% % Quit PowerPoint
% invoke(ppt,'Quit');

% % Close PowerPoint and terminate ActiveX:
% delete(ppt);

if exist('callingDir', 'var')
	cd(callingDir);
end

return


%   AUTHORSHIP
%   Primary Developer: Stephen Meehan <swmeehan@stanford.edu>
%   Math Lead & Secondary Developer:  Connor Meehan <connor.gw.meehan@gmail.com>
%   Bioinformatics Lead:  Wayne Moore <wmoore@stanford.edu>
%   Provided by the Herzenberg Lab at Stanford University
%   License: BSD 3 clause
%

function [answer, cancelled]=inputDlg(msg,title,varargin)
if nargin==1
    title='Input required';
end
[msgType, jsa,default,~,isNumerics]=getMsgTypeAndOptions(...
    javax.swing.JOptionPane.QUESTION_MESSAGE, varargin);
[msg, where, property, properties, default, myIcon, javaWin,~,~,modal]...
    =decodeMsg(msg, default);

if ~isempty(jsa)
    inputValue=char(jsa(1));
else
    inputValue='';
end
if msgType==0
    myIcon='error.png';
elseif msgType==1
    myIcon = 'facs.gif';
elseif msgType==2
    myIcon='warning.png';
else
    myIcon='question.png';
end
pane=javaObjectEDT('javax.swing.JOptionPane', msg, msgType);
pane.setWantsInput(true);
pane.setInitialSelectionValue(inputValue);
pane.selectInitialValue();
pane.setIcon(Gui.Icon(myIcon));
pane.setOptionType(javax.swing.JOptionPane.OK_CANCEL_OPTION);
PopUp.Pane(pane, title,where, javaWin, modal);
answer=pane.getInputValue;
cancelled=strcmp(answer,'uninitializedValue');
if cancelled
    answer='';
end
end


classdef Step1 < adi.StepBase

    %   Copyright 2017 The MathWorks, Inc.
    properties (Hidden)
       InstallButton
    end

    methods
        function obj = Step1(varargin)
            obj@adi.StepBase(varargin{:});

            %       obj.Workflow.InstallDriverWorkflow = true;

            parentContainer = obj.ContentPanel;

            obj.Title.Text = 'ADI Board Support Package Installer';

            obj.InfoText1.Position = [20 340 400 30];
            obj.InfoText1.Text = 'Step 1: Installing drivers';

            obj.InfoText2.Position = [20 290 400 50];
            obj.InfoText2.Text = 'Test2';

            obj.InstallButton = matlab.hwmgr.internal.hwsetup.Button.getInstance(parentContainer);
            obj.InstallButton.ButtonPushedFcn = @obj.LinuxInstall;
            obj.InstallButton.Text = 'WINNER';

            obj.HelpText.AboutSelection = 'About Selection';
            obj.HelpText.WhatToConsider = 'Test3';
        end

        function out = getNextScreenID(obj)
            % HSA infrastructure requires a "getNextScreenID" method implemented
            % in the leaf class. Otherwise, it renders "Finish" button instead of
            % "Next".
            out = getNextScreenIDImpl(obj);
        end

        function restoreScreen(obj)
            obj.enableScreen();
        end
    end

    methods (Access = protected)

        function out = getNextScreenIDImpl(~)
            out = 'adi.Step2';
        end

        function LinuxInstall(~,~,~)
            system('sudo whoami');
        end

    end

end


function printFuncName = getStandardOutputFuncName()
global logger

if isempty(logger)
    printFuncName = 'fprintf';
elseif isa(logger, 'Logger')
    if ~logger.IsOpen()
        logger.Open();
    end
    if ~logger.IsOpen()
        printFuncName = 'fprintf';
    else
        printFuncName = 'logger.Write';
    end
else
    printFuncName = 'logger.Write';
end


function varargout = ft_info(varargin)

% FT_INFO prints an info message on screen, depending on the verbosity
% settings of the calling high-level FieldTrip function.
%
% Use as
%   ft_info(...)
% with arguments similar to fprintf, or
%   ft_info(msgId, ...)
% with arguments similar to warning.
%
% You can switch of all messages using
%   ft_info off
% or for specific ones using
%   ft_info off msgId
%
% To switch them back on, you would use
%   ft_info on
% or for specific ones using
%   ft_info on msgId
%
% Messages are only printed once per timeout period using
%   ft_info timeout 60
%   ft_info once
% or for specific ones using
%   ft_info once msgId
%
% You can see the most recent messages and identifier using
%   ft_info last
%
% You can query the current on/off/once state for all messages using
%   ft_info query
%
% See also FT_ERROR, FT_WARNING, FT_NOTICE, FT_INFO, FT_DEBUG, ERROR, WARNING

% Copyright (C) 2017, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.fieldtriptoolbox.org
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id$

if nargout
  varargout{:} = ft_notification(varargin{:});
elseif isequal(varargin, {'last'})
  % return an answer anyway
  varargout{1} = ft_notification(varargin{:});
else
  ft_notification(varargin{:});
end


function strip_svn_dirs()
% Removes the .svn dirs from the path
    strip_path_dirs('\.svn');
end


function this = rmfield(this, vals);

    eval( [ 'this.EEG.' vals '=[];' ] );


function funUpload1(object_handle, event)

    global mode;
    global figure1;

    mode = 'Upload1';
    figure1 = true;

    set(object_handle, 'BackGroundColor', [0.4,0.4,0.4], 'Enable', 'off');

end


function disp(obj)

% function disp(obj)
% Disp a configuration dependency
%
% This code is part of a batch job configuration system for MATLAB. See
%      help matlabbatch
% for a general overview.
%_______________________________________________________________________
% Copyright (C) 2007 Freiburg Brain Imaging

% Volkmar Glauche
% $Id: disp.m 1716 2008-05-23 08:18:45Z volkmar $

rev = '$Rev: 1716 $'; %#ok

sz = size(obj);
fprintf('%s object: ', class(obj));
if length(sz)>4,
    fprintf('%d-D\n',length(sz));
else
    for i=1:(length(sz)-1),
        fprintf('%d-by-',sz(i));
    end;
    fprintf('%d\n',sz(end));
end;
if prod(sz)==1,
    so = struct(obj);
    disp(so);
end;
return;


function size = pivparpool(cmd,core)
% parpool size: pivparpool('size')
% parpool close: pivparpool('close')
% parpool open: pivparpool('open', 2)

if nargin < 1
	error('Requires at least one input argument')
end
if nargin == 1
    if verLessThan('matlab', '8.2')
        if strcmp(cmd,'size')
            size = matlabpool('size');
        elseif strcmp(cmd,'close')
            matlabpool close;
        else
            error('Wrong input arguments.')
        end
    else
        poolobj = gcp('nocreate');
        if strcmp(cmd,'size')
            if isempty(poolobj)
                size = 0;
            else
                size = poolobj.NumWorkers;
            end
        elseif strcmp(cmd,'close')
            delete(poolobj);
        else
            error('Wrong input arguments.')
        end
    end
elseif nargin == 2
    if verLessThan('matlab', '8.2')
        if strcmp(cmd,'open')
            matlabpool('open','local',core);
        else
            error('Wrong input arguments.')
        end
    else
        if strcmp(cmd,'open')
            parpool('local',core);
        else
            error('Wrong input arguments.')
        end
    end
elseif nargin > 2
	error('Too many input arguments.')
end


%--- help for generic/load_parameters ---
%
%  INTERNAL FUNCTION
%
%


function res = get_release_mode()

global POSE_RELEASE_MODE;

if isempty(POSE_RELEASE_MODE)
    POSE_RELEASE_MODE = false;
end

res = POSE_RELEASE_MODE;

end


%% Crystal Directions
%
%%
%


function obj=reportTestOutcome(obj, test_outcome)
% reports the test outcome to the stream of the current object
%
% obj=reportTestOutcome(obj, test_outcome)
%
% Inputs:
%   obj             MOxUnitTestReport instance
%   test_outcome    MOxUnitTestReport instance with the outcome to report.
%                   This function will print the outcome to the stream used
%                   when obj was instantiated. As a side effect,
%                   test_outcome is added to the report
%
% Output:
%   obj             MOxUnitTestReport instance with the test_outcome added

    obj=addTestOutcome(obj,test_outcome);

    verbosity=obj.verbosity;

    outcome_str=getProgressStr(test_outcome, verbosity);
    stream=obj.stream;

    postfix=''; % the default

    max_line_length=60;
    if mod(countTestOutcomes(obj),max_line_length)==0 && verbosity==1
        % when showing single characters, print a newline every sixty
        % characters
        postfix=sprintf('\n');
    end

    fprintf(stream,'%s%s',outcome_str,postfix);


classdef CoreTestException < MException
    % CoreTestException. Part of the MTest unit test framework
    %
    % This class is used by the CoreMockReporting class when generating exceptions
    % during testing. This allows tests to verify that an exception has occurred
    % as expected, and allows easy distinguishing of exceptions generated by the
    % framework compared to other errors.
    %
    %     Licence
    %     -------
    %     Part of CoreMat. https://github.com/tomdoel/coremat
    %     Author: Tom Doel, 2013.  www.tomdoel.com
    %     Distributed under the MIT licence. Please see website for details.
    %

    properties
    end

    methods
        function obj = CoreTestException
            obj = obj@MException('CoreTestException:FakeException', 'Fake exception');
        end
    end

end