text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using CFUValidator.CommandLineOptions;
using CFUValidator.OutputDecorators;
using CFUValidator.Updates;
using CFUValidator.Validators;
using Moq;
using XenAdmin;
using XenAdmin.Alerts;
using XenAdmin.Core;
using XenAdminTests;
using XenAPI;

namespace CFUValidator
{
    public class CFUValidationException : Exception
    {
        public CFUValidationException(string message) : base(message){}
    }

    public class CFUValidator
    {
        private readonly MockObjectManager mom = new MockObjectManager();
        private readonly XmlRetrieverFactory xmlFactory = new XmlRetrieverFactory();
        private const string id = "id";
        private string XmlLocation { get; set; }
        private string ServerVersion { get; set; }
        private OptionUsage UrlOrFile { get; set; }
        private List<string> InstalledHotfixes { get; set; }
        private bool CheckHotfixContents{ get; set; }

        public CFUValidator(OptionUsage urlOrFile, string xmlLocation, string serverVersion,
                            List<string> installedHotfixes, bool checkHotfixContents)
        {
            if(urlOrFile != OptionUsage.File && urlOrFile != OptionUsage.Url)
                throw new ArgumentException("urlOrFile option should be either File or Url");

            mom.CreateNewConnection(id);
            ConnectionsManager.XenConnections.AddRange(mom.AllConnections);
            XmlLocation = xmlLocation;
            ServerVersion = serverVersion;
            InstalledHotfixes = installedHotfixes;
            UrlOrFile = urlOrFile;
            CheckHotfixContents = checkHotfixContents;
        }

        public void Run()
        {
            List<XenServerPatch> xenServerPatches;
            List<XenServerVersion> xenServerVersions;
            List<XenCenterVersion> xenCenterVersions;

            Status = "Getting check for updates XML from " + XmlLocation + "...";
            ReadCheckForUpdatesXML(out xenServerPatches, out xenServerVersions, out xenCenterVersions);

            List<string> versionToCheck = GetVersionToCheck(xenServerVersions);

            foreach (string ver in versionToCheck)
            {
                ServerVersion = ver;
                RunTestsForGivenServerVersion(xenServerVersions, xenServerPatches, xenCenterVersions);
            }

        }

        private List<string> GetVersionToCheck(List<XenServerVersion> xenServerVersions)
        {
            if(ServerVersion == CFUCommandLineOptionManager.AllVersions)
                return xenServerVersions.ConvertAll(i => i.Version.ToString()).Distinct().ToList();

            return new List<string>{ServerVersion};
        }

        private void RunTestsForGivenServerVersion(List<XenServerVersion> xenServerVersions,
                                                   List<XenServerPatch> xenServerPatches,
                                                   List<XenCenterVersion> xenCenterVersions)
        {
            CheckProvidedVersionNumber(xenServerVersions);

            Status = String.Format("Generating server {0} mock-ups...", ServerVersion);
            SetupMocks(xenServerPatches, xenServerVersions);

            Status = "Determining XenCenter update required...";
            var xcupdateAlert = XenAdmin.Core.Updates.NewXenCenterUpdateAlert(xenCenterVersions, new Version(ServerVersion));

            Status = "Determining XenServer update required...";
            var updateAlert = XenAdmin.Core.Updates.NewXenServerVersionAlert(xenServerVersions);

            Status = "Determining patches required...";
            var patchAlerts = XenAdmin.Core.Updates.NewXenServerPatchAlerts(xenServerVersions, xenServerPatches).Where(alert => !alert.CanIgnore).ToList();

            //Build patch checks list
            List<AlertFeatureValidator> validators = new List<AlertFeatureValidator>
                                                         {
                                                             new CorePatchDetailsValidator(patchAlerts),
                                                             new PatchURLValidator(patchAlerts),
                                                             new ZipContentsValidator(patchAlerts)
                                                         };

            Status = "Running patch check(s), this may take some time...";
            RunValidators(validators);

            Status = "Generating summary...";
            GeneratePatchSummary(patchAlerts, validators, updateAlert, xcupdateAlert);
        }

        private void CheckProvidedVersionNumber(List<XenServerVersion> xenServerVersions)
        {
            if (!xenServerVersions.Any(v => v.Version.ToString() == ServerVersion))
            {
                StringBuilder sb = new StringBuilder("\nAvailable versions are:\n");
                xenServerVersions.ConvertAll(i=>i.Version.ToString()).Distinct().ToList().ForEach(v=>sb.AppendLine(v));
                throw new CFUValidationException("Could not find the version in the check for updates file: " + ServerVersion + sb);
            }
        }

        public string Output { get; private set; }

        #region Status event code
        public delegate void StatusChangedHandler(object sender, EventArgs e);

        public event StatusChangedHandler StatusChanged;

        protected virtual void OnStatusChanged()
        {
            if (StatusChanged != null)
                StatusChanged(Status, EventArgs.Empty);
        }

        private string status;
        private string Status
        {
            get { return status; }
            set
            {
                status = value;
                OnStatusChanged();
            }
        }
        #endregion

        private void RunValidators(List<AlertFeatureValidator> validators)
        {
            int count = 1;
            foreach (AlertFeatureValidator validator in validators)
            {
                if (validator is ZipContentsValidator && !CheckHotfixContents)
                    continue;

                Status = count++ + ". " + validator.Description + "...";

                validator.StatusChanged += validator_StatusChanged;
                validator.Validate();
                validator.StatusChanged -= validator_StatusChanged;
            }
            Status = "Validator checks complete";
        }

        private void validator_StatusChanged(object sender, EventArgs e)
        {
            Status = sender as string;
        }

        private void GeneratePatchSummary(List<XenServerPatchAlert> alerts, List<AlertFeatureValidator> validators,
                                          XenServerVersionAlert updateAlert, XenCenterUpdateAlert xcupdateAlert)
        {
            OuputComponent oc = new OutputTextOuputComponent(XmlLocation, ServerVersion);
            XenCenterUpdateDecorator xcud = new XenCenterUpdateDecorator(oc, xcupdateAlert);
            XenServerUpdateDecorator xsud = new XenServerUpdateDecorator(xcud, updateAlert);
            PatchAlertDecorator pad = new PatchAlertDecorator(xsud, alerts);
            AlertFeatureValidatorDecorator afdCoreFields = new AlertFeatureValidatorDecorator(pad,
                                                                                validators.First(v => v is CorePatchDetailsValidator),
                                                                                "Core fields in patch checks:");
            AlertFeatureValidatorDecorator afdPatchUrl = new AlertFeatureValidatorDecorator(afdCoreFields,
                                                                                validators.First(v => v is PatchURLValidator),
                                                                                "Required patch URL checks:");
            AlertFeatureValidatorDecorator afdZipContents = new AlertFeatureValidatorDecorator(afdPatchUrl,
                                                                                validators.First(v => v is ZipContentsValidator),
                                                                                "Required patch zip content checks:");

            if(CheckHotfixContents)
                Output = afdZipContents.Generate().Insert(0, Output).ToString();
            else
                Output = afdPatchUrl.Generate().Insert(0, Output).ToString();

        }

        private void ReadCheckForUpdatesXML(out List<XenServerPatch> patches, out List<XenServerVersion> versions, out List<XenCenterVersion> xcVersions)
        {
            ICheckForUpdatesXMLSource checkForUpdates = xmlFactory.GetAction(UrlOrFile, XmlLocation);
            checkForUpdates.RunAsync();

            ConsoleSpinner spinner = new ConsoleSpinner();
            while(!checkForUpdates.IsCompleted)
            {
                spinner.Turn(checkForUpdates.PercentComplete);
            }

            if (checkForUpdates.ErrorRaised != null)
                throw checkForUpdates.ErrorRaised;

            patches = checkForUpdates.XenServerPatches;
            versions = checkForUpdates.XenServerVersions;
            xcVersions = checkForUpdates.XenCenterVersions;
        }

        private void SetupMocks(List<XenServerPatch> xenServerPatches, List<XenServerVersion> xenServerVersions)
        {
            Mock<Host>  master = mom.NewXenObject<Host>(id);
            Mock<Pool> pool = mom.NewXenObject<Pool>(id);
            XenRef<Host> masterRef = new XenRef<Host>("ref");
            pool.Setup(p => p.master).Returns(masterRef);
            mom.MockCacheFor(id).Setup(c => c.Resolve(It.IsAny<XenRef<Pool>>())).Returns(pool.Object);
            mom.MockConnectionFor(id).Setup(c => c.Resolve(masterRef)).Returns(master.Object);
            master.Setup(h => h.software_version).Returns(new Dictionary<string, string>());
            master.Setup(h => h.ProductVersion).Returns(ServerVersion);
            master.Setup(h => h.AppliedPatches()).Returns(GenerateMockPoolPatches(xenServerPatches));

            //Currently build number will be referenced first so if it's present hook it up
            string buildNumber = xenServerVersions.First(v => v.Version.ToString() == ServerVersion).BuildNumber;
            master.Setup(h=>h.BuildNumberRaw).Returns(buildNumber);
        }

        private List<Pool_patch> GenerateMockPoolPatches(List<XenServerPatch> xenServerPatches)
        {
            List<Pool_patch> patches = new List<Pool_patch>();

            foreach (string installedHotfix in InstalledHotfixes)
            {
                string hotfix = installedHotfix;
                XenServerPatch match = xenServerPatches.Find(m => m.Name.Contains(hotfix));

                if(match == null)
                    throw new CFUValidationException("No patch could be found in the XML matching " + hotfix);

                Mock<Pool_patch> pp = mom.NewXenObject<Pool_patch>(id);
                pp.Setup(p => p.uuid).Returns(match.Uuid);
                patches.Add(pp.Object);
            }

            return patches;
        }

    }
}


text:
<TITLE>org.krysalis.barcode4j.output.svg Package</TITLE>

This package contains classes for barcode output to bitmap images.

redpajama_set_name: RedPajamaGithub


text:
<mat-card>
  <mat-card-header>
    <mat-card-title>
      <mat-icon (click)="toggleCollapse()">{{collapseIcon}}</mat-icon>
      {{testName}}
    </mat-card-title>
    <mat-card-subtitle [ngClass]="resultText.toLowerCase()">{{resultText}}</mat-card-subtitle>
  </mat-card-header>
  <mat-card-content *ngIf="!collapse">

Test image

Diff image

Reference image

  </mat-card-content>
  <mat-card-actions>
    <mat-button-toggle-group [(ngModel)]="mode" class="mode-section">
      <mat-button-toggle value="diff">
        Diff
      </mat-button-toggle>
      <mat-button-toggle value="flip">
        Flip
      </mat-button-toggle>
      <mat-button-toggle value="side">
        Side by side
      </mat-button-toggle>
    </mat-button-toggle-group>
    <button mat-button color="primary" (click)="flip()" *ngIf="mode === 'flip'">Flip</button>
  </mat-card-actions>
</mat-card>


text:
#ifndef _SONARSENSOR_HH_
#define _SONARSENSOR_HH_

#include <string>
#include <list>

