Example usage for java.lang Integer toString

List of usage examples for java.lang Integer toString

Introduction

In this page you can find the example usage for java.lang Integer toString.

Prototype

@HotSpotIntrinsicCandidate
public static String toString(int i) 

Source Link

Document

Returns a String object representing the specified integer.

Usage

From source file:niclients.main.regni.java

public static void main(String[] args) throws UnsupportedEncodingException {
    HttpClient client = new DefaultHttpClient();

    if (commandparser(args)) {
        if (createpub()) {
            try {
                HttpResponse response = client.execute(post);
                int resp_code = response.getStatusLine().getStatusCode();
                System.err.println("RESP_CODE: " + Integer.toString(resp_code));
                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                String line = "";
                while ((line = rd.readLine()) != null) {
                    System.out.println(line);
                }/*from  ww  w.j ava  2s. c o m*/

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.err.println("Publish creation failed!");
        }

    } else {
        System.err.println("Command line parsing failed!");
    }
}

From source file:com.mycompany.asyncreq.Main.java

public static void main(String[] args) throws JsonProcessingException, JSONException, IOException {

    Configuration config = new Configuration();
    // Name tables with lowercase_underscore_separated
    RestTemplate restTemplate = new RestTemplate();
    config.setNamingStrategy(new ImprovedNamingStrategy());
    try {/*  w w  w.  j av  a 2 s.  c om*/

        ArrayList<String> ArrReq = GenData();
        String addr;
        for (Iterator<String> i = ArrReq.iterator(); i.hasNext();) {
            try {
                addr = i.next();
                Thread.sleep(1000);
                Root tRoot = restTemplate.getForObject(addr, Root.class);
                tRoot.addr = addr;
                if (!tRoot.dataset.isEmpty())
                    if (tRoot.dataset.size() == tRoot.validation.count.value)
                        ObjToCsv(tRoot, "all");

                    else {
                        for (int reg = 1; reg < 5; reg++) {
                            Thread.sleep(1000);
                            addr = "http://comtrade.un.org/api/get?max=50000&type=C&freq=M&px=HS&ps=2014&r=804&p="
                                    + tRoot.dataset.get(0).getptCode() + "&rg=" + reg + "&cc=All&fmt=json";
                            Root tRootImp = restTemplate.getForObject(addr, Root.class);
                            tRootImp.addr = addr;
                            if (!tRootImp.dataset.isEmpty())
                                if (tRootImp.dataset.size() == tRootImp.validation.count.value)
                                    ObjToCsv(tRootImp, Integer.toString(reg));
                                else
                                    System.out.println("addr:  " + tRootImp.addr + "\n");
                        }
                    }
                else
                    System.out.println("addr:  " + tRoot.addr + ":null" + "\n");
            } catch (Exception e) {
                System.err.println(e.getMessage());

            }
        }

    } catch (Exception e) {
        System.err.println("Got an exception! ");
        System.err.println(e.getMessage());
    }
}

From source file:com.ict.dtube.tools.command.MQAdminStartup.java

public static void main(String[] args) {
    System.setProperty(RemotingCommand.RemotingVersionKey, Integer.toString(MQVersion.CurrentVersion));

    try {//  www  .  j  av a 2 s  .c  o  m
        initLogback();
        switch (args.length) {
        case 0:
            printHelp();
            break;
        case 2:
            if (args[0].equals("help")) {
                SubCommand cmd = findSubCommand(args[1]);
                if (cmd != null) {
                    Options options = ServerUtil.buildCommandlineOptions(new Options());
                    options = cmd.buildCommandlineOptions(options);
                    if (options != null) {
                        ServerUtil.printCommandLineHelp("mqadmin " + cmd.commandName(), options);
                    }
                } else {
                    System.out.println("The sub command \'" + args[1] + "\' not exist.");
                }
                break;
            }
        case 1:
        default:
            SubCommand cmd = findSubCommand(args[0]);
            if (cmd != null) {
                // mainargs?args?
                String[] subargs = parseSubArgs(args);

                // ?
                Options options = ServerUtil.buildCommandlineOptions(new Options());
                final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs,
                        cmd.buildCommandlineOptions(options), new PosixParser());
                if (null == commandLine) {
                    System.exit(-1);
                    return;
                }

                if (commandLine.hasOption('n')) {
                    String namesrvAddr = commandLine.getOptionValue('n');
                    System.setProperty(MixAll.NAMESRV_ADDR_PROPERTY, namesrvAddr);
                }

                cmd.execute(commandLine, options);
            } else {
                System.out.println("The sub command \'" + args[0] + "\' not exist.");
            }
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:implementation.java

public static void main(String[] args) throws IOException {
    // Network Variables
    KUSOCKET ClientSocket = new KUSOCKET();
    ENDPOINT ClientAddress = new ENDPOINT("0.0.0.0", 0);
    ENDPOINT BroadcastAddress = new ENDPOINT("255.255.255.255", TokenAccess.SERVER_PORT_NUMBER);
    ENDPOINT AnyAddress = new ENDPOINT("0.0.0.0", 0);

    ENDPOINT ServerAddress = new ENDPOINT();
    MESSAGE OutgoingMessage = new MESSAGE();
    MESSAGE IncomingMessage = new MESSAGE();

    // Output variables         
    int CommentLength = TokenAccess.COMMENT_LENGTH;
    String Comment = new String();

    // Protocol variables
    Timer firstnode = new Timer();
    Timer tokentimer = new Timer();
    Timer tokenlost = new Timer();
    Timer exit = new Timer();
    int DialogueNumber = 0;
    int numRetries = 0;
    Integer addressIP[] = new Integer[2];
    int trigger = 0;
    String lanAddress = "192.168.1.67";
    // Create socket and await connection ///////////////////////////////////////

    // --------------------------------------------------------------------------
    // FINITE STATE MACHINE
    // --------------------------------------------------------------------------

    System.err.println("FSM Started ===================" + '\n');

    // FSM variables
    TokenAccess.STATES state = TokenAccess.STATES.STATE_INITIAL; // Initial STATE
    TokenAccess.STATES lastState = state; // Last STATE
    boolean bContinueEventWait = false;
    boolean bContinueStateLoop = true;
    String last = null;//from w  w w  . j  a  v a 2s  . c  om
    ClientSocket.CreateUDPSocket(ClientAddress);
    while (bContinueStateLoop) {

        switch (state) {
        case STATE_INITIAL:

            firstnode.Start(TokenAccess.firstnode);
            state = TokenAccess.STATES.STATE_STARTED;
            bContinueEventWait = false; // Stop Events loop
            break;

        case STATE_STARTED:

            ClientSocket.MakeConnection(AnyAddress);

            if (firstnode.isExpired()) {
                tokentimer.Start(TokenAccess.tokentimer);

                System.out.println("implementation.main()");
                // adding  local host ip to array
                String t = InetAddress.getLocalHost().getHostAddress();
                String[] split = t.split("\\.");
                addressIP[0] = Integer.parseInt(split[3]);
                System.out.println(split[3]);
                state = TokenAccess.STATES.STATE_TOKENED;
                bContinueEventWait = false;// Stop Events loop

            }
            boolean isMessageQueued = false;

            isMessageQueued = ClientSocket.RetrieveQueuedMessage(TokenAccess.READ_INTERVAL, IncomingMessage,
                    ServerAddress);

            if (isMessageQueued && (IncomingMessage.Type == TokenAccess.PDU_CONNECT)) {
                System.out.println("ring exists");
                //pdu_connect used instead of ring exisits 
                state = TokenAccess.STATES.STATE_tokenLess;
                bContinueEventWait = false;

            }

        case STATE_tokenLess:
            ClientSocket.MakeConnection(AnyAddress);
            while (state == TokenAccess.STATES.STATE_tokenLess) {
                // Instructs the socket to accept

                // building ip address message
                OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_CONNECT,
                        InetAddress.getLocalHost().getHostAddress(),
                        InetAddress.getLocalHost().getHostAddress().length());
                //broadcasting ip address
                ClientSocket.DeliverMessage(OutgoingMessage, BroadcastAddress);
                //     System.out.println("broadcasting address");

                isMessageQueued = ClientSocket.RetrieveQueuedMessage(TokenAccess.READ_INTERVAL, IncomingMessage,
                        ServerAddress);

                //will trigger if used on a 192 network i didnt know how to use regex for any number and a dot
                if (isMessageQueued == true && (IncomingMessage.Type == TokenAccess.PDU_CLOSE)) {
                    System.out.println("pdu close");
                    String ipaddress = IncomingMessage.Buffer;

                    for (int n : addressIP) {
                        if (addressIP[n] == Integer.parseInt(ipaddress)) {
                            String a;
                            a = Integer.toString(addressIP[n]);
                            OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_ACK,
                                    InetAddress.getLocalHost().getHostAddress(),
                                    InetAddress.getLocalHost().getHostAddress().length());
                            ENDPOINT exitAddress = new ENDPOINT(a, TokenAccess.SERVER_PORT_NUMBER);

                            ClientSocket.DeliverMessage(OutgoingMessage, exitAddress);
                            addressIP = ArrayUtils.removeElement(addressIP, n);
                        }

                    }
                }

                if (last != null && tokenlost.bRunning == false) {
                    tokenlost.Start(TokenAccess.tokenlost);
                    last = null;
                    System.out.println("token lost timer started");
                }

                if (isMessageQueued == true && (IncomingMessage.Type == TokenAccess.CMD_CONNECT)) {
                    System.out.println("token lost timer stopped");
                    tokenlost.Stop();
                }

                if (tokenlost.isExpired()) {

                    System.out.println("token lost");

                    for (int n = 0; n < addressIP.length; n++) {
                        String ipaddress = InetAddress.getLocalHost().toString();
                        int lastdot = ipaddress.lastIndexOf(".") + 1;
                        ipaddress = ipaddress.substring(lastdot, ipaddress.length());
                        System.out.println(n);
                        if (addressIP[n] == null) {

                        } else {
                            if (addressIP[n] == Integer.parseInt(ipaddress)) {

                                String a;
                                a = Integer.toString(addressIP[n]);
                                System.out.println("variable a " + a);
                                OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_ACK,
                                        InetAddress.getLocalHost().getHostAddress(),
                                        InetAddress.getLocalHost().getHostAddress().length());
                                ENDPOINT exitAddress = new ENDPOINT(lanAddress, TokenAccess.SERVER_PORT_NUMBER);

                                ClientSocket.DeliverMessage(OutgoingMessage, exitAddress);

                                OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_TOKEN,
                                        InetAddress.getLocalHost().getHostAddress(),
                                        InetAddress.getLocalHost().getHostAddress().length());
                                String b = Integer.toString(addressIP[n]);
                                b = lanAddress;
                                System.out.println(b);

                                ENDPOINT exitAddresss = new ENDPOINT(b, TokenAccess.SERVER_PORT_NUMBER);
                                ClientSocket.DeliverMessage(OutgoingMessage, exitAddresss);

                            }
                        }
                    }

                }

                if (exit.isExpired()) {
                    OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_CLOSE,
                            InetAddress.getLocalHost().getHostAddress(),
                            InetAddress.getLocalHost().getHostAddress().length());
                    exit.Start(30);
                }

                if (isMessageQueued && (IncomingMessage.Type == TokenAccess.PDU_TOKEN)) {
                    tokenlost.Stop();
                    System.out.println(IncomingMessage.Type);
                    state = TokenAccess.STATES.STATE_TOKENED;
                    tokentimer.Start(TokenAccess.tokentimer);
                    break;
                }

            }

        case STATE_TOKENED:
            while (state == TokenAccess.STATES.STATE_TOKENED) {

                //send data
                OutgoingMessage.BuildMessage(0, 0, "ALIVE", CommentLength);
                ClientSocket.DeliverMessage(OutgoingMessage, BroadcastAddress);
                tokenlost.Stop();
                while (trigger == 0) {
                    System.out.println("TOKENED");
                    trigger++;
                }

                if (tokentimer.isExpired()) {
                    trigger = 0;
                    System.out.println("token expired");
                    String ipaddress = InetAddress.getLocalHost().toString();
                    //  System.out.println( "System name : "+ipaddress);

                    for (int n = 0; n < addressIP.length; n++) {
                        // System.out.println(n);
                        int lastdot = ipaddress.lastIndexOf(".") + 1;
                        ipaddress = ipaddress.substring(lastdot, ipaddress.length());
                        // System.out.println("IP address: "+ipaddress);
                        int address1 = Integer.parseInt(ipaddress);

                        System.out.println("made it to line 214");
                        System.out.println(n);
                        System.out.println(addressIP[0]);

                        if (addressIP[n] == address1) {
                            String a;
                            a = Integer.toString(addressIP[n]);
                            System.out.println("variable a = " + a);

                            String ip = InetAddress.getLocalHost().getHostAddress();
                            System.out.println("line 226");
                            System.out.println(ip);

                            OutgoingMessage.BuildMessage(++DialogueNumber, TokenAccess.PDU_TOKEN,
                                    InetAddress.getLocalHost().getHostAddress(),
                                    InetAddress.getLocalHost().getHostAddress().length());
                            String b;

                            System.out.println("line 222");
                            if (n + 1 >= addressIP.length) {
                                b = (ip);
                                //   System.out.println(b);
                            } else {
                                b = ip;

                            }

                            System.out.println(b);

                            //b = InetAddress.getLocalHost().toString().substring(0, lastdot); 
                            // int slash =   b.indexOf("/");
                            System.out.println(b);
                            ENDPOINT exitAddresss = new ENDPOINT(b, TokenAccess.SERVER_PORT_NUMBER);
                            ClientSocket.DeliverMessage(OutgoingMessage, exitAddresss);
                            System.out.println("exiting tokened state");
                            state = TokenAccess.STATES.STATE_tokenLess;
                            last = "1";
                        }
                        break;
                    }
                }
            }

        case STATE_EXIT:
            while (state == TokenAccess.STATES.STATE_EXIT) {
                System.exit(0);

            }

        }

    }

}