#include "gazebo/math/Angle.hh"
#include "gazebo/math/Pose.hh"
#include "gazebo/transport/TransportTypes.hh"
#include "gazebo/sensors/Sensor.hh"

namespace gazebo
{
  /// \ingroup gazebo_sensors
  /// \brief Sensors namespace
  namespace sensors
  {
    /// \addtogroup gazebo_sensors
    /// \{

    /// \class SonarSensor SonarSensor.hh sensors/sensors.hh
    /// \brief Sensor with sonar cone.
    ///
    /// This sensor uses a cone .
    class SonarSensor: public Sensor
    {
      /// \brief Constructor
      public: SonarSensor();

      /// \brief Destructor
      public: virtual ~SonarSensor();

      // Documentation inherited
      public: virtual void Load(const std::string &_worldName);

      // Documentation inherited
      public: virtual void Init();

      // Documentation inherited
      protected: virtual void UpdateImpl(bool _force);

      // Documentation inherited
      protected: virtual void Fini();

      // Documentation inherited
      public: virtual std::string GetTopic() const;

      /// \brief Get the minimum range of the sonar
      /// \return The sonar's minimum range.
      public: double GetRangeMin() const;

      /// \brief Get the minimum range of the sonar.
      /// \return The sonar's maximum range.
      public: double GetRangeMax() const;

      /// \brief Get the radius of the sonar cone at maximum range.
      /// \return The radisu of the sonar cone at max range.
      public: double GetRadius() const;

      /// \brief Get detected range for a sonar.
      ///         Warning: If you are accessing all the ray data in a loop
      ///         it's possible that the Ray will update in the middle of
      ///         your access loop. This means some data will come from one
      ///         scan, and some from another scan. You can solve this
      ///         problem by using SetActive(false) <your accessor loop>
      ///         SetActive(true).
      /// \return Returns DBL_MAX for no detection.
      public: double GetRange();

      // Documentation inherited
      public: virtual bool IsActive();

      /// \brief Connect a to the new update signal.
      /// \param[in] _subscriber Callback function.
      /// \return The connection, which must be kept in scope.
      public: template<typename T>
              event::ConnectionPtr ConnectUpdate(T _subscriber)
              {return update.Connect(_subscriber);}

      /// \brief Disconnect from the update signal.
      /// \param[in] _conn Connection to remove.
      public: void DisconnectUpdate(event::ConnectionPtr &_conn)
              {update.Disconnect(_conn);}

      /// \brief Callback for contact messages from the physics engine.
      private: void OnContacts(ConstContactsPtr &_msg);

      /// \brief Collison object that holds the sonarShape.
      private: physics::CollisionPtr sonarCollision;

      /// \brief Shape used to generate contact information.
      private: physics::MeshShapePtr sonarShape;

      /// \brief Parent entity of this sensor
      private: physics::EntityPtr parentEntity;

      /// \brief Subscription to contact messages from the physics engine
      private: transport::SubscriberPtr contactSub;

      /// \brief Publishes the sonsarMsg.
      private: transport::PublisherPtr sonarPub;

      /// \brief Store current sonar info
      private: msgs::SonarStamped sonarMsg;

      /// \brief Mutex used to protect reading/writing the sonar message.
      private: boost::mutex mutex;

      /// \brief Contact messages list type
      typedef std::list<boost::shared_ptr<msgs::Contacts const> > ContactMsgs_L;

      /// \brief List of received contacts from the sonar collision shape.
      private: ContactMsgs_L incomingContacts;

      /// \brief Pose of the sonar shape's midpoint.
      private: math::Pose sonarMidPose;

      /// \brief Minimum range
      private: double rangeMin;

      /// \brief Maximum range
      private: double rangeMax;

      /// \brief Radius of the sonar cone at maximum range.
      private: double radius;

      /// \brief Update event.
      protected: event::EventT<void(msgs::SonarStamped)> update;
    };
    /// \}
  }
}
#endif


text:
<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@drawable/play_btn"
        android:state_focused="true"/>
    <item
        android:drawable="@drawable/play_btn_clicked"
        android:state_pressed="true"/>
    <item
        android:drawable="@drawable/play_btn"/>
</selector>


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.actions;

/**
 * An TestExecException that is related to the failure of a TestAction.
 */
public final class TestExecException extends ExecException {

  public TestExecException(String message) {
    super(message);
  }

  @Override
  public ActionExecutionException toActionExecutionException(String messagePrefix,
      boolean verboseFailures, Action action) {
    String message = messagePrefix + " failed";
    return new ActionExecutionException(
        message + ": " + getMessage(), this, action, isCatastrophic());
  }
}


text:
package com.sun.tools.doclets.formats.html;

import java.io.*;
import java.util.*;

import com.sun.javadoc.*;
import com.sun.tools.doclets.formats.html.markup.*;
import com.sun.tools.doclets.internal.toolkit.*;
import com.sun.tools.doclets.internal.toolkit.util.*;

/**
 * Writes nested class documentation in HTML format.
 *
 * @author Robert Field
 * @author Atul M Dambalkar
 * @author Jamie Ho (rewrite)
 * @author Bhavesh Patel (Modified)
 */
public class NestedClassWriterImpl extends AbstractMemberWriter
    implements MemberSummaryWriter {

    public NestedClassWriterImpl(SubWriterHolderWriter writer,
            ClassDoc classdoc) {
        super(writer, classdoc);
    }

    public NestedClassWriterImpl(SubWriterHolderWriter writer) {
        super(writer);
    }

    /**
     * {@inheritDoc}
     */
    public Content getMemberSummaryHeader(ClassDoc classDoc,
            Content memberSummaryTree) {
        memberSummaryTree.addContent(HtmlConstants.START_OF_NESTED_CLASS_SUMMARY);
        Content memberTree = writer.getMemberTreeHeader();
        writer.addSummaryHeader(this, classDoc, memberTree);
        return memberTree;
    }

    /**
     * Close the writer.
     */
    public void close() throws IOException {
        writer.close();
    }

    public int getMemberKind() {
        return VisibleMemberMap.INNERCLASSES;
    }

    /**
     * {@inheritDoc}
     */
    public void addSummaryLabel(Content memberTree) {
        Content label = HtmlTree.HEADING(HtmlConstants.SUMMARY_HEADING,
                writer.getResource("doclet.Nested_Class_Summary"));
        memberTree.addContent(label);
    }

    /**
     * {@inheritDoc}
     */
    public String getTableSummary() {
        return configuration().getText("doclet.Member_Table_Summary",
                configuration().getText("doclet.Nested_Class_Summary"),
                configuration().getText("doclet.nested_classes"));
    }

    /**
     * {@inheritDoc}
     */
    public String getCaption() {
        return configuration().getText("doclet.Nested_Classes");
    }

    /**
     * {@inheritDoc}
     */
    public String[] getSummaryTableHeader(ProgramElementDoc member) {
        String[] header;
        if (member.isInterface()) {
            header = new String[] {
                writer.getModifierTypeHeader(),
                configuration().getText("doclet.0_and_1",
                        configuration().getText("doclet.Interface"),
                        configuration().getText("doclet.Description"))
            };
        }
        else {
            header = new String[] {
                writer.getModifierTypeHeader(),
                configuration().getText("doclet.0_and_1",
                        configuration().getText("doclet.Class"),
                        configuration().getText("doclet.Description"))
            };
        }
        return header;
    }

    /**
     * {@inheritDoc}
     */
    public void addSummaryAnchor(ClassDoc cd, Content memberTree) {
        memberTree.addContent(writer.getMarkerAnchor("nested_class_summary"));
    }

    /**
     * {@inheritDoc}
     */
    public void addInheritedSummaryAnchor(ClassDoc cd, Content inheritedTree) {
        inheritedTree.addContent(writer.getMarkerAnchor(
                "nested_classes_inherited_from_class_" + cd.qualifiedName()));
    }

    /**
     * {@inheritDoc}
     */
    public void addInheritedSummaryLabel(ClassDoc cd, Content inheritedTree) {
        Content classLink = new RawHtml(writer.getPreQualifiedClassLink(
                LinkInfoImpl.CONTEXT_MEMBER, cd, false));
        Content label = new StringContent(cd.isInterface() ?
            configuration().getText("doclet.Nested_Classes_Interface_Inherited_From_Interface") :
            configuration().getText("doclet.Nested_Classes_Interfaces_Inherited_From_Class"));
        Content labelHeading = HtmlTree.HEADING(HtmlConstants.INHERITED_SUMMARY_HEADING,
                label);
        labelHeading.addContent(writer.getSpace());
        labelHeading.addContent(classLink);
        inheritedTree.addContent(labelHeading);
    }

    /**
     * {@inheritDoc}
     */
    protected void addSummaryLink(int context, ClassDoc cd, ProgramElementDoc member,
            Content tdSummary) {
        Content strong = HtmlTree.STRONG(new RawHtml(
                writer.getLink(new LinkInfoImpl(context, (ClassDoc)member, false))));
        Content code = HtmlTree.CODE(strong);
        tdSummary.addContent(code);
    }

    /**
     * {@inheritDoc}
     */
    protected void addInheritedSummaryLink(ClassDoc cd,
            ProgramElementDoc member, Content linksTree) {
        linksTree.addContent(new RawHtml(
                writer.getLink(new LinkInfoImpl(LinkInfoImpl.CONTEXT_MEMBER,
                (ClassDoc)member, false))));
    }

    /**
     * {@inheritDoc}
     */
    protected void addSummaryType(ProgramElementDoc member,
            Content tdSummaryType) {
        ClassDoc cd = (ClassDoc)member;
        addModifierAndType(cd, null, tdSummaryType);
    }

    /**
     * {@inheritDoc}
     */
    protected Content getDeprecatedLink(ProgramElementDoc member) {
        return writer.getQualifiedClassLink(LinkInfoImpl.CONTEXT_MEMBER,
                (ClassDoc)member);
    }

    /**
     * {@inheritDoc}
     */
    protected Content getNavSummaryLink(ClassDoc cd, boolean link) {
        if (link) {
            return writer.getHyperLink("", (cd == null) ? "nested_class_summary":
                "nested_classes_inherited_from_class_" +
                cd.qualifiedName(),
                writer.getResource("doclet.navNested"));
        } else {
            return writer.getResource("doclet.navNested");
        }
    }

    /**
     * {@inheritDoc}
     */
    protected void addNavDetailLink(boolean link, Content liNav) {
    }
}


text:
import { registerMigration } from './migrationUtils';
import { Posts } from '../../lib/collections/posts'
import * as _ from 'underscore';

registerMigration({
  name: "migrateLinkPosts",
  dateWritten: "2019-04-24",
  idempotent: true,
  action: async () => {
    // Get posts which were linkposts in legacy, but aren't linkposts now.
    // There are only ~800 such posts, so no batching is necessary.
    const unmigratedLinkposts = await Posts.find({
      // In old-LW/Reddit ontology, there are two fundamental types of post:
      // link-posts and self-posts. This is represented by the is_self field,
      // which, after making its way through the old DB schema and our import
      // script, is either present and "t" (a self-post), or missing (a
      // link-post).
      "legacyData.is_self": { "$exists": false },

      // Also make sure it actually has a legacy URL. This excludes non-legacy
      // posts.
      "legacyData.url": { "$exists": true, },

      // And it isn't already a linkpost, ie, this script hasn't already
      // migrated it.
      url: {$exists:false}
    }).fetch();

    // eslint-disable-next-line no-console
    console.log(`Found ${unmigratedLinkposts.length} old linkposts to migrate`);

    const updates = _.map(unmigratedLinkposts, post => ({
      updateOne: {
        filter: { _id: post._id },
        update: {
          $set: {
            url: (post as any).legacyData.url,
          }
        }
      }
    }));

    if (updates.length > 0) {
      Posts.rawCollection().bulkWrite(updates, { ordered: false });
    }
  }
});


text:
'use strict';

var InfiniteScroll = angular.module('converge.modules.infinitescroll', []);

var pageBottomCallbacks = [];

var $InfiniteScroll = {
    addPageBottomCallback: function (callback) {
        pageBottomCallbacks.push(callback);

        // TODO: Test this function. I don't remember JavaScript well enough to
        //       know whether `cb != callback` works for a single instance, or
        //       for all instances (originating from the same code).
        // Consideration: Have the callback remove only this specific instance,
        //                or have it remove *all* instances?
        return function () {
            pageBottomCallbacks = _.filter(pageBottomCallbacks, function (cb) {
                return cb != callback;
            });
        };
    }
};

// Already instantiated service
InfiniteScroll.value('$InfiniteScroll', $InfiniteScroll);

$(window).scroll(_.debounce(function (e) {
    // Yes, always re-calc these values
    // The user may have resized windows, we may have added items, etc.
    var $window = $(window);

    var visibleHeight = $window.innerHeight();
    var docHeight = $(document).innerHeight();

    var currentScrollPosition = $window.scrollTop();
    var scrollHeight = docHeight - visibleHeight;

    if ((scrollHeight - currentScrollPosition) < 100) {
        for (var i = pageBottomCallbacks.length - 1; i >= 0; i--) {
            pageBottomCallbacks[i]();
        };
    }
}, 300));


text:
#ifndef _amici_model_jakstat_adjoint_h
#define _amici_model_jakstat_adjoint_h
/* Generated by amiwrap (R2017b) fee0d5a069aba864a92ded7da50ae68ea7ea43cc */
#include <cmath>
#include <memory>
#include "amici/defines.h"
#include <sunmatrix/sunmatrix_sparse.h> //SUNMatrixContent_Sparse definition
#include "amici/solver_cvodes.h"
#include "amici/model_ode.h"

namespace amici {

class Solver;

namespace model_model_jakstat_adjoint{

extern void JSparse_model_jakstat_adjoint(SUNMatrixContent_Sparse JSparse, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx);
extern void Jy_model_jakstat_adjoint(double *nllh, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my);
extern void dJydsigma_model_jakstat_adjoint(double *dJydsigma, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my);
extern void dJydy_model_jakstat_adjoint(double *dJydy, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my);
extern void dsigmaydp_model_jakstat_adjoint(double *dsigmaydp, const realtype t, const realtype *p, const realtype *k, const realtype *y, const int ip);
extern void dwdp_model_jakstat_adjoint(realtype *dwdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl, const realtype *stcl);
extern void dwdx_model_jakstat_adjoint(realtype *dwdx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl);
extern void dxdotdp_model_jakstat_adjoint(realtype *dxdotdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *w, const realtype *dwdp);
extern void dydp_model_jakstat_adjoint(double *dydp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *w, const realtype *dwdp);
extern void dydx_model_jakstat_adjoint(double *dydx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx);
extern void sigmay_model_jakstat_adjoint(double *sigmay, const realtype t, const realtype *p, const realtype *k, const realtype *y);
extern void sx0_model_jakstat_adjoint(realtype *sx0, const realtype t,const realtype *x0, const realtype *p, const realtype *k, const int ip);
extern void w_model_jakstat_adjoint(realtype *w, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *tcl);
extern void x0_model_jakstat_adjoint(realtype *x0, const realtype t, const realtype *p, const realtype *k);
extern void xdot_model_jakstat_adjoint(realtype *xdot, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w);
extern void y_model_jakstat_adjoint(double *y, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w);

class Model_model_jakstat_adjoint : public amici::Model_ODE {
public:
    Model_model_jakstat_adjoint()
        : amici::Model_ODE(
              amici::ModelDimensions(
                  9,
                  9,
                  9,
                  9,
                  0,
                  17,
                  2,
                  3,
                  3,
                  0,
                  0,
                  0,
                  1,
                  2,
                  1,
                  5,
                  0,
                  0,
                  {},
                  0,
                  0,
                  0,
                  18,
                  8,
                  1
              ),
              amici::SimulationParameters(
                  std::vector<realtype>(2, 1.0),
                  std::vector<realtype>(17, 1.0)
              ),
              amici::SecondOrderMode::none,
              std::vector<realtype>{0, 0, 0, 0, 0, 0, 0, 0, 0},
              std::vector<int>{})
              {};

    amici::Model* clone() const override { return new Model_model_jakstat_adjoint(*this); };

    std::string getAmiciCommit() const override { return "fee0d5a069aba864a92ded7da50ae68ea7ea43cc"; };

    void fJSparse(SUNMatrixContent_Sparse JSparse, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx) override {
        JSparse_model_jakstat_adjoint(JSparse, t, x, p, k, h, w, dwdx);
    }

    void fJrz(double *nllh, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz) override {
    }

    void fJy(double *nllh, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my) override {
        Jy_model_jakstat_adjoint(nllh, iy, p, k, y, sigmay, my);
    }

    void fJz(double *nllh, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz) override {
    }

    void fdJrzdsigma(double *dJrzdsigma, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz) override {
    }

    void fdJrzdz(double *dJrzdz, const int iz, const realtype *p, const realtype *k, const double *rz, const double *sigmaz) override {
    }

    void fdJydsigma(double *dJydsigma, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my) override {
        dJydsigma_model_jakstat_adjoint(dJydsigma, iy, p, k, y, sigmay, my);
    }

    void fdJydy(double *dJydy, const int iy, const realtype *p, const realtype *k, const double *y, const double *sigmay, const double *my) override {
        dJydy_model_jakstat_adjoint(dJydy, iy, p, k, y, sigmay, my);
    }

    void fdJzdsigma(double *dJzdsigma, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz) override {
    }

    void fdJzdz(double *dJzdz, const int iz, const realtype *p, const realtype *k, const double *z, const double *sigmaz, const double *mz) override {
    }

    void fdeltaqB(double *deltaqB, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *xB) override {
    }

    void fdeltasx(double *deltasx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const int ip, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *sx, const realtype *stau, const realtype *tcl) override {
    }

    void fdeltax(double *deltax, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ie, const realtype *xdot, const realtype *xdot_old) override {
    }

    void fdeltaxB(double *deltaxB, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ie, const realtype *xdot, const realtype *xdot_old, const realtype *xB) override {
    }

    void fdrzdp(double *drzdp, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip) override {
    }

    void fdrzdx(double *drzdx, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
    }

    void fdsigmaydp(double *dsigmaydp, const realtype t, const realtype *p, const realtype *k, const realtype *y, const int ip) override {
        dsigmaydp_model_jakstat_adjoint(dsigmaydp, t, p, k, y, ip);
    }

    void fdsigmazdp(double *dsigmazdp, const realtype t, const realtype *p, const realtype *k, const int ip) override {
    }

    void fdwdp(realtype *dwdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl, const realtype *stcl) override {
        dwdp_model_jakstat_adjoint(dwdp, t, x, p, k, h, w, tcl, stcl);
    }

    void fdwdx(realtype *dwdx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *tcl) override {
        dwdx_model_jakstat_adjoint(dwdx, t, x, p, k, h, w, tcl);
    }

    void fdxdotdp(realtype *dxdotdp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *w, const realtype *dwdp) override {
        dxdotdp_model_jakstat_adjoint(dxdotdp, t, x, p, k, h, ip, w, dwdp);
    }

    void fdydp(double *dydp, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip, const realtype *w, const realtype *dwdp) override {
        dydp_model_jakstat_adjoint(dydp, t, x, p, k, h, ip, w, dwdp);
    }

    void fdydx(double *dydx, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w, const realtype *dwdx) override {
        dydx_model_jakstat_adjoint(dydx, t, x, p, k, h, w, dwdx);
    }

    void fdzdp(double *dzdp, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const int ip) override {
    }

    void fdzdx(double *dzdx, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
    }

    void froot(realtype *root, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *tcl) override {
    }

    void frz(double *rz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
    }

    void fsigmay(double *sigmay, const realtype t, const realtype *p, const realtype *k, const realtype *y) override {
        sigmay_model_jakstat_adjoint(sigmay, t, p, k, y);
    }

    void fsigmaz(double *sigmaz, const realtype t, const realtype *p, const realtype *k) override {
    }

    void fsrz(double *srz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip) override {
    }

    void fstau(double *stau, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *tcl, const realtype *sx, const int ip, const int ie) override {
    }

    void fsx0(realtype *sx0, const realtype t,const realtype *x0, const realtype *p, const realtype *k, const int ip) override {
        sx0_model_jakstat_adjoint(sx0, t, x0, p, k, ip);
    }

    void fsz(double *sz, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *sx, const int ip) override {
    }

    void fw(realtype *w, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *tcl) override {
        w_model_jakstat_adjoint(w, t, x, p, k, h, tcl);
    }

    void fx0(realtype *x0, const realtype t, const realtype *p, const realtype *k) override {
        x0_model_jakstat_adjoint(x0, t, p, k);
    }

    void fxdot(realtype *xdot, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w) override {
        xdot_model_jakstat_adjoint(xdot, t, x, p, k, h, w);
    }

    void fy(double *y, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h, const realtype *w) override {
        y_model_jakstat_adjoint(y, t, x, p, k, h, w);
    }

    void fz(double *z, const int ie, const realtype t, const realtype *x, const realtype *p, const realtype *k, const realtype *h) override {
    }

};

} // namespace model_model_jakstat_adjoint

} // namespace amici

#endif /* _amici_model_jakstat_adjoint_h */


text:
package edu.utah.ece.async.ibiosim.analysis;

import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.prefs.Preferences;

import javax.xml.stream.XMLStreamException;

import org.sbml.jsbml.Model;