From source file:io.lavagna.loader.Loader.java

public static void main(String[] args) throws InterruptedException {

    System.setProperty("datasource.dialect", "MYSQL");

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(TestServiceConfig.class,
            PersistenceAndServiceConfig.class);

    ac.register(CreateCardService.class);

    ProjectService ps = ac.getBean(ProjectService.class);
    CreateCardService ccs = ac.getBean(CreateCardService.class);

    UserRepository ur = ac.getBean(UserRepository.class);
    List<User> users = new ArrayList<>();

    System.out.println("creating users");
    for (int i = 0; i < 30; i++) {
        ur.createUser("loader", "user" + i, null, null, true);
        users.add(ur.findUserByName("loader", "user" + i));
    }//from w w  w .ja  v a2 s.co m
    System.out.println("end creation");

    CardLabelRepository clr = ac.getBean(CardLabelRepository.class);

    List<Project> projects = new ArrayList<>(PROJECT_NUMBERS);
    List<Integer> milestonesIds = new ArrayList<>();
    System.out.println("creating projects");
    for (int i = 0; i < PROJECT_NUMBERS; i++) {
        String name = "Load test project " + i;
        Project p = ps.create(name, "LDTEST_" + i, name);
        projects.add(p);

        // create user labels
        for (int iLabel = 0; iLabel < 10; iLabel++) {
            clr.addLabel(p.getId(), true, LabelType.NULL, LabelDomain.USER, "label-" + iLabel, 0);
        }

        // update milestone label
        CardLabel milestoneLabel = clr.findLabelByName(p.getId(), "MILESTONE", LabelDomain.SYSTEM);
        for (int j = 0; j < MILESTONES_PER_PROJECT; j++) {
            milestonesIds.add(clr.addLabelListValue(milestoneLabel.getId(), Integer.toString(j)).getId());
        }
    }
    System.out.println("end creation");

    System.out.println("creating boards");
    for (Project project : projects) {
        buildBoards(project, ac, users, milestonesIds);
    }
    System.out.println("end creation");

    long processed = ccs.getCreatedCardCounter().get();
    while (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
        long current = ccs.getCreatedCardCounter().get();
        System.err.println("processed: " + (current - processed) + " cards in 10s");
        processed = current;
    }

    ac.close();
}