import edu.utah.ece.async.ibiosim.analysis.fba.FluxBalanceAnalysis;
import edu.utah.ece.async.ibiosim.analysis.markov.BuildStateGraphThread;
import edu.utah.ece.async.ibiosim.analysis.markov.PerformSteadyStateMarkovAnalysisThread;
import edu.utah.ece.async.ibiosim.analysis.markov.PerformTransientMarkovAnalysisThread;
import edu.utah.ece.async.ibiosim.analysis.markov.StateGraph;
import edu.utah.ece.async.ibiosim.analysis.markov.StateGraph.Property;
import edu.utah.ece.async.ibiosim.analysis.properties.AdvancedProperties;
import edu.utah.ece.async.ibiosim.analysis.properties.AnalysisProperties;
import edu.utah.ece.async.ibiosim.analysis.simulation.DynamicSimulation;
import edu.utah.ece.async.ibiosim.analysis.simulation.DynamicSimulation.SimulationType;
import edu.utah.ece.async.ibiosim.analysis.simulation.flattened.Simulator;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.parser.BioModel;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.util.SBMLutilities;
import edu.utah.ece.async.ibiosim.dataModels.biomodel.util.Utility;
import edu.utah.ece.async.ibiosim.dataModels.util.Executables;
import edu.utah.ece.async.ibiosim.dataModels.util.Message;
import edu.utah.ece.async.ibiosim.dataModels.util.MutableString;
import edu.utah.ece.async.ibiosim.dataModels.util.exceptions.BioSimException;
import edu.utah.ece.async.ibiosim.dataModels.util.observe.BioObservable;
import edu.utah.ece.async.ibiosim.dataModels.util.observe.CoreObservable;
import edu.utah.ece.async.lema.verification.lpn.Abstraction;
import edu.utah.ece.async.lema.verification.lpn.LPN;
import edu.utah.ece.async.lema.verification.lpn.Translator;

/**
 * Run class is used to execute an analysis method.
 *
 * @author Leandro Watanabe
 * @author Chris Myers
 * @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
 * @version $Rev$
 * @version %I%
 */
public class Run extends CoreObservable implements ActionListener {

  private final AnalysisProperties properties;
  private FileWriter logFile;

  private final Message message = new Message();
  private final Runtime exec = Runtime.getRuntime();

  private Process reb2sac;
  private StateGraph sg;
  private DynamicSimulation dynSim;

  private File work;

  /**
   * The Run class is a wrapper for all of the analysis methods. The run configurations are
   * specified by an {@link AnalysisProperties}, which describes the type of analysis to run
   * and the simulation parameters.
   *
   * @param properties
   *          - the analysis properties object that stores the simulation parameters.
   */
  public Run(AnalysisProperties properties) {
    this.properties = properties;
  }

  /**
   * When Run is executed, it loads up the parameters from {@link AnalysisProperties} and performs
   * analysis.
   *
   * @return error code. Value 0 indicates a success run.
   *
   * @throws IOException
   *           - io problem
   * @throws XMLStreamException
   *           - problem with the XML processing.
   * @throws InterruptedException
   *           - thred problem
   * @throws BioSimException
   *           - something went wrong with the analysis
   */
  public int execute(String outDir, String filename) throws IOException, XMLStreamException, InterruptedException, BioSimException {
    Runtime exec = Runtime.getRuntime();
    int exitValue = 255;
    long time1, time2;

    work = new File(outDir);
    new FileWriter(new File(outDir + File.separator + "running")).close();

    if (properties.isNary() && properties.isGui() && (properties.isSsa() || properties.isXhtml() || properties.isDot())) {
      exitValue = executeNary(filename);
    }

    if (properties.isNary() && !properties.isGui() && !properties.getSim().contains("markov-chain-analysis") && properties.getSimulationProperties().getRun() == 1) {
      message.setLog("Executing:\n" + Executables.reb2sacExecutable + " --target.encoding=nary-level " + "\"" + filename + "\"");
      this.notifyObservers(message);
      time1 = System.nanoTime();
      reb2sac = exec.exec(Executables.reb2sacExecutable + " --target.encoding=nary-level " + "\"" + filename + "\"", Executables.envp, work);
    } else if (properties.isFba()) {
      time1 = System.nanoTime();
      exitValue = executeFBA(filename);
    } else if (properties.isSbml()) {
      time1 = System.nanoTime();
      exitValue = executeSBML(filename);
    } else if (properties.isDot()) {
      time1 = System.nanoTime();
      exitValue = executeDot(filename);
    } else if (properties.isXhtml()) {
      time1 = System.nanoTime();
      exitValue = executeXhtml(filename);
    } else if (properties.getSim().equals("atacs")) {
      time1 = System.nanoTime();
      exitValue = executeAtacs();
    } else if (properties.getSim().equals("prism")) {
      time1 = System.nanoTime();
      exitValue = executePrism(filename);
    } else if (properties.getSim().contains("markov-chain-analysis") || properties.getSim().equals("reachability-analysis")) {
      time1 = System.nanoTime();
      exitValue = executeMarkov(filename);
    } else {
      time1 = System.nanoTime();
      exitValue = executeSimulation(filename);

    }

    // updateReb2SacProgress();
    time2 = System.nanoTime();
    displayError(exitValue);

    String time = SBMLutilities.createTimeString(time1, time2);

    message.setLog("Total Simulation Time: " + time);
    this.notifyObservers(message);
    return exitValue;
  }

  private void displayError(int exitValue) {
    if (exitValue == 143) {
      message.setDialog("Canceled Simulation", "The simulation was" + " canceled by the user.");
      this.notifyObservers(message);
    } else if (exitValue == 139) {
      message.setErrorDialog("Not An SBML File", "The selected model is not a valid sbml file." + "\nYou must select an sbml file.");
      this.notifyObservers(message);
    } else if (exitValue != 0) {
      message.setErrorDialog("Error In Execution!", "Bad Return Value!\n" + "The reb2sac program returned " + exitValue + " as an exit value.");
      this.notifyObservers(message);
    }
  }

  private int executeFBA(String filename) throws XMLStreamException, IOException, BioSimException {
    int exitValue = 255;

    FluxBalanceAnalysis fluxBalanceAnalysis = new FluxBalanceAnalysis(properties.getDirectory() + File.separator, properties.getModelFile(), properties.getSimulationProperties().getAbsError());
    this.addObservable(fluxBalanceAnalysis);
    exitValue = fluxBalanceAnalysis.PerformFluxBalanceAnalysis();

    if (exitValue == 1) {
      message.setErrorDialog("Error", "Flux balance analysis did not converge.");
    } else if (exitValue == 2) {
      message.setErrorDialog("Error", "Flux balance analysis failed.");
    } else if (exitValue == -1) {
      message.setErrorDialog("Error", "No flux balance constraints.");
    } else if (exitValue == -2) {
      message.setErrorDialog("Error", "Initial point must be strictly feasible.");
    } else if (exitValue == -3) {
      message.setErrorDialog("Error", "The FBA problem is infeasible.");
    } else if (exitValue == -4) {
      message.setErrorDialog("Error", "The FBA problem has a singular KKT system.");
    } else if (exitValue == -5) {
      message.setErrorDialog("Error", "The matrix must have at least one row.");
    } else if (exitValue == -6) {
      message.setErrorDialog("Error", "The matrix is singular.");
    } else if (exitValue == -7) {
      message.setErrorDialog("Error", "Equalities matrix A must have full rank.");
    } else if (exitValue == -8) {
      message.setErrorDialog("Error", "Miscellaneous FBA failure (see console for details).");
    } else if (exitValue == -9) {
      message.setErrorDialog("Error", "Reaction in flux objective does not have a flux bound.");
    } else if (exitValue == -10) {
      message.setErrorDialog("Error", "All reactions must have flux bounds for FBA.");
    } else if (exitValue == -11) {
      message.setErrorDialog("Error", "No flux objectives.");
    } else if (exitValue == -12) {
      message.setErrorDialog("Error", "No active flux objective.");
    } else if (exitValue == -13) {
      message.setErrorDialog("Error", "Unknown flux balance analysis error.");
    }
    if (exitValue != 0) {
      this.notifyObservers(message);
    }
    return exitValue;
  }