From source file:niclients.main.pubni.java

public static void main(String[] args) throws UnsupportedEncodingException {

    HttpClient client = new DefaultHttpClient();

    if (commandparser(args)) {

        niname = addauthorityToNiname(niname, authority);
    }/*from   w  w  w .  j av  a  2 s.co  m*/

    niname = niUtils.makenif(niname, filename);
    if (niname != null) {
        if (createpub()) {
            try {

                HttpResponse response = client.execute(post);
                int resp_code = response.getStatusLine().getStatusCode();
                System.err.println("RESP_CODE: " + Integer.toString(resp_code));
                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                String line = "";
                while ((line = rd.readLine()) != null) {
                    System.out.println(line);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            System.out.println("Niname creation failed!\n");
        }
    } else {
        System.out.println("Command line parsing failed!\n");
    }
}

From source file:eu.amidst.core.inference.MPEInferenceExperiments_Deliv1.java

/**
 * The class constructor.// w  w w.j  a va 2 s .  c o m
 * @param args Array of options: "filename variable a b N useVMP" if variable is continuous or "filename variable w N useVMP" for discrete
 */
public static void main(String[] args) throws Exception { // args: seedNetwork numberGaussians numberDiscrete seedAlgorithms

    int seedNetwork = 23423523;
    int numberOfGaussians = 20;
    int numberOfMultinomials = 20;

    int seed = 634634534;

    int parallelSamples = 100;
    int samplingMethodSize = 10000;

    int repetitions = 10;

    int numberOfIterations = 200;

    if (args.length != 8) {
        if (Main.VERBOSE)
            System.out.println("Invalid number of parameters. Using default values");
    } else {
        try {
            seedNetwork = Integer.parseInt(args[0]);
            numberOfGaussians = Integer.parseInt(args[1]);
            numberOfMultinomials = Integer.parseInt(args[2]);

            seed = Integer.parseInt(args[3]);

            parallelSamples = Integer.parseInt(args[4]);
            samplingMethodSize = Integer.parseInt(args[5]);

            repetitions = Integer.parseInt(args[6]);

            numberOfIterations = Integer.parseInt(args[7]);

        } catch (NumberFormatException ex) {
            if (Main.VERBOSE)
                System.out.println(
                        "Invalid parameters. Provide integers: seedNetwork numberGaussians numberDiscrete seedAlgorithms parallelSamples sampleSize repetitions");
            if (Main.VERBOSE)
                System.out.println("Using default parameters");
            if (Main.VERBOSE)
                System.out.println(ex.toString());
            System.exit(20);
        }
    }
    int numberOfLinks = (int) 1.3 * (numberOfGaussians + numberOfMultinomials);

    BayesianNetworkGenerator.setSeed(seedNetwork);
    BayesianNetworkGenerator.setNumberOfGaussianVars(numberOfGaussians);
    BayesianNetworkGenerator.setNumberOfMultinomialVars(numberOfMultinomials, 2);
    BayesianNetworkGenerator.setNumberOfLinks(numberOfLinks);

    String filename = "./networks/simulated/RandomBN_" + Integer.toString(numberOfMultinomials) + "D_"
            + Integer.toString(numberOfGaussians) + "C_" + Integer.toString(seedNetwork) + "_Seed.bn";
    //BayesianNetworkGenerator.generateBNtoFile(numberOfMultinomials,2,numberOfGaussians,numberOfLinks,seedNetwork,filename);
    BayesianNetwork bn = BayesianNetworkGenerator.generateBayesianNetwork();

    //if (Main.VERBOSE) System.out.println(bn.getDAG());
    //if (Main.VERBOSE) System.out.println(bn.toString());

    MPEInference mpeInference = new MPEInference();
    mpeInference.setModel(bn);
    mpeInference.setParallelMode(true);

    //if (Main.VERBOSE) System.out.println("CausalOrder: " + Arrays.toString(Utils.getCausalOrder(mpeInference.getOriginalModel().getDAG()).stream().map(Variable::getName).toArray()));
    List<Variable> modelVariables = Utils.getTopologicalOrder(bn.getDAG());
    if (Main.VERBOSE)
        System.out.println();

    // Including evidence:
    //double observedVariablesRate = 0.00;
    //Assignment evidence = randomEvidence(seed, observedVariablesRate, bn);
    //mpeInference.setEvidence(evidence);

    mpeInference.setSampleSize(parallelSamples);
    mpeInference.setSeed(seed);
    mpeInference.setNumberOfIterations(numberOfIterations);

    double[] SA_All_prob = new double[repetitions];
    double[] SA_Some_prob = new double[repetitions];
    double[] HC_All_prob = new double[repetitions];
    double[] HC_Some_prob = new double[repetitions];
    double[] sampling_prob = new double[repetitions];

    double[] SA_All_time = new double[repetitions];
    double[] SA_Some_time = new double[repetitions];
    double[] HC_All_time = new double[repetitions];
    double[] HC_Some_time = new double[repetitions];
    double[] sampling_time = new double[repetitions];

    long timeStart;
    long timeStop;
    double execTime;

    Assignment mpeEstimate;

    mpeInference.setParallelMode(true);

    for (int k = 0; k < repetitions; k++) {

        mpeInference.setSampleSize(parallelSamples);

        /***********************************************
         *        SIMULATED ANNEALING
         ************************************************/

        // MPE INFERENCE WITH SIMULATED ANNEALING, ALL VARIABLES
        //if (Main.VERBOSE) System.out.println();
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.SA_GLOBAL);

        //mpeEstimate = mpeInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate (SA.All): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().));
        //if (Main.VERBOSE) System.out.println();
        SA_All_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        SA_All_time[k] = execTime;

        // MPE INFERENCE WITH SIMULATED ANNEALING, SOME VARIABLES AT EACH TIME
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.SA_LOCAL);

        //mpeEstimate = mpeInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate  (SA.Some): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: "+ Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().));
        //if (Main.VERBOSE) System.out.println();
        SA_Some_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        SA_Some_time[k] = execTime;

        /***********************************************
         *        HILL CLIMBING
         ************************************************/

        // MPE INFERENCE WITH HILL CLIMBING, ALL VARIABLES
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.HC_GLOBAL);

        //mpeEstimate = mpeInference.getEstimate();
        //modelVariables = mpeInference.getOriginalModel().getVariables().getListOfVariables();
        //if (Main.VERBOSE) System.out.println("MPE estimate (HC.All): " + mpeEstimate.outputString(modelVariables));
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        HC_All_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        HC_All_time[k] = execTime;

        //  MPE INFERENCE WITH HILL CLIMBING, ONE VARIABLE AT EACH TIME
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.HC_LOCAL);

        //mpeEstimate = mpeInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate  (HC.Some): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        HC_Some_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        HC_Some_time[k] = execTime;

        /***********************************************
         *        SAMPLING AND DETERMINISTIC
         ************************************************/

        // MPE INFERENCE WITH SIMULATION AND PICKING MAX

        mpeInference.setSampleSize(samplingMethodSize);

        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.SAMPLING);

        //mpeEstimate = mpeInference.getEstimate();
        //modelVariables = mpeInference.getOriginalModel().getVariables().getListOfVariables();
        //if (Main.VERBOSE) System.out.println("MPE estimate (SAMPLING): " + mpeEstimate.outputString(modelVariables));
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        sampling_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        sampling_time[k] = execTime;
    }

    double determ_prob = 0;
    double determ_time = 0;

    if (bn.getNumberOfVars() <= 50) {

        // MPE INFERENCE, DETERMINISTIC
        timeStart = System.nanoTime();
        //mpeInference.runInference(-2);

        //mpeEstimate = mpeInference.getEstimate();
        //modelVariables = mpeInference.getOriginalModel().getVariables().getListOfVariables();
        //if (Main.VERBOSE) System.out.println("MPE estimate (DETERM.): " + mpeEstimate.outputString(modelVariables));
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();

        determ_prob = mpeInference.getLogProbabilityOfEstimate();
        determ_time = execTime;
        determ_prob = -34.64743236365595;
        determ_time = 0;

    } else {
        if (Main.VERBOSE)
            System.out.println("Too many variables for deterministic method");
    }

    /***********************************************
     *        DISPLAY OF RESULTS
     ************************************************/

    if (Main.VERBOSE)
        System.out.println("*** RESULTS ***");

    //        if (Main.VERBOSE) System.out.println("SA_All log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(SA_All_prob));
    //        if (Main.VERBOSE) System.out.println("SA_Some log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(SA_Some_prob));
    //        if (Main.VERBOSE) System.out.println("HC_All log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(HC_All_prob));
    //        if (Main.VERBOSE) System.out.println("HC_Some log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(HC_Some_prob));
    //        if (Main.VERBOSE) System.out.println("Sampling log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(sampling_prob));
    //
    //        if(bn.getNumberOfVars()<=50) {
    //            if (Main.VERBOSE) System.out.println("Deterministic log-probability");
    //            if (Main.VERBOSE) System.out.println(Double.toString(determ_prob));
    //        }
    //        if (Main.VERBOSE) System.out.println();

    final double determ_prob_FINAL = determ_prob;

    //        int SA_All_success = (int) Arrays.stream(SA_All_prob).filter(db -> (db <= determ_prob_FINAL+0.001 && db >=determ_prob_FINAL-0.001)).count();
    //        int SA_Some_success = (int) Arrays.stream(SA_Some_prob).filter(db -> (db <= determ_prob_FINAL+0.001 && db >=determ_prob_FINAL-0.001)).count();
    //        int HC_All_success = (int) Arrays.stream(HC_All_prob).filter(db -> (db <= determ_prob_FINAL+0.001 && db >=determ_prob_FINAL-0.001)).count();
    //        int HC_Some_success = (int) Arrays.stream(HC_Some_prob).filter(db -> (db <= determ_prob_FINAL+0.001 && db >=determ_prob_FINAL-0.001)).count();
    //        int sampling_success = (int) Arrays.stream(sampling_prob).filter(db -> (db <= determ_prob_FINAL+0.001 && db >=determ_prob_FINAL-0.001)).count();
    //
    //        if (Main.VERBOSE) System.out.println("SA_All % success");
    //        if (Main.VERBOSE) System.out.println(Double.toString( 100 * SA_All_success/repetitions ));
    //        if (Main.VERBOSE) System.out.println("SA_Some % success");
    //        if (Main.VERBOSE) System.out.println(Double.toString( 100 * SA_Some_success/repetitions ));
    //        if (Main.VERBOSE) System.out.println("HC_All % success");
    //        if (Main.VERBOSE) System.out.println(Double.toString( 100 * HC_All_success/repetitions ));
    //        if (Main.VERBOSE) System.out.println("HC_Some % success");
    //        if (Main.VERBOSE) System.out.println(Double.toString( 100 * HC_Some_success/repetitions ));
    //        if (Main.VERBOSE) System.out.println("Sampling % success");
    //        if (Main.VERBOSE) System.out.println(Double.toString( 100 * sampling_success/repetitions ));
    //        if (Main.VERBOSE) System.out.println();

    if (Main.VERBOSE)
        System.out.println("SA_All RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Arrays.stream(SA_All_prob)
                .map(value -> Math.pow(value - determ_prob_FINAL, 2)).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("SA_Some RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Arrays.stream(SA_Some_prob)
                .map(value -> Math.pow(value - determ_prob_FINAL, 2)).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("HC_All RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Arrays.stream(HC_All_prob)
                .map(value -> Math.pow(value - determ_prob_FINAL, 2)).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("HC_Some RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Arrays.stream(HC_Some_prob)
                .map(value -> Math.pow(value - determ_prob_FINAL, 2)).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("Sampling RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Arrays.stream(sampling_prob)
                .map(value -> Math.pow(value - determ_prob_FINAL, 2)).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println();

    if (Main.VERBOSE)
        System.out.println("SA_All times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(SA_All_time));
    if (Main.VERBOSE)
        System.out.println("Mean time: " + Double.toString(Arrays.stream(SA_All_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("SA_Some times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(SA_Some_time));
    if (Main.VERBOSE)
        System.out
                .println("Mean time: " + Double.toString(Arrays.stream(SA_Some_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("HC_All times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(HC_All_time));
    if (Main.VERBOSE)
        System.out.println("Mean time: " + Double.toString(Arrays.stream(HC_All_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("HC_Some times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(HC_Some_time));
    if (Main.VERBOSE)
        System.out
                .println("Mean time: " + Double.toString(Arrays.stream(HC_Some_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("Sampling times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(sampling_time));
    if (Main.VERBOSE)
        System.out
                .println("Mean time: " + Double.toString(Arrays.stream(sampling_time).average().getAsDouble()));

    if (bn.getNumberOfVars() <= 50) {
        if (Main.VERBOSE)
            System.out.println("Deterministic time");
        if (Main.VERBOSE)
            System.out.println(Double.toString(determ_time));
        if (Main.VERBOSE)
            System.out.println("and probability");
        if (Main.VERBOSE)
            System.out.println(determ_prob);
    }

}

From source file:guardar.en.base.de.datos.MainServidor.java

public static void main(String[] args)
        throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException {

    Mongo mongo = new Mongo("localhost", 27017);

    // nombre de la base de datos
    DB database = mongo.getDB("paginas");
    // coleccion de la db
    DBCollection collection = database.getCollection("indice");
    DBCollection collection_textos = database.getCollection("tabla");
    ArrayList<String> lista_textos = new ArrayList();

    try {/* w w  w. j ava  2 s .  co m*/
        ServerSocket servidor = new ServerSocket(4545); // Crear un servidor en pausa hasta que un cliente llegue.
        while (true) {
            String aux = new String();
            lista_textos.clear();
            Socket clienteNuevo = servidor.accept();// Si llega se acepta.
            // Queda en pausa otra vez hasta que un objeto llegue.
            ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream());

            JSONObject request = (JSONObject) entrada.readObject();
            String b = (String) request.get("id");
            //hacer una query a la base de datos con la palabra que se quiere obtener

            BasicDBObject query = new BasicDBObject("palabra", b);
            DBCursor cursor = collection.find(query);
            ArrayList<DocumentosDB> lista_doc = new ArrayList<>();
            // de la query tomo el campo documentos y los agrego a una lista
            try {
                while (cursor.hasNext()) {
                    //System.out.println(cursor.next());
                    BasicDBList campo_documentos = (BasicDBList) cursor.next().get("documentos");
                    // en el for voy tomando uno por uno los elementos en el campo documentos
                    for (Iterator<Object> it = campo_documentos.iterator(); it.hasNext();) {
                        BasicDBObject dbo = (BasicDBObject) it.next();
                        //DOC tiene id y frecuencia
                        DocumentosDB doc = new DocumentosDB();
                        doc.makefn2(dbo);
                        //int id = (int)doc.getId_documento();
                        //int f = (int)doc.getFrecuencia();

                        lista_doc.add(doc);

                        //*******************************************

                        //********************************************

                        //QUERY A LA COLECCION DE TEXTOS
                        /* BasicDBObject query_textos = new BasicDBObject("id", doc.getId_documento());//query
                         DBCursor cursor_textos = collection_textos.find(query_textos);
                         try {
                        while (cursor_textos.hasNext()) {
                                    
                                    
                            DBObject obj = cursor_textos.next();
                                
                            String titulo = (String) obj.get("titulo");
                            titulo = titulo + "\n\n";
                            String texto = (String) obj.get("texto");
                                
                            String texto_final = titulo + texto;
                            aux = texto_final;
                            lista_textos.add(texto_final);
                        }
                         } finally {
                        cursor_textos.close();
                         }*/
                        //System.out.println(doc.getId_documento());
                        //System.out.println(doc.getFrecuencia());

                    } // end for

                } //end while query

            } finally {
                cursor.close();
            }

            // ordeno la lista de menor a mayor
            Collections.sort(lista_doc, new Comparator<DocumentosDB>() {

                @Override
                public int compare(DocumentosDB o1, DocumentosDB o2) {
                    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                    return o1.getFrecuencia().compareTo(o2.getFrecuencia());
                }
            });
            int tam = lista_doc.size() - 1;
            for (int j = tam; j >= 0; j--) {

                BasicDBObject query_textos = new BasicDBObject("id",
                        (int) lista_doc.get(j).getId_documento().intValue());//query
                DBCursor cursor_textos = collection_textos.find(query_textos);// lo busco
                try {
                    while (cursor_textos.hasNext()) {

                        DBObject obj = cursor_textos.next();
                        String titulo = "*******************************";
                        titulo += (String) obj.get("titulo");
                        int f = (int) lista_doc.get(j).getFrecuencia().intValue();
                        String strinf = Integer.toString(f);
                        titulo += "******************************* frecuencia:" + strinf;
                        titulo = titulo + "\n\n";

                        String texto = (String) obj.get("texto");

                        String texto_final = titulo + texto + "\n\n";
                        aux = aux + texto_final;
                        //lista_textos.add(texto_final);
                    }
                } finally {
                    cursor_textos.close();
                }

            }

            //actualizar el cache
            try {
                Socket cliente_cache = new Socket("localhost", 4500); // nos conectamos con el servidor
                ObjectOutputStream mensaje_cache = new ObjectOutputStream(cliente_cache.getOutputStream()); // get al output del servidor, que es cliente : socket del cliente q se conecto al server
                JSONObject actualizacion_cache = new JSONObject();
                actualizacion_cache.put("actualizacion", 1);
                actualizacion_cache.put("busqueda", b);
                actualizacion_cache.put("respuesta", aux);
                mensaje_cache.writeObject(actualizacion_cache); // envio el msj al servidor
            } catch (Exception ex) {

            }

            //RESPONDER DESDE EL SERVIDORIndex al FRONT
            ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj
            resp.writeObject(aux);
            System.out.println("msj enviado desde el servidor");

        }
    } catch (IOException ex) {
        Logger.getLogger(MainServidor.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:eu.amidst.core.inference.MPEInferenceExperiments_Deliv2.java

/**
 * The class constructor.//from  w w  w  . ja va 2  s . c o m
 * @param args Array of options: "filename variable a b N useVMP" if variable is continuous or "filename variable w N useVMP" for discrete
 */
public static void main(String[] args) throws Exception { // args: seedNetwork numberGaussians numberDiscrete seedAlgorithms

    int seedNetwork = 234235;
    int numberOfGaussians = 100;
    int numberOfMultinomials = 100;

    int seed = 125634;

    int parallelSamples = 100;
    int samplingMethodSize = 10000;

    int repetitions = 10;

    int numberOfIterations = 200;

    if (args.length != 8) {
        if (Main.VERBOSE)
            System.out.println("Invalid number of parameters. Using default values");
    } else {
        try {
            seedNetwork = Integer.parseInt(args[0]);
            numberOfGaussians = Integer.parseInt(args[1]);
            numberOfMultinomials = Integer.parseInt(args[2]);

            seed = Integer.parseInt(args[3]);

            parallelSamples = Integer.parseInt(args[4]);
            samplingMethodSize = Integer.parseInt(args[5]);

            repetitions = Integer.parseInt(args[6]);

            numberOfIterations = Integer.parseInt(args[7]);

        } catch (NumberFormatException ex) {
            if (Main.VERBOSE)
                System.out.println(
                        "Invalid parameters. Provide integers: seedNetwork numberGaussians numberDiscrete seedAlgorithms parallelSamples sampleSize repetitions");
            if (Main.VERBOSE)
                System.out.println("Using default parameters");
            if (Main.VERBOSE)
                System.out.println(ex.toString());
            System.exit(20);
        }
    }
    int numberOfLinks = (int) 1.3 * (numberOfGaussians + numberOfMultinomials);

    BayesianNetworkGenerator.setSeed(seedNetwork);
    BayesianNetworkGenerator.setNumberOfGaussianVars(numberOfGaussians);
    BayesianNetworkGenerator.setNumberOfMultinomialVars(numberOfMultinomials, 2);
    BayesianNetworkGenerator.setNumberOfLinks(numberOfLinks);

    String filename = "./networks/simulated/RandomBN_" + Integer.toString(numberOfMultinomials) + "D_"
            + Integer.toString(numberOfGaussians) + "C_" + Integer.toString(seedNetwork) + "_Seed.bn";
    //BayesianNetworkGenerator.generateBNtoFile(numberOfMultinomials,2,numberOfGaussians,numberOfLinks,seedNetwork,filename);
    BayesianNetwork bn = BayesianNetworkGenerator.generateBayesianNetwork();

    //if (Main.VERBOSE) System.out.println(bn.getDAG());
    //if (Main.VERBOSE) System.out.println(bn.toString());

    MPEInference mpeInference = new MPEInference();
    mpeInference.setModel(bn);
    mpeInference.setParallelMode(true);

    //if (Main.VERBOSE) System.out.println("CausalOrder: " + Arrays.toString(Utils.getCausalOrder(mpeInference.getOriginalModel().getDAG()).stream().map(Variable::getName).toArray()));
    List<Variable> modelVariables = Utils.getTopologicalOrder(bn.getDAG());
    if (Main.VERBOSE)
        System.out.println();

    // Including evidence:
    //double observedVariablesRate = 0.00;
    //Assignment evidence = randomEvidence(seed, observedVariablesRate, bn);
    //mpeInference.setEvidence(evidence);

    mpeInference.setNumberOfIterations(numberOfIterations);

    mpeInference.setSampleSize(parallelSamples);
    mpeInference.setSeed(seed);

    double[] SA_All_prob = new double[repetitions];
    double[] SA_Some_prob = new double[repetitions];
    double[] HC_All_prob = new double[repetitions];
    double[] HC_Some_prob = new double[repetitions];
    double[] sampling_prob = new double[repetitions];

    double[] SA_All_time = new double[repetitions];
    double[] SA_Some_time = new double[repetitions];
    double[] HC_All_time = new double[repetitions];
    double[] HC_Some_time = new double[repetitions];
    double[] sampling_time = new double[repetitions];

    long timeStart;
    long timeStop;
    double execTime;

    Assignment bestMpeEstimate = new HashMapAssignment(bn.getNumberOfVars());
    double bestMpeEstimateLogProb = -100000;
    int bestMpeEstimateMethod = -5;

    mpeInference.setParallelMode(true);

    final double bestProbability = -171.81983739975342;
    //        BEST MPE ESTIMATE FOUND:
    //        {DiscreteVar0 = 0, DiscreteVar1 = 0, DiscreteVar2 = 1, DiscreteVar3 = 0, DiscreteVar4 = 0, DiscreteVar5 = 0, DiscreteVar6 = 0, DiscreteVar7 = 0, DiscreteVar8 = 0, DiscreteVar9 = 0, DiscreteVar10 = 0, DiscreteVar11 = 1, DiscreteVar12 = 1, DiscreteVar13 = 1, DiscreteVar14 = 0, DiscreteVar15 = 0, DiscreteVar16 = 0, DiscreteVar17 = 1, DiscreteVar18 = 1, DiscreteVar19 = 0, DiscreteVar20 = 0, DiscreteVar21 = 0, DiscreteVar22 = 1, DiscreteVar23 = 1, DiscreteVar24 = 0, DiscreteVar25 = 0, DiscreteVar26 = 0, DiscreteVar27 = 0, DiscreteVar28 = 1, DiscreteVar29 = 1, DiscreteVar30 = 0, DiscreteVar31 = 0, DiscreteVar32 = 1, DiscreteVar33 = 1, DiscreteVar34 = 0, DiscreteVar35 = 1, DiscreteVar36 = 0, DiscreteVar37 = 0, DiscreteVar38 = 0, DiscreteVar39 = 0, DiscreteVar40 = 0, DiscreteVar41 = 1, DiscreteVar42 = 1, DiscreteVar43 = 1, DiscreteVar44 = 0, DiscreteVar45 = 1, DiscreteVar46 = 1, DiscreteVar47 = 0, DiscreteVar48 = 1, DiscreteVar49 = 1, DiscreteVar50 = 0, DiscreteVar51 = 0, DiscreteVar52 = 0, DiscreteVar53 = 1, DiscreteVar54 = 0, DiscreteVar55 = 1, DiscreteVar56 = 1, DiscreteVar57 = 0, DiscreteVar58 = 1, DiscreteVar59 = 0, DiscreteVar60 = 0, DiscreteVar61 = 1, DiscreteVar62 = 0, DiscreteVar63 = 0, DiscreteVar64 = 0, DiscreteVar65 = 1, DiscreteVar66 = 1, DiscreteVar67 = 1, DiscreteVar68 = 1, DiscreteVar69 = 1, DiscreteVar70 = 1, DiscreteVar71 = 0, DiscreteVar72 = 0, DiscreteVar73 = 0, DiscreteVar74 = 0, DiscreteVar75 = 1, DiscreteVar76 = 0, DiscreteVar77 = 1, DiscreteVar78 = 1, DiscreteVar79 = 0, DiscreteVar80 = 1, DiscreteVar81 = 1, DiscreteVar82 = 1, DiscreteVar83 = 0, DiscreteVar84 = 1, DiscreteVar85 = 1, DiscreteVar86 = 1, DiscreteVar87 = 1, DiscreteVar88 = 0, DiscreteVar89 = 0, DiscreteVar90 = 1, DiscreteVar91 = 0, DiscreteVar92 = 0, DiscreteVar93 = 0, DiscreteVar94 = 0, DiscreteVar95 = 0, DiscreteVar96 = 0, DiscreteVar97 = 1, DiscreteVar98 = 1, DiscreteVar99 = 1, GaussianVar0 = -4,551, GaussianVar1 = 14,731, GaussianVar2 = -1,108, GaussianVar3 = -6,564, GaussianVar4 = -2,415, GaussianVar5 = 10,265, GaussianVar6 = 6,058, GaussianVar7 = 6,367, GaussianVar8 = 26,731, GaussianVar9 = 0,807, GaussianVar10 = -19,410, GaussianVar11 = 18,070, GaussianVar12 = -14,177, GaussianVar13 = 7,765, GaussianVar14 = 3,596, GaussianVar15 = -7,757, GaussianVar16 = -1,705, GaussianVar17 = -5,476, GaussianVar18 = -17,932, GaussianVar19 = 22,843, GaussianVar20 = -9,860, GaussianVar21 = 3,844, GaussianVar22 = 8,262, GaussianVar23 = -9,080, GaussianVar24 = 1,750, GaussianVar25 = 11,532, GaussianVar26 = 0,700, GaussianVar27 = 12,206, GaussianVar28 = 8,532, GaussianVar29 = -40,395, GaussianVar30 = 19,981, GaussianVar31 = -30,713, GaussianVar32 = 0,476, GaussianVar33 = -12,406, GaussianVar34 = 4,942, GaussianVar35 = -0,245, GaussianVar36 = -176,861, GaussianVar37 = 8,474, GaussianVar38 = -8,849, GaussianVar39 = -3,844, GaussianVar40 = -8,495, GaussianVar41 = 4,664, GaussianVar42 = -4,730, GaussianVar43 = 4,063, GaussianVar44 = -1,631, GaussianVar45 = -103,340, GaussianVar46 = -1,598, GaussianVar47 = -11,460, GaussianVar48 = 14,123, GaussianVar49 = -0,135, GaussianVar50 = 1,487, GaussianVar51 = -4,859, GaussianVar52 = 0,370, GaussianVar53 = -10,038, GaussianVar54 = 18,145, GaussianVar55 = 225,324, GaussianVar56 = 1,059, GaussianVar57 = -1,170, GaussianVar58 = 83,480, GaussianVar59 = 7,375, GaussianVar60 = 5,091, GaussianVar61 = 61,381, GaussianVar62 = 42,955, GaussianVar63 = -712,533, GaussianVar64 = 21,460, GaussianVar65 = -19,337, GaussianVar66 = 213,903, GaussianVar67 = -10,197, GaussianVar68 = -65,619, GaussianVar69 = 41,045, GaussianVar70 = 133,452, GaussianVar71 = -1,997, GaussianVar72 = 17,485, GaussianVar73 = -40,691, GaussianVar74 = -16,378, GaussianVar75 = -72,550, GaussianVar76 = -1,761, GaussianVar77 = 12,647, GaussianVar78 = -31,531, GaussianVar79 = -41,444, GaussianVar80 = -14,190, GaussianVar81 = 17,387, GaussianVar82 = -12,333, GaussianVar83 = -57,795, GaussianVar84 = -20,386, GaussianVar85 = 49,735, GaussianVar86 = 14,593, GaussianVar87 = -168,778, GaussianVar88 = -6,157, GaussianVar89 = 82,897, GaussianVar90 = -30,018, GaussianVar91 = -2,366, GaussianVar92 = -12,753, GaussianVar93 = -141,490, GaussianVar94 = 17,844, GaussianVar95 = 99,703, GaussianVar96 = -37,859, GaussianVar97 = 123,045, GaussianVar98 = -4,054, GaussianVar99 = 3,024}
    //        with method:2
    //        and log probability: -171.81983739975342

    for (int k = 0; k < repetitions; k++) {

        mpeInference.setSampleSize(parallelSamples);

        /***********************************************
         *        SIMULATED ANNEALING
         ************************************************/

        // MPE INFERENCE WITH SIMULATED ANNEALING, ALL VARIABLES
        //if (Main.VERBOSE) System.out.println();
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.SA_GLOBAL);

        //mpeEstimate = mpeInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate (SA.All): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().));
        //if (Main.VERBOSE) System.out.println();
        SA_All_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        SA_All_time[k] = execTime;

        if (mpeInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mpeInference.getEstimate();
            bestMpeEstimateLogProb = mpeInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = 1;
        }

        // MPE INFERENCE WITH SIMULATED ANNEALING, SOME VARIABLES AT EACH TIME
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.SA_LOCAL);

        //mpeEstimate = mpeInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate  (SA.Some): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: "+ Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println(.toString(mapInference.getOriginalModel().getStaticVariables().iterator().));
        //if (Main.VERBOSE) System.out.println();
        SA_Some_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        SA_Some_time[k] = execTime;

        if (mpeInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mpeInference.getEstimate();
            bestMpeEstimateLogProb = mpeInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = 0;
        }

        /***********************************************
         *        HILL CLIMBING
         ************************************************/

        // MPE INFERENCE WITH HILL CLIMBING, ALL VARIABLES
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.HC_GLOBAL);

        //mpeEstimate = mpeInference.getEstimate();
        //modelVariables = mpeInference.getOriginalModel().getVariables().getListOfVariables();
        //if (Main.VERBOSE) System.out.println("MPE estimate (HC.All): " + mpeEstimate.outputString(modelVariables));
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        HC_All_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        HC_All_time[k] = execTime;

        if (mpeInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mpeInference.getEstimate();
            bestMpeEstimateLogProb = mpeInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = 3;
        }

        //  MPE INFERENCE WITH HILL CLIMBING, ONE VARIABLE AT EACH TIME
        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.HC_LOCAL);

        //mpeEstimate = mpeInference.getEstimate();
        //if (Main.VERBOSE) System.out.println("MPE estimate  (HC.Some): " + mpeEstimate.outputString(modelVariables));   //toString(modelVariables)
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        HC_Some_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        HC_Some_time[k] = execTime;

        if (mpeInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mpeInference.getEstimate();
            bestMpeEstimateLogProb = mpeInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = 2;
        }

        /***********************************************
         *        SAMPLING AND DETERMINISTIC
         ************************************************/

        // MPE INFERENCE WITH SIMULATION AND PICKING MAX

        mpeInference.setSampleSize(samplingMethodSize);

        timeStart = System.nanoTime();
        mpeInference.runInference(MPEInference.SearchAlgorithm.SAMPLING);

        //mpeEstimate = mpeInference.getEstimate();
        //modelVariables = mpeInference.getOriginalModel().getVariables().getListOfVariables();
        //if (Main.VERBOSE) System.out.println("MPE estimate (SAMPLING): " + mpeEstimate.outputString(modelVariables));
        //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
        timeStop = System.nanoTime();
        execTime = (double) (timeStop - timeStart) / 1000000000.0;
        //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
        //if (Main.VERBOSE) System.out.println();
        sampling_prob[k] = mpeInference.getLogProbabilityOfEstimate();
        sampling_time[k] = execTime;

        if (mpeInference.getLogProbabilityOfEstimate() > bestMpeEstimateLogProb) {
            bestMpeEstimate = mpeInference.getEstimate();
            bestMpeEstimateLogProb = mpeInference.getLogProbabilityOfEstimate();
            bestMpeEstimateMethod = -1;
        }
    }

    double determ_prob = 0;
    double determ_time = 0;

    //        if(bn.getNumberOfVars()<=50) {
    //
    //            // MPE INFERENCE, DETERMINISTIC
    //            timeStart = System.nanoTime();
    //            mpeInference.runInference(-2);
    //
    //            //mpeEstimate = mpeInference.getEstimate();
    //            //modelVariables = mpeInference.getOriginalModel().getVariables().getListOfVariables();
    //            //if (Main.VERBOSE) System.out.println("MPE estimate (DETERM.): " + mpeEstimate.outputString(modelVariables));
    //            //if (Main.VERBOSE) System.out.println("with probability: " + Math.exp(mpeInference.getLogProbabilityOfEstimate()) + ", logProb: " + mpeInference.getLogProbabilityOfEstimate());
    //            timeStop = System.nanoTime();
    //            execTime = (double) (timeStop - timeStart) / 1000000000.0;
    //            //if (Main.VERBOSE) System.out.println("computed in: " + Double.toString(execTime) + " seconds");
    //            //if (Main.VERBOSE) System.out.println();
    //            determ_prob = mpeInference.getLogProbabilityOfEstimate();
    //            determ_time = execTime;
    //
    //        }
    //        else {
    //            if (Main.VERBOSE) System.out.println("Too many variables for deterministic method");
    //        }

    /***********************************************
     *        DISPLAY OF RESULTS
     ************************************************/

    if (Main.VERBOSE)
        System.out.println("*** RESULTS ***");

    //        if (Main.VERBOSE) System.out.println("SA_All log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(SA_All_prob));
    //        if (Main.VERBOSE) System.out.println("SA_Some log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(SA_Some_prob));
    //        if (Main.VERBOSE) System.out.println("HC_All log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(HC_All_prob));
    //        if (Main.VERBOSE) System.out.println("HC_Some log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(HC_Some_prob));
    //        if (Main.VERBOSE) System.out.println("Sampling log-probabilities");
    //        if (Main.VERBOSE) System.out.println(Arrays.toString(sampling_prob));
    //        if(bn.getNumberOfVars()<=50) {
    //            if (Main.VERBOSE) System.out.println("Deterministic log-probability");
    //            if (Main.VERBOSE) System.out.println(Double.toString(determ_prob));
    //        }

    if (Main.VERBOSE)
        System.out.println("SA_All RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Math.sqrt(Arrays.stream(SA_All_prob)
                .map(value -> Math.pow(value - bestProbability, 2)).average().getAsDouble())));
    if (Main.VERBOSE)
        System.out.println("SA_Some RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Math.sqrt(Arrays.stream(SA_Some_prob)
                .map(value -> Math.pow(value - bestProbability, 2)).average().getAsDouble())));
    if (Main.VERBOSE)
        System.out.println("HC_All RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Math.sqrt(Arrays.stream(HC_All_prob)
                .map(value -> Math.pow(value - bestProbability, 2)).average().getAsDouble())));
    if (Main.VERBOSE)
        System.out.println("HC_Some RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Math.sqrt(Arrays.stream(HC_Some_prob)
                .map(value -> Math.pow(value - bestProbability, 2)).average().getAsDouble())));
    if (Main.VERBOSE)
        System.out.println("Sampling RMS probabilities");
    if (Main.VERBOSE)
        System.out.println(Double.toString(Math.sqrt(Arrays.stream(sampling_prob)
                .map(value -> Math.pow(value - bestProbability, 2)).average().getAsDouble())));
    if (Main.VERBOSE)
        System.out.println();

    if (Main.VERBOSE)
        System.out.println("SA_All times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(SA_All_time));
    if (Main.VERBOSE)
        System.out.println("Mean time: " + Double.toString(Arrays.stream(SA_All_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("SA_Some times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(SA_Some_time));
    if (Main.VERBOSE)
        System.out
                .println("Mean time: " + Double.toString(Arrays.stream(SA_Some_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("HC_All times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(HC_All_time));
    if (Main.VERBOSE)
        System.out.println("Mean time: " + Double.toString(Arrays.stream(HC_All_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("HC_Some times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(HC_Some_time));
    if (Main.VERBOSE)
        System.out
                .println("Mean time: " + Double.toString(Arrays.stream(HC_Some_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println("Sampling times");
    //if (Main.VERBOSE) System.out.println(Arrays.toString(sampling_time));
    if (Main.VERBOSE)
        System.out
                .println("Mean time: " + Double.toString(Arrays.stream(sampling_time).average().getAsDouble()));
    if (Main.VERBOSE)
        System.out.println();
    //        if(bn.getNumberOfVars()<=50) {
    //            if (Main.VERBOSE) System.out.println("Deterministic time");
    //            if (Main.VERBOSE) System.out.println(Double.toString(determ_time));
    //        }

    if (Main.VERBOSE)
        System.out.println("BEST MPE ESTIMATE FOUND:");
    if (Main.VERBOSE)
        System.out.println(bestMpeEstimate.outputString(Utils.getTopologicalOrder(bn.getDAG())));
    if (Main.VERBOSE)
        System.out.println("with method:" + bestMpeEstimateMethod);
    if (Main.VERBOSE)
        System.out.println("and log probability: " + bestMpeEstimateLogProb);
}

From source file:LamportBasicVersion.java

public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException {
    totalMessageCount = 0;/*  w  ww  .j  ava 2  s  .  c om*/
    //For parsing the file and storing the information
    String line;
    String configurationFile = "configuration.txt";
    int lineCountInFile = 0;
    myProcessId = Integer.parseInt(args[0]);
    FileReader fileReader = new FileReader(configurationFile);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    while ((line = bufferedReader.readLine()) != null) {
        if ((!(line.startsWith("#"))) && (!(line.isEmpty()))) {
            lineCountInFile = lineCountInFile + 1;
            String[] splitLine = line.split(" ");
            switch (lineCountInFile) {
            case 1:
                numberOfProcesses = Integer.parseInt(splitLine[0]);
                interRequestDelay = Integer.parseInt(splitLine[1]);
                csExecutionTime = Integer.parseInt(splitLine[2]);
                maxNumberOfRequest = Integer.parseInt(splitLine[3]);
                machineNames = new String[Integer.parseInt(splitLine[0])];
                portNumbers = new int[Integer.parseInt(splitLine[0])];
                break;
            default:
                machineNames[lineCountInFile - 2] = splitLine[1];
                portNumbers[lineCountInFile - 2] = Integer.parseInt(splitLine[2]);
                break;
            }
        }
    }
    conditionArray = new int[numberOfProcesses];
    finishFlagArray = new int[numberOfProcesses];
    //Initializing vector class
    VectorClass.initialize(numberOfProcesses);
    //Fill the arrays with zero false value
    for (int o = 0; o < numberOfProcesses; o++) {
        conditionArray[o] = 0;
        finishFlagArray[o] = 0;
    }
    // Write output to file
    filename = filename + Integer.toString(myProcessId) + ".out";
    file = new File(filename);
    file.createNewFile();
    writer = new FileWriter(file);
    // Write clocks to file
    filenameClock = filenameClock + Integer.toString(myProcessId) + ".out";
    fileClock = new File(filenameClock);
    fileClock.createNewFile();
    //writerClock = new FileWriter(fileClock);
    fw = new FileWriter(fileClock);
    bw = new BufferedWriter(fw);
    //
    // Expo mean insert
    csExecutionExpoDelay = new ExponentialDistribution(csExecutionTime);
    interRequestExpoDelay = new ExponentialDistribution(interRequestDelay);
    //
    System.out.println("********************************************************");
    System.out.println("My process id : " + myProcessId);
    System.out.println("Number of processes : " + numberOfProcesses);
    System.out.println("Inter-request delay : " + interRequestDelay);
    System.out.println("Critical section execution time : " + csExecutionTime);
    System.out.println("Maximum number of request : " + maxNumberOfRequest);
    System.out.println(
            "My process name : " + machineNames[myProcessId] + " My port number : " + portNumbers[myProcessId]);
    for (int i = 0; i < numberOfProcesses; i++) {
        System.out.println("Process name : " + machineNames[i] + " Port number : " + portNumbers[i]);
    }
    System.out.println("********************************************************");
    //For hosting server localhost
    SctpServerChannel sctpServerChannel = SctpServerChannel.open();
    InetSocketAddress serverAddr = new InetSocketAddress(portNumbers[myProcessId]);
    sctpServerChannel.bind(serverAddr);
    System.out.println("********************************************************");
    System.out.println("Local server hosted");
    System.out.println("********************************************************");
    //For creating neighbor SCTP channels
    Thread.sleep(30000);
    socketAddress = new SocketAddress[numberOfProcesses];
    sctpChannel = new SctpChannel[numberOfProcesses];
    System.out.println("********************************************************");
    System.out.println("Neighbor channels created");
    System.out.println("********************************************************");
    //Thread spanned for generating critical section request
    new Thread(new LamportBasicVersion()).start();
    //while loop to receive all the requests and other messages
    while (true) {
        try (SctpChannel sctpChannelFromClient = sctpServerChannel.accept()) {
            mutex.acquire();
            byteBufferFromNeighbor.clear();
            String receiveMessage;
            MessageInfo messageInfoFromNeighbor = sctpChannelFromClient.receive(byteBufferFromNeighbor, null,
                    null);
            //System.out.println("Raw Message : " + messageInfoFromNeighbor);
            receiveMessage = byteToString(byteBufferFromNeighbor, messageInfoFromNeighbor);
            //write to file start
            writer.write("Received Message : " + receiveMessage);
            writer.write("\n");
            writer.flush();
            //write to file end
            System.out.println("Received Message : " + receiveMessage);
            if (receiveMessage.contains("Request")) {
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                int requestMade = Integer.parseInt(parseMessage[3] + parseMessage[1]);
                queue.add(requestMade);
                //Send reply messages to that process for entering CS
                lamportClock++;
                //vector clock construction
                int[] vector = VectorClass.increment(myProcessId);
                String vectorClockConstruction = "";
                for (int g = 0; g < vector.length; g++) {
                    if (g == 0) {
                        vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]);
                    } else {
                        vectorClockConstruction = vectorClockConstruction + "," + Integer.toString(vector[g]);
                    }
                }
                //
                for (int k = 0; k < numberOfProcesses; k++) {
                    if (k == Integer.parseInt(parseMessage[1])) {
                        try {
                            byteBufferToNeighbor.clear();
                            initializeChannels();
                            sctpChannel[k].connect(socketAddress[k]);
                            String sendMessage = "Reply from Process-" + myProcessId + "-"
                                    + Integer.toString(requestMade) + "-" + lamportClock + "-"
                                    + vectorClockConstruction;
                            System.out.println("Message sent is : " + sendMessage);
                            //write to file start
                            writer.write("Message sent is : " + sendMessage);
                            writer.write("\n");
                            writer.flush();
                            //write to file end
                            MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0);
                            byteBufferToNeighbor.put(sendMessage.getBytes());
                            byteBufferToNeighbor.flip();
                            sctpChannel[k].send(byteBufferToNeighbor, messageInfoToNeighbor);
                            totalMessageCount++;
                            sctpChannel[k].close();
                        } catch (IOException ex) {
                            Logger.getLogger(LamportBasicVersion.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            } else if (receiveMessage.contains("Reply")) {
                conditionArray[myProcessId] = 1;
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                conditionArray[Integer.parseInt(parseMessage[1])] = 1;
                int count = 0;
                for (int v = 0; v < numberOfProcesses; v++) {
                    if (conditionArray[v] == 1) {
                        count = count + 1;
                    }
                }
                if (count == numberOfProcesses) {
                    L1ConditionFlag = 1;
                    System.out.println("Inside L1");
                    blockingQueue.put("L1");
                    //Clearing condition array after receiving all REPLY
                    for (int z = 0; z < numberOfProcesses; z++) {
                        conditionArray[z] = 0;
                    }
                    if (L2ConditionFlag == 0 && outstandingRequest == 1) {
                        Integer[] queueArray = new Integer[queue.size()];
                        queue.toArray(queueArray);
                        Arrays.sort(queueArray);
                        if (queueArray[0] == currentRequestBeingServed) {
                            System.out.println("Inside L2");
                            L2ConditionFlag = 1;
                            blockingQueue.put("L2");
                        }
                    }
                }
            } else if (receiveMessage.contains("Release")) {
                int present = 0;
                int delete = 0;
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                if (queue.size() != 0) {
                    Integer[] queueArray = new Integer[queue.size()];
                    queue.toArray(queueArray);
                    Arrays.sort(queueArray);
                    for (int a = 0; a < queueArray.length; a++) {
                        if (queueArray[a] == Integer.parseInt(parseMessage[2])) {
                            present = 1;
                            delete = a;
                        }
                    }
                    if (present == 1) {
                        for (int s = 0; s <= delete; s++) {
                            queue.remove();
                        }
                    }
                }
                if (L2ConditionFlag == 0 && outstandingRequest == 1) {
                    if (queue.size() != 0) {
                        Integer[] queueArray1 = new Integer[queue.size()];
                        queue.toArray(queueArray1);
                        Arrays.sort(queueArray1);
                        if (currentRequestBeingServed == queueArray1[0]) {
                            L2ConditionFlag = 1;
                            System.out.println("Inside L2");
                            blockingQueue.put("L2");
                        }
                    }
                }
            } else if (receiveMessage.contains("Finish")) {
                String[] parseMessage = receiveMessage.split("-");
                lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1;
                //vector clock update
                String[] stringNumericalTimestamp = parseMessage[4].split(",");
                int[] numericalTimestamp = new int[stringNumericalTimestamp.length];
                for (int d = 0; d < stringNumericalTimestamp.length; d++) {
                    numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]);
                }
                VectorClass.update(myProcessId, numericalTimestamp);
                //
                finishFlagArray[Integer.parseInt(parseMessage[1])] = 1;
                int count = 0;
                for (int v = 0; v < numberOfProcesses; v++) {
                    if (finishFlagArray[v] == 1) {
                        count = count + 1;
                    }
                }
                if (count == numberOfProcesses) {
                    break;
                }
            }
            //logic for other messages
            //Print the queue to check
            System.out.println("********************************************************");
            for (Object item : queue) {
                System.out.print(item);
                System.out.print("\t");
            }
            System.out.println("********************************************************");
        }
        mutex.release();
    }
}