  private int executeMarkov(String filename) throws XMLStreamException, IOException, InterruptedException, BioSimException {
    String prop = null;
    LPN lhpnFile = null;
    String root = properties.getRoot();
    String sim = properties.getSim();
    if (filename.contains(".lpn")) {
      lhpnFile = new LPN();
      lhpnFile.load(filename);
    } else {
      new File(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + ".lpn").delete();
      ArrayList<String> specs = new ArrayList<>();
      ArrayList<Object[]> conLevel = new ArrayList<>();
      retrieveSpeciesAndConLevels(specs, conLevel);

      BioModel bioModel = BioModel.createBioModel(properties.getDirectory(), this);
      bioModel.load(filename);
      if (bioModel.flattenModel(true) != null) {
        if (properties.getVerificationProperties().getLpnProperty() != null && !properties.getVerificationProperties().getLpnProperty().equals("")) {
          prop = properties.getVerificationProperties().getLpnProperty();
        } else {
          prop = properties.getVerificationProperties().getConstraintProperty();
        }

        // TODO: this is temporary hack
        // Just takes first, but should be chosen from list
        if (sim.equals("transient-markov-chain-analysis")) {
          if (prop == null) {
            Model m = bioModel.getSBMLDocument().getModel();
            for (int num = 0; num < m.getConstraintCount(); num++) {
              String constraint = SBMLutilities.myFormulaToString(m.getConstraint(num).getMath());
              if (constraint.startsWith("G(") || constraint.startsWith("F(") || constraint.startsWith("U(")) {
                prop = Translator.convertProperty(m.getConstraint(num).getMath());
                break;
              }
            }
          }
        }

        MutableString mutProp = new MutableString(prop);
        lhpnFile = LPN.convertToLHPN(specs, conLevel, mutProp, bioModel);
        prop = mutProp.getString();
        if (lhpnFile == null) {
          new File(properties.getDirectory() + File.separator + "running").delete();
          return 0;
        }
        lhpnFile.save(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + ".lpn");
        this.message.setLog("Saving SBML file as LPN:\n" + filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + ".lpn");
      } else {
        new File(properties.getDirectory() + File.separator + "running").delete();
        return 0;
      }
    }
    sg = new StateGraph(lhpnFile);
    this.addObservable(sg);
    BuildStateGraphThread buildStateGraph = new BuildStateGraphThread(sg, null);
    buildStateGraph.start();
    buildStateGraph.join();
    message.setLog("Number of states found: " + sg.getNumberOfStates());
    this.notifyObservers(message);
    message.setLog("Number of transitions found: " + sg.getNumberOfTransitions());
    this.notifyObservers(message);
    message.setLog("Memory used during state exploration: " + sg.getMemoryUsed() + "MB");
    this.notifyObservers(message);
    message.setLog("Total memory used: " + sg.getTotalMemoryUsed() + "MB");
    this.notifyObservers(message);

    if (sim.equals("reachability-analysis") && !sg.getStop()) {
      message.setDialog("View State Graph", "Do you want to view the state graph?");
      if (parent.request(RequestType.REQUEST_BOOLEAN, message)) {
        if (message.getBoolean()) {
          viewStateGraph(filename, properties.getModelFile(), properties.getDirectory(), sg);
        }
      }
    } else if (sim.equals("steady-state-markov-chain-analysis")) {
      if (!sg.getStop()) {
        message.setLog("Performing steady state Markov chain analysis.");
        PerformSteadyStateMarkovAnalysisThread performMarkovAnalysis = new PerformSteadyStateMarkovAnalysisThread(sg, null);
        if (filename.contains(".lpn")) {
          performMarkovAnalysis.start(properties.getSimulationProperties().getAbsError(), null);
        } else {
          BioModel gcm = BioModel.createBioModel(root, this);
          gcm.load(filename);
          ArrayList<Property> propList = new ArrayList<>();
          if (prop == null) {
            Model m = gcm.getSBMLDocument().getModel();
            for (int num = 0; num < m.getConstraintCount(); num++) {
              String constraint = SBMLutilities.myFormulaToString(m.getConstraint(num).getMath());
              if (constraint.startsWith("St(")) {
                propList.add(sg.createProperty(m.getConstraint(num).getMetaId(), Translator.convertProperty(m.getConstraint(num).getMath())));
              }
            }
          }
          performMarkovAnalysis.start(properties.getSimulationProperties().getAbsError(), propList);
        }
        performMarkovAnalysis.join();
        if (!sg.getStop()) {
          String simrep = sg.getMarkovResults();
          if (simrep != null) {
            FileOutputStream simrepstream = new FileOutputStream(new File(properties.getDirectory() + File.separator + "sim-rep.txt"));
            simrepstream.write((simrep).getBytes());
            simrepstream.close();
          }
          sg.outputTSD(properties.getDirectory() + File.separator + "percent-term-time.tsd");
          message.setDialog("View State Graph", "Do you want to view the state graph?");
          if (parent.request(RequestType.REQUEST_BOOLEAN, message)) {
            if (message.getBoolean()) {
              viewStateGraph(filename, properties.getModelFile(), properties.getDirectory(), sg);
            }
          }
        }
      }
    } else if (sim.equals("transient-markov-chain-analysis")) {
      if (!sg.getStop()) {
        message.setLog("Performing transient Markov chain analysis with uniformization.");
        this.notifyObservers(message);
        PerformTransientMarkovAnalysisThread performMarkovAnalysis = new PerformTransientMarkovAnalysisThread(sg, null);
        if (prop != null) {
          String[] condition;

          condition = Translator.getProbpropParts(Translator.getProbpropExpression(prop));
          boolean globallyTrue = false;
          if (prop.contains("PF")) {
            condition[0] = "true";
          } else if (prop.contains("PG")) {
            condition[0] = "true";
            globallyTrue = true;
          }
          performMarkovAnalysis.start(properties.getSimulationProperties().getTimeLimit(), properties.getSimulationProperties().getMaxTimeStep(), properties.getSimulationProperties().getPrintInterval(), properties.getSimulationProperties().getAbsError(), condition, globallyTrue);

        } else {
          performMarkovAnalysis.start(properties.getSimulationProperties().getTimeLimit(), properties.getSimulationProperties().getMaxTimeStep(), properties.getSimulationProperties().getPrintInterval(), properties.getSimulationProperties().getAbsError(), null, false);
        }
        performMarkovAnalysis.join();
        if (!sg.getStop()) {
          String simrep = sg.getMarkovResults();
          if (simrep != null) {
            FileOutputStream simrepstream = new FileOutputStream(new File(properties.getDirectory() + File.separator + "sim-rep.txt"));
            simrepstream.write((simrep).getBytes());
            simrepstream.close();
          }
          sg.outputTSD(properties.getDirectory() + File.separator + "percent-term-time.tsd");
          message.setDialog("View State Graph", "Do you want to view the state graph?");
          if (parent.request(RequestType.REQUEST_BOOLEAN, message)) {
            if (message.getBoolean()) {
              viewStateGraph(filename, properties.getModelFile(), properties.getDirectory(), sg);
            }
          }
        }
      }
    }
    return 0;
  }

  private int executeNary(String filename) throws XMLStreamException, IOException, BioSimException {
    String modelFile = properties.getModelFile();
    String directory = properties.getDirectory();
    String simName = properties.getSim();
    String root = properties.getRoot();
    String lpnProperty = properties.getVerificationProperties().getLpnProperty();
    String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "").replace(".xml", "") + ".lpn";
    ArrayList<String> specs = new ArrayList<>();
    ArrayList<Object[]> conLevel = new ArrayList<>();
    retrieveSpeciesAndConLevels(specs, conLevel);
    BioModel bioModel = BioModel.createBioModel(properties.getRoot(), this);
    // TODO: check
    bioModel.load(root + File.separator + modelFile);
    String prop = null;
    if (!lpnProperty.equals("")) {
      prop = lpnProperty;
    }
    MutableString mutProp = new MutableString(prop);
    LPN lpnFile = LPN.convertToLHPN(specs, conLevel, mutProp, bioModel);
    prop = mutProp.getString();
    if (lpnFile == null) {
      new File(directory + File.separator + "running").delete();
      // logFile.close();
      return 0;
    }
    lpnFile.save(root + File.separator + simName + File.separator + lpnName);
    try {
      Translator t1 = new Translator();
      if (properties.isAbs()) {
        LPN lhpnFile = new LPN();
        lhpnFile.load(root + File.separator + simName + File.separator + lpnName);
        Abstraction abst = new Abstraction(lhpnFile, properties.getVerificationProperties().getAbsProperty());
        abst.abstractSTG(false);
        abst.save(root + File.separator + simName + File.separator + lpnName + ".temp");
        t1.convertLPN2SBML(root + File.separator + simName + File.separator + lpnName + ".temp", prop);
      } else {
        t1.convertLPN2SBML(root + File.separator + simName + File.separator + lpnName, prop);
      }
      t1.setFilename(root + File.separator + simName + File.separator + lpnName.replace(".lpn", ".xml"));
      t1.outputSBML();
    }
    catch (BioSimException e) {
      e.printStackTrace();
    }
    return 0;
  }

  private int executeSimulation(String filename) throws IOException, InterruptedException, XMLStreamException, BioSimException {
    int exitValue = 0;
    String SBMLFileName = filename;
    String[] env = Executables.envp;
    String sim = properties.getSim();

    boolean runJava = true;
    if (sim.equals("SSA-CR (Dynamic)")) {
      dynSim = new DynamicSimulation(SimulationType.CR);
      dynSim.addObservable(this);
    } else if (sim.equals("SSA-Direct (Dynamic)")) {
      dynSim = new DynamicSimulation(SimulationType.DIRECT);
      dynSim.addObservable(this);
    } else if (sim.equals("SSA-Direct (Flatten)")) {
      dynSim = new DynamicSimulation(SimulationType.HIERARCHICAL_DIRECT);
      dynSim.addObservable(this);
    } else if (sim.equals("SSA-Direct (Hierarchical)")) {
      dynSim = new DynamicSimulation(SimulationType.HIERARCHICAL_DIRECT);
      dynSim.addObservable(this);
    } else if (sim.equals("Mixed-Hierarchical")) {
      dynSim = new DynamicSimulation(SimulationType.HIERARCHICAL_MIXED);
      dynSim.addObservable(this);
    } else if (sim.equals("Hybrid-Hierarchical")) {
      dynSim = new DynamicSimulation(SimulationType.HIERARCHICAL_HYBRID);
      dynSim.addObservable(this);
    } else if (sim.equals("Runge-Kutta-Fehlberg (Dynamic)")) {
      dynSim = new DynamicSimulation(SimulationType.RK);
      dynSim.addObservable(this);
    } else if (sim.equals("Runge-Kutta-Fehlberg (Hierarchical)")) {
      dynSim = new DynamicSimulation(SimulationType.HIERARCHICAL_RK);
      dynSim.addObservable(this);
    } else if (sim.equals("Runge-Kutta-Fehlberg (Flatten)")) {
      dynSim = new DynamicSimulation(SimulationType.HIERARCHICAL_RK);
      dynSim.addObservable(this);
    } else if (sim.equals("atacs")) {
      exitValue = executeAtacs();
    } else if (sim.equals("prism")) {
      exitValue = executePrism(filename);
    } else if (sim.contains("markov-chain-analysis") || sim.equals("reachability-analysis")) {
      exitValue = executeMarkov(filename);
    } else {
      Simulator.expandArrays(SBMLFileName, properties.getAdvancedProperties().getStoichAmp());
      runJava = false;
    }

    if (runJava) {
      dynSim.simulate(properties, filename);

      new File(properties.getDirectory() + File.separator + "running").delete();
    } else {
      String[] command = properties.getReb2sacCommand(filename);

      message.setLog("Executing:\n" + SBMLutilities.commandString(command) + "\n");

      this.notifyObservers(message);

      reb2sac = exec.exec(command, env, work);
      ReadStream s1 = new ReadStream("stdin", reb2sac.getInputStream ());
      ReadStream s2 = new ReadStream("stderr", reb2sac.getErrorStream ());
      s1.start ();
      s2.start ();
      //updateReb2SacProgress();

      exitValue = reb2sac.waitFor();
    }
    return exitValue;
  }

  private int executeAtacs() throws IOException, InterruptedException {
    int exitValue = 0;

    String[] command = properties.getHse2Command();

    message.setLog("Executing:\n" + SBMLutilities.commandString(command));
    reb2sac = exec.exec(command, Executables.envp, work);

    command = properties.getAtacsCommand();

    message.setLog("Executing:\n" + SBMLutilities.commandString(command));
    this.notifyObservers(message);
    exec.exec(command, null, work);

    if (reb2sac != null) {
      exitValue = reb2sac.waitFor();
    }

    return exitValue;
  }

  private int executePrism(String filename) throws IOException, InterruptedException, XMLStreamException, BioSimException {
    int exitValue = 255;
    String prop = null;
    String directory = properties.getDirectory() + File.separator;
    String out = properties.getModelFile().replace(".xml", "").replaceAll(".lpn", "").replaceAll(".sbml", "");
    LPN lhpnFile = null;
    // String root = properties.getRoot();
    if (filename.contains(".lpn")) {
      lhpnFile = new LPN();
      lhpnFile.load(properties.getRoot() + File.separator + filename);
    } else {
      new File(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + ".lpn").delete();
      ArrayList<String> specs = new ArrayList<>();
      ArrayList<Object[]> conLevel = new ArrayList<>();
      retrieveSpeciesAndConLevels(specs, conLevel);
      BioModel bioModel = BioModel.createBioModel(properties.getDirectory(), this);
      bioModel.load(filename);
      if (bioModel.flattenModel(true) != null) {
        if (properties.getVerificationProperties().getLpnProperty() != null && !properties.getVerificationProperties().getLpnProperty().equals("")) {
          prop = properties.getVerificationProperties().getLpnProperty();
        } else {
          prop = properties.getVerificationProperties().getConstraintProperty();
        }
        MutableString mutProp = new MutableString(prop);
        lhpnFile = LPN.convertToLHPN(specs, conLevel, mutProp, bioModel);
        prop = mutProp.getString();
        if (lhpnFile == null) {
          new File(properties.getDirectory() + File.separator + "running").delete();
          return 0;
        }
        message.setLog("Saving SBML file as PRISM file:\n" + filename.replace(".xml", ".prism"));
        this.notifyObservers(message);
        message.setLog("Saving PRISM Property file:\n" + filename.replace(".xml", ".pctl"));
        this.notifyObservers(message);
    	// TODO: LUKAS
    	// bioModel.convertSBML2PRISM(logFile, filename);
        LPN.convertLPN2PRISM(logFile, lhpnFile, filename.replace(".xml", ".prism"), bioModel.getSBMLDocument());
        Preferences biosimrc = Preferences.userRoot();
        String prismCmd = biosimrc.get("biosim.general.prism", "");
        if (prismCmd.contains("$prism")) {
          prismCmd = prismCmd.replace("$prism", directory + out + ".prism");
        } else {
          prismCmd = prismCmd + " " + directory + out + ".prism";
        }
        if (prismCmd.contains("$pctl")) {
          prismCmd = prismCmd.replace("$pctl", directory + out + ".pctl");
        } else {
          prismCmd = prismCmd + " " + directory + out + ".pctl";
        }
        message.setLog("Executing:\n" + prismCmd);
        this.notifyObservers(message);
        reb2sac = exec.exec(prismCmd, null, work);
        String error = "", result = "";
        try {
          InputStream reb = reb2sac.getInputStream();
          InputStreamReader isr = new InputStreamReader(reb);
          BufferedReader br = new BufferedReader(isr);
          String line;
          while ((line = br.readLine()) != null) {
            if (line.startsWith("Result")) {
              result = line + '\n';
            }
          }
          InputStream reb2 = reb2sac.getErrorStream();
          int read = reb2.read();
          while (read != -1) {
            error += (char) read;
            read = reb2.read();
          }
          br.close();
          isr.close();
          reb.close();
          reb2.close();
        }
        catch (Exception e) {
          // e.printStackTrace();
        }
        if (reb2sac != null) {
          exitValue = reb2sac.waitFor();
        }
        if (!error.equals("")) {
          message.setLog("Errors:\n" + error + "\n");

          this.notifyObservers(message);
        } else if (!result.equals("")) {
          message.setLog(result);
          this.notifyObservers(message);
        } else {
          throw new BioSimException("Verification Failed!", "Verification could not be executed. Something went wrong.");
        }

        exitValue = 0;
      } else {
        new File(directory + File.separator + "running").delete();
        logFile.close();
        exitValue = 0;
      }
    }

    if (reb2sac != null) {
      exitValue = reb2sac.waitFor();
    }

    return exitValue;
  }

  private int executeDot(String filename) throws IOException, InterruptedException, BioSimException {
    int exitValue = 255;
    String[] command;
    String outputFileName = filename.replace(".sbml", "").replace(".xml", "") + ".dot";
    if (properties.isNary()) {
      LPN lhpnFile = new LPN();
      lhpnFile.load(filename.replace(".sbml", "").replace(".xml", "") + ".lpn");
      lhpnFile.printDot(outputFileName);
      exitValue = 0;
    } else if (filename.contains(".lpn")) {
      LPN lhpnFile = new LPN();
      try {
        lhpnFile.load(filename);
      }
      catch (BioSimException e) {
        e.printStackTrace();
      }
      if (properties.isAbs()) {
        Abstraction abst = new Abstraction(lhpnFile, properties.getVerificationProperties().getAbsProperty());
        abst.abstractSTG(false);
        abst.printDot(properties.getRoot() + File.separator + properties.getSim() + File.separator + properties.getModelFile());
      } else {
        lhpnFile.printDot(properties.getRoot() + File.separator + properties.getSim() + File.separator + properties.getModelFile());
      }
      exitValue = 0;
    } else {
      command = properties.getDotCommand();
      message.setLog("Executing:\n" + SBMLutilities.commandString(command));
      this.notifyObservers(message);
      reb2sac = exec.exec(command, Executables.envp, work);
    }

    if (reb2sac != null) {
      exitValue = reb2sac.waitFor();
    }

    if (exitValue == 0) {
      command = properties.getOpenDotCommand();

      exec.exec(command);
      message.setLog("Executing:\n" + SBMLutilities.commandString(command));
      this.notifyObservers(message);
    }

    return exitValue;
  }

  private int executeXhtml(String filename) throws IOException, InterruptedException {
    int exitValue = 0;
    Simulator.expandArrays(filename, 1);

    String[] command = properties.getXhtmlCommand();
    message.setLog("Executing:\n" + SBMLutilities.commandString(command));
    reb2sac = exec.exec(command, Executables.envp, work);

    if (reb2sac != null) {
      exitValue = reb2sac.waitFor();
    }

    command = properties.getOpenBrowserCommand();

    message.setLog("Executing:\n" + SBMLutilities.commandString(command));
    this.notifyObservers(message);
    exec.exec(command, null, work);

    return exitValue;
  }

  private int executeSBML(String filename) throws IOException, HeadlessException, XMLStreamException, InterruptedException, BioSimException {
    int exitValue = 255;

    String root = properties.getRoot();
    String modelFile = properties.getModelFile();
    String simName = properties.getSim();

    if (!parent.request(RequestType.REQUEST_STRING, message)) { return exitValue; }
    String sbmlName = message.getMessage();

    if (sbmlName != null && !sbmlName.trim().equals("")) {
      sbmlName = sbmlName.trim();
      if (!sbmlName.endsWith(".xml")) {
        sbmlName += ".xml";
      }

      File f = new File(root + File.separator + sbmlName);
      if (f.exists()) {
        message.setDialog("Overwrite", "File already exists.\nDo you want to overwrite?");
        if (!parent.request(RequestType.REQUEST_BOOLEAN, message)) { return exitValue; }

        boolean option = message.getBoolean();

        if (option) {
          File dir = new File(root + File.separator + sbmlName);
          if (dir.isDirectory()) {
            Utility.deleteDir(dir);
          } else {
            System.gc();
            dir.delete();
          }

        } else {
          new File(properties.getDirectory() + File.separator + "running").delete();
          return 0;
        }
      }
      if (modelFile.contains(".lpn")) {
        try {
          Translator t1 = new Translator();
          if (properties.isAbs()) {
            LPN lhpnFile = new LPN();
            lhpnFile.load(root + File.separator + modelFile);
            Abstraction abst = new Abstraction(lhpnFile, properties.getVerificationProperties().getAbsProperty());
            abst.abstractSTG(false);
            abst.save(root + File.separator + properties.getSim() + File.separator + modelFile);
            t1.convertLPN2SBML(root + File.separator + simName + File.separator + modelFile, properties.getVerificationProperties().getLpnProperty());
          } else {
            t1.convertLPN2SBML(root + File.separator + modelFile, properties.getVerificationProperties().getLpnProperty());
          }
          t1.setFilename(root + File.separator + sbmlName);
          t1.outputSBML();
          exitValue = 0;
          logFile.close();
        }
        catch (BioSimException e) {
          e.printStackTrace();
        }
        return exitValue;
      } else if (properties.isGui() && properties.isNary()) {
        String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "").replace(".xml", "") + ".lpn";
        ArrayList<String> specs = new ArrayList<>();
        ArrayList<Object[]> conLevel = new ArrayList<>();
        String directory = properties.getDirectory();
        retrieveSpeciesAndConLevels(specs, conLevel);
        BioModel bioModel = BioModel.createBioModel(properties.getRoot(), this);
        bioModel.load(root + File.separator + properties.getModelFile());

        if (bioModel.flattenModel(true) != null) {
          String lpnProperty = properties.getVerificationProperties().getLpnProperty();
          String prop = null;
          if (!lpnProperty.equals("")) {
            prop = lpnProperty;
          } else {
            prop = properties.getVerificationProperties().getConstraintProperty();
          }
          MutableString mutProp = new MutableString(prop);
          LPN lpnFile = LPN.convertToLHPN(specs, conLevel, mutProp, bioModel);
          prop = mutProp.getString();
          if (lpnFile == null) {
            new File(directory + File.separator + "running").delete();
            logFile.close();
            return 0;
          }
          lpnFile.save(root + File.separator + simName + File.separator + lpnName);
          try {
            Translator t1 = new Translator();
            if (properties.isAbs()) {
              LPN lhpnFile = new LPN();
              lhpnFile.load(root + File.separator + simName + File.separator + lpnName);
              Abstraction abst = new Abstraction(lhpnFile, properties.getVerificationProperties().getAbsProperty());
              abst.abstractSTG(false);
              abst.save(root + File.separator + simName + File.separator + lpnName + ".temp");
              t1.convertLPN2SBML(root + File.separator + simName + File.separator + lpnName + ".temp", prop);
            } else {
              t1.convertLPN2SBML(root + File.separator + simName + File.separator + lpnName, prop);
            }
            t1.setFilename(root + File.separator + sbmlName);
            t1.outputSBML();
          }
          catch (BioSimException e) {
            e.printStackTrace();
          }
        } else {
          new File(directory + File.separator + "running").delete();
          logFile.close();
          return 0;
        }
        exitValue = 0;
      } else {
        if (reb2sacAbstraction() && (properties.isAbs() || properties.isNary())) {
          String[] command = properties.getSbmlCommand(sbmlName);
          message.setLog("Executing:\n" + SBMLutilities.commandString(command));
          this.notifyObservers(message);
          reb2sac = exec.exec(command, Executables.envp, work);
        } else {
          message.setLog("Outputting SBML file:\n" + root + File.separator + sbmlName);
          this.notifyObservers(message);
          FileOutputStream fileOutput = new FileOutputStream(new File(root + File.separator + sbmlName));
          FileInputStream fileInput = new FileInputStream(new File(filename));
          int read = fileInput.read();
          while (read != -1) {
            fileOutput.write(read);
            read = fileInput.read();
          }
          fileInput.close();
          fileOutput.close();
          exitValue = 0;
        }
      }
    } else {
      return exitValue;
    }

    message.setString(sbmlName);
    parent.send(RequestType.ADD_FILE, message);

    if (reb2sac != null) {
      exitValue = reb2sac.waitFor();
    }

    return exitValue;
  }

  private boolean reb2sacAbstraction() {
    AdvancedProperties advProperties = properties.getAdvancedProperties();

    for (String abstractionOption : advProperties.getPreAbs()) {
      if (!abstractionOption.equals("complex-formation-and-sequestering-abstraction") && !abstractionOption.equals("operator-site-reduction-abstraction")) { return true; }
    }

    return advProperties.getLoopAbs().size() > 0 || advProperties.getPostAbs().size() > 0;

  }

  private void retrieveSpeciesAndConLevels(ArrayList<String> specs, ArrayList<Object[]> conLevel) {
    List<String> intSpecies = properties.getSimulationProperties().getIntSpecies();
    for (int i = 0; i < intSpecies.size(); i++) {
      if (!intSpecies.get(i).equals("")) {
        String[] split = intSpecies.get(i).split(" ");
        if (split.length > 1) {
          String[] levels = split[1].split(",");
          if (levels.length > 0) {
            specs.add(split[0]);
            conLevel.add(levels);
          }
        }
      }
    }
  }

  public class ReadStream implements Runnable {
	  String name;
	  InputStream is;
	  Thread thread;

	  public ReadStream(String name, InputStream is) {
		  this.name = name;
		  this.is = is;
	  }
	  public void start () {
		  thread = new Thread (this);
		  thread.start ();
	  }
	  public void run () {
		  try {
			  InputStreamReader isr = new InputStreamReader (is);
			  BufferedReader br = new BufferedReader (isr);
			  double runTime = properties.getSimulationProperties().getRun() * properties.getSimulationProperties().getTimeLimit();
			  double time = 0;
			  double oldTime = 0;
			  int runNum = 0;
			  int prog = 0;
			  while (true) {
				  String line = br.readLine ();
				  if (line == null) break;
				  if (name.equals("stdin")) {
					  try {
						  if (line.contains("Time")) {
							  time = Double.parseDouble(line.substring(line.indexOf('=') + 1, line.length()));
							  if (oldTime > time) {
								  runNum++;
							  }
							  oldTime = time;
							  time += (runNum * properties.getSimulationProperties().getTimeLimit());
							  double d = ((time * 100) / runTime);
							  String s = d + "";
							  double decimal = Double.parseDouble(s.substring(s.indexOf('.'), s.length()));
							  if (decimal >= 0.5) {
								  prog = (int) (Math.ceil(d));
							  } else {
								  prog = (int) (d);
							  }
						  }
					  }
					  catch (Exception e) {
						  e.printStackTrace();
					  }
					  if (parent!=null) {
						  message.setInteger(prog);
						  parent.send(RequestType.REQUEST_PROGRESS, message);
					  } else{
						  System.out.println(line);
					  }
				  } else {
					  System.out.println ("[" + name + "] " + line);
				  }
			  }
			  is.close ();
		  } catch (Exception ex) {
			  System.out.println ("Problem reading stream " + name + "... :" + ex);
			  ex.printStackTrace ();
		  }
	  }
  }

  private void updateReb2SacProgress() throws IOException {
    String error = "";
    try {
      double runTime = properties.getSimulationProperties().getRun() * properties.getSimulationProperties().getTimeLimit();
      InputStream reb = reb2sac.getInputStream();
      InputStreamReader isr = new InputStreamReader(reb);
      BufferedReader br = new BufferedReader(isr);
      String line;
      double time = 0;
      double oldTime = 0;
      int runNum = 0;
      int prog = 0;
      while ((line = br.readLine()) != null) {
        try {
          if (line.contains("Time")) {
            time = Double.parseDouble(line.substring(line.indexOf('=') + 1, line.length()));
            if (oldTime > time) {
              runNum++;
            }
            oldTime = time;
            time += (runNum * properties.getSimulationProperties().getTimeLimit());
            double d = ((time * 100) / runTime);
            String s = d + "";
            double decimal = Double.parseDouble(s.substring(s.indexOf('.'), s.length()));
            if (decimal >= 0.5) {
              prog = (int) (Math.ceil(d));
            } else {
              prog = (int) (d);
            }
          }
        }
        catch (Exception e) {
          e.printStackTrace();
        }
        this.message.setInteger(prog);
        parent.send(RequestType.REQUEST_PROGRESS, message);
      }
      InputStream reb2 = reb2sac.getErrorStream();
      int read = reb2.read();
      while (read != -1) {
        error += (char) read;
        read = reb2.read();
      }
      br.close();
      isr.close();
      reb.close();
      reb2.close();
    }
    catch (Exception e) {
      // e.printStackTrace();
    }

    if (!error.equals("")) {
      message.setLog("Errors:\n" + error);
      this.notifyObservers(message);
    }

  }

  private void viewStateGraph(String filename, String theFile, String directory, StateGraph sg) {
    String graphFile = filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + "_sg.dot";
    sg.outputStateGraph(graphFile, true);
    try {
      Runtime execGraph = Runtime.getRuntime();
      if (System.getProperty("os.name").contentEquals("Linux")) {
        message.setLog("Executing:\ndotty " + graphFile);
        execGraph.exec("dotty " + theFile.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + "_sg.dot", null, new File(directory));
      } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) {
        message.setLog("Executing:\nopen " + graphFile);
        execGraph.exec("open " + theFile.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + "_sg.dot", null, new File(directory));
      } else {
        message.setLog("Executing:\ndotty " + graphFile);
        execGraph.exec("dotty " + theFile.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + "_sg.dot", null, new File(directory));
      }
    }
    catch (Exception e1) {
      message.setErrorDialog("Error", "Error viewing state graph.");
    }
  }

  /**
   * This method is called if a button that cancels the simulation is pressed.
   */
  @Override
  public void actionPerformed(ActionEvent e) {

    if (dynSim != null) {
      dynSim.cancel();
    }
    if (reb2sac != null) {
      reb2sac.destroy();
    }
    if (sg != null) {
      sg.stop();
    }
  }

  @Override
  public boolean send(RequestType type, Message message) {
    if (type == RequestType.REQUEST_PROGRESS) {
      if (parent != null) { return parent.send(type, message); }
    }

    return false;
  }

}


text:
if [[ $TRAVIS_BRANCH == "master" && $TRAVIS_PULL_REQUEST == false && $RUN_TESTS == true ]]
then
    echo -e "### Installing pip requirements to lib directory"
    pip install -t lib -r requirements.txt

    echo -e "\n### Deploying to App Engine"
    cd ./ci/google_appengine
    python appcfg.py update --oauth2_refresh_token=$AE_OAUTH_REFRESH ../../
fi


text:
(function() {
  'use strict';

  angular
    .module('coldTracker', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'ngMessages', 'ngAria', 'ngRoute', 'toastr']);

})();


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

  <bean id="favoriteService" class="org.apache.xbean.spring.example.FavoriteService">
    <property name="favorites">
      <map>
        <entry key="Dan">
          <value>Grey Goose</value>
        </entry>
        <entry key="IndecisiveDan">
          <list>
            <value>Malbec</value>
            <bean class="java.lang.Integer">
              <constructor-arg value="0"/>
            </bean>
          </list>
        </entry>
        <entry key="WithInnerBean">
          <bean class="org.apache.xbean.spring.example.GinService">
            <property name="name" value="name"/>
          </bean>
        </entry>
      </map>
    </property>
  </bean>

</beans>


text:
package edu.ucsb.cs56.drawings.jkr.advanced;
import java.awt.geom.GeneralPath;
import java.awt.Shape;

import java.awt.geom.Point2D;
import java.awt.geom.Line2D;
import java.awt.geom.Ellipse2D;

/**
   A Playbutton

   @author John Rehbein
   @version for CS56, F16, UCSB

*/
public class BetterPlayButton extends PlayButton implements Shape
{
    /**
     Constructor

     @param x x coord of lower left corner of house
     @param y y coord of lower left corner of house
     @param radius radius of button
     */
    public BetterPlayButton(int x, int y, int radius)
    {
        super(x, y, radius);
        Point2D.Double[] point = {new Point2D.Double(x+radius/3.0+radius/20.0, y+radius/3.0+radius/20.0),
            new Point2D.Double(x+radius*2.0/3.0-radius/20.0, y+radius/2.0) };

        // An extra circle cause it looks cooler
        Ellipse2D.Double innerCircle = new Ellipse2D.Double(x+radius/20.0, y+radius/20.0, radius * 9/10.0, radius * 9/10.0);

        Line2D.Double accentLine =
        new Line2D.Double (point[0], point[1]);

        GeneralPath playButtonPath = this.get();
        playButtonPath.append(innerCircle, false);
        playButtonPath.append(accentLine, false);
    }
}


text:
var isNode = require("./isNode");

/**
 * @param {*} object The object to check.
 * @return {boolean} Whether or not the object is a DOM text node.
 */
function isTextNode(object) {
  return isNode(object) && object.nodeType == 3;
}

module.exports = isTextNode;


text:
import { NextFunction, Request, Response } from 'express'
import { ResizeDto } from '../resize.dto'

export function useWebpIfSupported(
  req: Request,
  res: Response,
  next: NextFunction,
): void {
  const { dto } = res.locals as { dto: ResizeDto }

  if (req.headers.accept?.includes('image/webp')) {
    dto.format = 'webp'
  }

  next()
}


text:
FROM maven:3.6.1-jdk-11-slim as maven
WORKDIR /wicket
COPY src src
COPY pom.xml pom.xml
RUN mvn compile war:war -q

FROM openjdk:11.0.3-jre-stretch
WORKDIR /resin
RUN curl -sL http://caucho.com/download/resin-4.0.61.tar.gz | tar xz --strip-components=1
RUN rm -rf webapps/*
COPY --from=maven /wicket/target/hellowicket-1.0.war webapps/ROOT.war
COPY resin.xml conf/resin.xml
CMD ["java", "-Xms2G", "-Xmx2G", "-server", "-XX:+UseNUMA", "-XX:+UseParallelGC", "-XX:+AggressiveOpts", "-jar", "lib/resin.jar", "console"]


text:
class TaxTribs::SaveCaseForLater
  attr_reader :tribunal_case, :user

  def initialize(tribunal_case, user)
    @tribunal_case = tribunal_case
    @user = user
    @email_sent = false
  end

  def save
    tribunal_case.nil? || tribunal_case.user.present? || claim_case_ownership
  end

  def email_sent?
    @email_sent
  end

  private

  def claim_case_ownership
    tribunal_case.update(user: user)
    NotifyMailer.new_case_saved_confirmation(tribunal_case).deliver_later
    @email_sent = true
  end
end


text:
		<title>Wastebin Login - EasyCTF 2015</title>

Wastebin

wastebin is the best paste tool on the internet guyz!!!11!1 we will keep all ur info safe

num of users registered:

		<form action="javascript:check_login();">

<input type="text" id="username" placeholder="Username" />

<input type="password" id="password" placeholder="Password" />

<input type="submit" value="Login!" />

		</form>


text:
module ALife.Creatur.Wain.ImageID.ActionQC
  (
    test
  ) where

import ALife.Creatur.Wain.ImageID.Action (Action)
import ALife.Creatur.Wain.TestUtils (prop_serialize_round_trippable,
  prop_genetic_round_trippable, prop_diploid_identity)
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck

instance Arbitrary Action where
  arbitrary = elements [minBound .. maxBound]

test :: Test
test = testGroup "ALife.Creatur.Wain.ImageID.ActionQC"
  [
    testProperty "prop_serialize_round_trippable - Action"
      (prop_serialize_round_trippable :: Action -> Property),
    testProperty "prop_genetic_round_trippable - Action"
      (prop_genetic_round_trippable (==) :: Action -> Property),
    testProperty "prop_diploid_identity - Action"
      (prop_diploid_identity (==) :: Action -> Property)
  ]


text:
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"os"

	"github.com/knq/firebase"
)

var (
	flagCredentials = flag.String("creds", "", "path to google service account credentials")
	flagRef         = flag.String("ref", "/", "firebase ref to retrieve")
	flagVerbose     = flag.Bool("v", false, "verbose logging")
	flagRules       = flag.Bool("rules", false, "retrieve rules")
)

func main() {
	var err error

	flag.Parse()

	// check credentials
	if *flagCredentials == "" {
		fmt.Fprintf(os.Stderr, "error: invalid credentials file\n")
		os.Exit(1)
	}

	// build firebase options
	opts := []firebase.Option{
		firebase.GoogleServiceAccountCredentialsFile(*flagCredentials),
	}
	if *flagVerbose {
		opts = append(opts, firebase.Log(log.Printf, log.Printf))
	}

	// create database ref
	ref, err := firebase.NewDatabaseRef(opts...)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		os.Exit(1)
	}

	// retrieve ref
	var buf []byte
	if !*flagRules {
		var v interface{}
		err = ref.Ref(*flagRef).Get(&v)
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}

		// pretty format
		buf, err = json.MarshalIndent(v, "", "  ")
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}
	} else {
		buf, err = ref.Ref(*flagRef).GetRulesJSON()
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}
	}

	fmt.Fprintf(os.Stdout, "%s\n", string(buf))
}


text:
<?php

namespace DkcwdZf2Munee;

/**
 * Module class required for module to be initialized in ZF2 application
 */
class Module
{
    /**
     * Retrieve autoloader configuration for the module
     *
     * @return array
     */
    public function getAutoloaderConfig()
    {
        return array('Zend\Loader\StandardAutoloader' => array(
            'namespaces' => array(
                __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
            ),
        ));
    }

    /**
     * Retrieve application configuration for this module
     *
     * @return array
     */
    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    /**
     * Register view helpers for this module
     *
     * @return array
     */
    public function getViewHelperConfig()
    {
        $path = 'DkcwdZf2Munee\View\Helpers\\';
        return array(
            'invokables' => array(
                'MuneeCss' => $path . 'MuneeCss',
                'MuneeImg' => $path . 'MuneeImg',
                'MuneeJs'  => $path . 'MuneeJs',
            ),
        );
    }

}


text:
![5 stars](../../images/ic_star_black_18dp_1x.png)![5 stars](../../images/ic_star_black_18dp_1x.png)![5 stars](../../images/ic_star_black_18dp_1x.png)![5 stars](../../images/ic_star_black_18dp_1x.png)![5 stars](../../images/ic_star_black_18dp_1x.png) 2

To use the Today's Ten skill, try saying...

* *Alexa, open Today's Ten*

* *Alexa, ask Today's Ten for tech events*

* *Alexa, tell Today's Ten to get world events*

Want to know what's going on in the world but a little short on time? Alexa can help with the Today's 10 skill. Get a rundown of the top ten world events or business events happening at the moment so you can stay up to date even if you're running late. Powered by Business Insider.

***

### Skill Details

* **Invocation Name:** today's ten
* **Category:** null
* **ID:** amzn1.echo-sdk-ams.app.cad10f38-2f37-4d9a-8fcc-1ab1791ce3e4
* **ASIN:** B01F9VJXL6
* **Author:** CaptainQuirk
* **Release Date:** May 12, 2016 @ 05:38:44
* **In-App Purchasing:** No


text:
TRPG
====

Text-Based Role-Playing Game

Game Data is stored in JSON files that are read at startup.  OOP principles are rarely used for simplicity.

The plan is to move ove to a more object-oriented approach as more features get added.

Based on [this tutorial.](http://inventwithpython.com/blog/2014/12/11/making-a-text-adventure-game-with-the-cmd-and-textwrap-python-modules/)

Jacob Peroutek


text:
package com.capitalone.dashboard.service;

import com.capitalone.dashboard.model.*;
import com.capitalone.dashboard.repository.CollectorRepository;
import com.capitalone.dashboard.repository.ComponentRepository;
import com.capitalone.dashboard.repository.TestResultRepository;
import com.capitalone.dashboard.request.TestResultRequest;
import com.mysema.query.BooleanBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;

@Service
public class TestResultServiceImpl implements TestResultService {

    private final TestResultRepository testResultRepository;
    private final ComponentRepository componentRepository;
    private final CollectorRepository collectorRepository;

    @Autowired
    public TestResultServiceImpl(TestResultRepository testResultRepository,
                                 ComponentRepository componentRepository,
                                 CollectorRepository collectorRepository) {
        this.testResultRepository = testResultRepository;
        this.componentRepository = componentRepository;
        this.collectorRepository = collectorRepository;
    }

    @Override
    public DataResponse<Iterable<TestResult>> search(TestResultRequest request) {
        Component component = componentRepository.findOne(request.getComponentId());
        if (!component.getCollectorItems().containsKey(CollectorType.Test)) {
            return new DataResponse<>(null, 0L);
        }
        ArrayList<TestResult> result = new ArrayList<>();

        for (CollectorItem item : component.getCollectorItems().get(CollectorType.Test)) {

            QTestResult testResult = new QTestResult("testResult");
            BooleanBuilder builder = new BooleanBuilder();

            builder.and(testResult.collectorItemId.eq(item.getId()));

            if (request.validStartDateRange()) {
                builder.and(testResult.startTime.between(request.getStartDateBegins(), request.getStartDateEnds()));
            }
            if (request.validEndDateRange()) {
                builder.and(testResult.endTime.between(request.getEndDateBegins(), request.getEndDateEnds()));
            }

            if (request.validDurationRange()) {
                builder.and(testResult.duration.between(request.getDurationGreaterThan(), request.getDurationLessThan()));
            }

            if (!request.getTypes().isEmpty()) {
                builder.and(testResult.testCapabilities.any().type.in(request.getTypes()));
            }

            if (request.getMax() == null) {
                result.addAll(Lists.newArrayList(testResultRepository.findAll(builder.getValue(), testResult.timestamp.desc())));
            } else {
                PageRequest pageRequest = new PageRequest(0, request.getMax(), Sort.Direction.DESC, "timestamp");
                result.addAll(Lists.newArrayList(testResultRepository.findAll(builder.getValue(), pageRequest).getContent()));
            }
        }
        //One collector per Type. get(0) is hardcoded.
        if (!CollectionUtils.isEmpty(component.getCollectorItems().get(CollectorType.Test)) && (component.getCollectorItems().get(CollectorType.Test).get(0) != null)) {
            Collector collector = collectorRepository.findOne(component.getCollectorItems().get(CollectorType.Test).get(0).getCollectorId());
            if (collector != null) {
                return new DataResponse<>((Iterable<TestResult>) result, collector.getLastExecuted());
            }
        }

        return new DataResponse<>(null, 0L);
    }
}


text:
    Payments

Number of Payments per Day

Amount Collected Per Day


text:
({
  _HASH_PREFIX: 'nav',

  init: function(cmp, evt) {
    if(this._isDebug(cmp)){
      this._debug('---- init routeView:' + cmp.get('v.path') + '----');
    }

    var data = this._getHashData();
    if (!data) {
      return;
    }
    this._handleState(cmp, data);
  },

  _handleState: function(cmp, data) {
    var component, viewPath = (data.viewPath || '').split('/'),
      cmpPath = (data.cmpPath || '').split('/'),
      parameters = data.parameters || {},
      myPath = cmp.get('v.path');

    for (var i = 0; i < viewPath.length; i++) {
      if (viewPath[i] === myPath) {
        component = cmpPath[i];
        if (!this._shouldLoadComponent(cmp, component, parameters)) {
          if(this._isDebug(cmp)){
            this._debug('----component:' + component + ' already loaded----');
          }
          return;
        }
        cmp.set('v.component', component);
        cmp.set('v.parameters', parameters);
        this._newComponent(cmp, component, parameters);
        break;
      }
    }
  },

  route: function(cmp, evt) {
    if(this._isDebug(cmp)){
      this._debug('----subscribe to route app event----' + cmp.get('v.path'));
    }
    var data = this._getHashData();
    if (!data) {
      return;
    }
    this._handleState(cmp, data);
  },

  _newComponent: function(cmp, componentName, parameters) {
    $A.createComponent(componentName, parameters, function(child, status, error) {
      switch (status) {
        case 'SUCCESS':
          cmp.set('v.body', child);
          break;
        case 'INCOMPLETE':
          console.log('No response from server or client is offline.');
          break;
        case 'ERROR':
          console.log('Error:' + error);
      }
    });
  },

  _getHashData: function() {
    var data,
      self = this,
      hash = location.hash || '',
      prefix = this._HASH_PREFIX + '=';

    if (hash.indexOf(prefix) === -1) {
      return 0;
    }
    return JSON.parse(self._decode(hash.substr(hash.indexOf(prefix) + prefix.length)));
  },

  _shouldLoadComponent: function(cmp, componentName, parameters) {
    var currentComponent = cmp.get('v.component'),
      currentProps = cmp.get("v.parameters") || {};
    if (currentComponent !== componentName) {
      return 1;
    }
    return this._matchObject(currentProps)(parameters) ? 0 : 1;
  },

  _matchObject: function(source) {
    return function(target) {
      var keys = Object.keys(source);
      return keys.length === 0 || !keys.some(function(k) {
        return source[k] != target[k];
      });
    }
  },

  _isDebug: function(cmp){
    return !!cmp.get('v.debug');
  },

  _debug: function(msg){
    console.log(msg);
  },

  _encode: function(data) {
    return window.btoa(unescape(encodeURIComponent(data)));
  },

  _decode: function(data) {
      return decodeURIComponent(escape(window.atob(data)));
    }
    ////// end of code /////
})


text:
package com.wavesplatform.api.http.requests

import com.wavesplatform.account.PublicKey
import com.wavesplatform.common.state.ByteStr
import com.wavesplatform.lang.ValidationError
import com.wavesplatform.lang.script.Script
import com.wavesplatform.transaction.assets.IssueTransaction
import com.wavesplatform.transaction.{Proofs, TxVersion}
import play.api.libs.json.{Format, Json}

case class IssueRequest(
    version: Option[Byte],
    sender: Option[String],
    senderPublicKey: Option[String],
    name: String,
    description: String,
    quantity: Long,
    decimals: Byte,
    reissuable: Boolean,
    script: Option[String],
    fee: Long,
    timestamp: Option[Long],
    signature: Option[ByteStr],
    proofs: Option[Proofs]
) extends TxBroadcastRequest {
  def toTxFrom(sender: PublicKey): Either[ValidationError, IssueTransaction] = {
    val actualVersion = version.getOrElse(TxVersion.V3)

    for {
      validProofs <- toProofs(signature, proofs)
      validScript <- script match {
        case None         => Right(None)
        case Some(script) => Script.fromBase64String(script).map(Some(_))
      }
      tx <- IssueTransaction.create(
        actualVersion,
        sender,
        name,
        description,
        quantity,
        decimals,
        reissuable,
        validScript,
        fee,
        timestamp.getOrElse(defaultTimestamp),
        validProofs
      )
    } yield tx
  }
}

object IssueRequest {
  implicit val jsonFormat: Format[IssueRequest] = Json.format
}