text:
enum YStatusCode {
  kStatusCode_OK,
  kStatusCode_ERROR,

  kStatusCode_InvalidArguments,
  kStatusCode_SystemError,
  kStatusCode_AlreadyRunning,

  NUM_STATUS_CODES
};

static const char* kStatusCodeStrings[] = {
  "OK",                   // kStatusCode_OK,
  "ERROR",                // kStatusCode_ERROR,
  "Invalid Arguments",    // kStatusCode_InvalidArguments,
  "System Error",         // kStatusCode_SystemError,
  "Already Running",      //kStatusCode_AlreadyRunning,
};
static_assert(sizeof(kStatusCodeStrings) / sizeof(const char*) ==
              NUM_STATUS_CODES,
              "Status Code strings must match all status codes.");

#endif // YCOMMON_HEADERS_STATUSCODES_H


text:
<?php
/**
 * @author    MyBB Group
 * @version   2.0.0
 * @package   mybb/core
 * @license   http://www.mybb.com/licenses/bsd3 BSD-3
 */

namespace MyBB\Core\Exceptions;

use \Exception;

class PollClosedException extends Exception
{
	/**
	 * @var string
	 */
	protected $message = 'errors.poll_is_closed';

	/**
	 * @param null      $message
	 * @param int       $code
	 * @param Exception $previous
	 */
	public function __construct($message = null, $code = 0, \Exception $previous = null)
	{
		if ($message === null) {
			$message = trans($this->message);
		}

		parent::__construct($message, $code, $previous);
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * @filenames   : GatotKaca/Erp/MainBundle/Controller/OfficeHourController.php
 * Author       : Muhammad Surya Ikhsanudin
 * License      : Protected
 * Email        : mutofiyah@gmail.com
 *
 * Dilarang merubah, mengganti dan mendistribusikan
 * ulang tanpa sepengetahuan Author
 **/
namespace GatotKaca\Erp\MainBundle\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use GatotKaca\Erp\MainBundle\Controller\AdminController;

class OfficeHourController extends AdminController
{
    const MODULE= 'panelofficehour';

    /**
     * @Route("/officehour", name="GatotKacaErpMainBundle_OfficeHour_index")
     **/
    public function indexAction()
    {
        return $this->goHome();
    }

    /**
     * @Route("/officehour/save", name="GatotKacaErpMainBundle_OfficeHour_save")
     *
     * Save OfficeHour
     **/
    public function saveAction()
    {
        $session    = $this->getHelper()->getSession();
        $request    = $this->getRequest();
        $security   = $this->getSecurity();
        $output     = array('success' => false);
        //Don't have authorization
        if (!$security->isAllowed($session->get('group_id'), OfficeHourController::MODULE, 'view')) {
            return new JsonResponse($output);
        }
        $input  = json_decode($request->get('officehour'));
        //Get model
        $model  = $this->getModelManager()->getOfficeHour();
        if ($success = $model->save($input)) {
            $output['success']  = true;
            $output['msg']      = 'Office Hour has been saved.';
        } else {
            $output['msg']      = $model->getMessage().'. Office Hour has not been saved.';
        }
        $security->logging($request->getClientIp(), $session->get('user_id'), $request->get('_route'), $model->getAction(), $model->getModelLog());

        return new JsonResponse($output);
    }

    /**
     * @Route("/officehour/getlist", name="GatotKacaErpMainBundle_OfficeHour_getList")
     **/
    public function getListAction()
    {
        $session    = $this->getHelper()->getSession();
        $request    = $this->getRequest();
        $security   = $this->getSecurity();
        $output     = array('success' => false);
        //Don't have authorization
        if (!$security->isAllowed($session->get('group_id'), OfficeHourController::MODULE, 'view')) {
            return new JsonResponse($output);
        }
        $output = array('success' => true);
        $keyword= strtoupper($request->get('query', ''));
        $start  = abs($request->get('start'));
        $limit  = abs($request->get('limit'));
        $status = $request->get('status', 'true');
        //Get model
        $model  = $this->getModelManager()->getOfficeHour();
        $model->setStatus(($status === 'all') ? null : $status);
        $officeHour = $model->getList($keyword, $start, $limit);
        if ($total = count($officeHour)) {
            $output['total']= $model->getTotal($keyword, $limit);
            $output['data'] = $officeHour;
        } else {
            $output['total']= $total;
            $output['data'] = array();
        }
        $security->logging($request->getClientIp(), $session->get('user_id'), $request->get('_route'), $model->getAction(), $model->getModelLog());

        return new JsonResponse($output);
    }

    /**
     * @Route("/officehour/getbyid", name="GatotKacaErpMainBundle_OfficeHour_getById")
     */
    public function getByIdAction()
    {
        $session    = $this->getHelper()->getSession();
        $request    = $this->getRequest();
        $security   = $this->getSecurity();
        $output     = array('success' => false);
        //Don't have authorization
        if (!$security->isAllowed($session->get('group_id'), OfficeHourController::MODULE, 'view')) {
            return new JsonResponse($output);
        }
        $output     = array('success' => true);
        //Get model
        $model      = $this->getModelManager()->getOfficeHour();
        $officeHour = $model->getById($request->get('officehour_id'));
        if (count($officeHour)) {
            $output['data'] = $officeHour;
        }
        $security->logging($request->getClientIp(), $session->get('user_id'), $request->get('_route'), $model->getAction(), $model->getModelLog());

        return new JsonResponse($output);
    }

    /**
     * @Route("/officehour/delete", name="GatotKacaErpMainBundle_OfficeHour_delete")
     */
    public function deleteAction()
    {
        $session    = $this->getHelper()->getSession();
        $request    = $this->getRequest();
        $security   = $this->getSecurity();
        $output     = array('success' => false, 'msg' => 'Authorization failed.');
        //Don't have authorization
        if (!$security->isAllowed($session->get('group_id'), OfficeHourController::MODULE, 'delete')) {
            return new JsonResponse($output);
        }
        //Get model
        $model  = $this->getModelManager()->getOfficeHour();
        if ($success = $model->delete($request->get('id', ''))) {
            $output['success']  = true;
            $output['msg']      = 'OfficeHour has been delete.';
        } else {
            $output['msg']      = "Operation failed. ".$model->getMessage();
        }
        $security->logging($request->getClientIp(), $session->get('user_id'), $request->get('_route'), $model->getAction(), $model->getModelLog());

        return new JsonResponse($output);
    }
}


text:
package com.gemstone.gemfire.cache30;

import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import com.gemstone.gemfire.SystemFailure;
import com.gemstone.gemfire.cache.AttributesFactory;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheException;
import com.gemstone.gemfire.cache.CacheExistsException;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.CacheTransactionManager;
import com.gemstone.gemfire.cache.ExpirationAttributes;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.RegionExistsException;
import com.gemstone.gemfire.cache.TimeoutException;
import com.gemstone.gemfire.cache.Region.Entry;
import com.gemstone.gemfire.cache.client.ClientCache;
import com.gemstone.gemfire.cache.client.ClientCacheFactory;
import com.gemstone.gemfire.cache.client.PoolManager;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.distributed.internal.DistributionMessageObserver;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.distributed.internal.membership.jgroup.MembershipManagerHelper;
import com.gemstone.gemfire.internal.FileUtil;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.HARegion;
import com.gemstone.gemfire.internal.cache.InternalRegionArguments;
import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.gemstone.gemfire.internal.cache.PartitionedRegion;
import com.gemstone.gemfire.internal.cache.xmlcache.CacheCreation;
import com.gemstone.gemfire.internal.cache.xmlcache.CacheXmlGenerator;
import com.gemstone.org.jgroups.Event;
import com.gemstone.org.jgroups.JChannel;
import com.gemstone.org.jgroups.stack.Protocol;

import dunit.DistributedTestCase;
import dunit.Host;
import dunit.SerializableCallable;
import dunit.VM;

/**
 * The abstract superclass of tests that require the creation of a
 * {@link Cache}.
 *
 * @author David Whitlock
 * @since 3.0
 */
public abstract class CacheTestCase extends DistributedTestCase {

  /** The Cache from which regions are obtained
   *
   * All references synchronized via CacheTestCase.class
   * */
  // static so it doesn't get serialized with SerializableRunnable inner classes
  protected static Cache cache;

  ////////  Constructors

  public CacheTestCase(String name) {
    super(name);
  }

  ////////  Helper methods
  /**
   * Creates the Cache for this test
   */
  private void createCache() {
    createCache(false);
  }

  private void createCache(boolean client) {
    createCache(client, null);
  }

  private void createCache(boolean client, CacheFactory cf) {
    synchronized(CacheTestCase.class) {
      try {
        System.setProperty("gemfire.DISABLE_DISCONNECT_DS_ON_CACHE_CLOSE", "true");
        Cache c;
        if (client) {
          c = (Cache)new ClientCacheFactory(getSystem().getProperties()).create();
        } else {
          if(cf == null) {
            c = CacheFactory.create(getSystem());
          } else {
            Properties props = getSystem().getProperties();
            for(Map.Entry entry : props.entrySet()) {
              cf.set((String) entry.getKey(), (String)entry.getValue());
            }
            c = cf.create();
          }
        }
        cache = c;
      } catch (CacheExistsException e) {
        fail("the cache already exists", e);

      } catch (RuntimeException ex) {
        throw ex;

      } catch (Exception ex) {
        fail("Checked exception while initializing cache??", ex);
      } finally {
        System.clearProperty("gemfire.DISABLE_DISCONNECT_DS_ON_CACHE_CLOSE");
      }
    }
  }

  /**
   * Creates the Cache for this test that is not connected
   * to other members
   */
  public Cache createLonerCache() {
    synchronized(CacheTestCase.class) {
      try {
        System.setProperty("gemfire.DISABLE_DISCONNECT_DS_ON_CACHE_CLOSE", "true");
        Cache c = CacheFactory.create(getLonerSystem());
        cache = c;
      } catch (CacheExistsException e) {
        fail("the cache already exists", e);

      } catch (RuntimeException ex) {
        throw ex;

      } catch (Exception ex) {
        fail("Checked exception while initializing cache??", ex);
      } finally {
        System.clearProperty("gemfire.DISABLE_DISCONNECT_DS_ON_CACHE_CLOSE");
      }
      return cache;
    }
  }

  /**
   * Creates the Cache for this test that is not connected
   * to other members.
   * Added specifically to test scenario of defect #47181.
   */
  public Cache createLonerCacheWithEnforceUniqueHost() {
    synchronized(CacheTestCase.class) {
      try {
        System.setProperty("gemfire.DISABLE_DISCONNECT_DS_ON_CACHE_CLOSE", "true");
        Cache c = CacheFactory.create(getLonerSystemWithEnforceUniqueHost());
        cache = c;
      } catch (CacheExistsException e) {
        fail("the cache already exists", e);

      } catch (RuntimeException ex) {
        throw ex;

      } catch (Exception ex) {
        fail("Checked exception while initializing cache??", ex);
      } finally {
        System.clearProperty("gemfire.DISABLE_DISCONNECT_DS_ON_CACHE_CLOSE");
      }
      return cache;
    }
  }

  /**
   * Creates the Cache for this test that has its own mcast group
   */
  public Cache createMcastCache() {
    synchronized(CacheTestCase.class) {
      try {
        System.setProperty("gemfire.DISABLE_DISCONNECT_DS_ON_CACHE_CLOSE", "true");
        Cache c = CacheFactory.create(getMcastSystem());
        cache = c;
      } catch (CacheExistsException e) {
        fail("the cache already exists", e);

      } catch (RuntimeException ex) {
        throw ex;

      } catch (Exception ex) {
        fail("Checked exception while initializing cache??", ex);
      } finally {
        System.clearProperty("gemfire.DISABLE_DISCONNECT_DS_ON_CACHE_CLOSE");
      }
      return cache;
    }
  }

  /**
   * Creates the Cache for this test that has its own mcast group
   */
  public Cache createMcastCache(int jgroupsPort) {
    synchronized(CacheTestCase.class) {
      try {
        System.setProperty("gemfire.DISABLE_DISCONNECT_DS_ON_CACHE_CLOSE", "true");
        Cache c = CacheFactory.create(getMcastSystem(jgroupsPort));
        cache = c;
      } catch (CacheExistsException e) {
        fail("the cache already exists", e);

      } catch (RuntimeException ex) {
        throw ex;

      } catch (Exception ex) {
        fail("Checked exception while initializing cache??", ex);
      } finally {
        System.clearProperty("gemfire.DISABLE_DISCONNECT_DS_ON_CACHE_CLOSE");
      }
      return cache;
    }
  }
  /**
   * Sets this test up with a CacheCreation as its cache.
   * Any existing cache is closed. Whoever calls this must also call finishCacheXml
   */
  public static synchronized void beginCacheXml() {
//    getLogWriter().info("before closeCache");
    closeCache();
//    getLogWriter().info("before TestCacheCreation");
    cache = new TestCacheCreation();
//    getLogWriter().info("after TestCacheCreation");
  }
  /**
   * Finish what beginCacheXml started. It does this be generating a cache.xml
   * file and then creating a real cache using that cache.xml.
   */
  public void finishCacheXml(String name) {
    synchronized(CacheTestCase.class) {
      File file = new File(name + "-cache.xml");
      try {
        PrintWriter pw = new PrintWriter(new FileWriter(file), true);
        CacheXmlGenerator.generate(cache, pw);
        pw.close();
      } catch (IOException ex) {
        fail("IOException during cache.xml generation to " + file, ex);
      }
      cache = null;
      GemFireCacheImpl.testCacheXml = file;
      try {
        createCache();
      } finally {
        GemFireCacheImpl.testCacheXml = null;
      }
    }
  }

  /**
   * Finish what beginCacheXml started. It does this be generating a cache.xml
   * file and then creating a real cache using that cache.xml.
   */
  public void finishCacheXml(String name, boolean useSchema, String xmlVersion) {
    synchronized(CacheTestCase.class) {
      File dir = new File("XML_" + xmlVersion);
      dir.mkdirs();
      File file = new File(dir, name + ".xml");
      try {
        PrintWriter pw = new PrintWriter(new FileWriter(file), true);
        CacheXmlGenerator.generate(cache, pw, useSchema, xmlVersion);
        pw.close();
      } catch (IOException ex) {
        fail("IOException during cache.xml generation to " + file, ex);
      }
      cache = null;
      GemFireCacheImpl.testCacheXml = file;
      try {
        createCache();
      } finally {
        GemFireCacheImpl.testCacheXml = null;
      }
    }
  }

  /**
   * Return a cache for obtaining regions, created lazily.
   */
  public final Cache getCache() {
    return getCache(false);
  }

  public final Cache getCache(CacheFactory cf) {
    return getCache(false, cf);
  }

  public final Cache getCache(boolean client) {
    return getCache(client, null);
  }

  public final Cache getCache(boolean client, CacheFactory cf) {
    synchronized (CacheTestCase.class) {
      final GemFireCacheImpl gfCache = GemFireCacheImpl.getInstance();
      if (gfCache != null && !gfCache.isClosed()
          && gfCache.getCancelCriterion().cancelInProgress() != null) {
        waitForCriterion(new WaitCriterion() {

          public boolean done() {
            return gfCache.isClosed();
          }

          public String description() {
            return "waiting for cache to close";
          }
        }, 30 * 1000, 300, true);
      }
      if (cache == null || cache.isClosed()) {
        cache = null;
        createCache(client, cf);
      }
      if (client && cache != null) {
        addExpectedException("java.net.ConnectException");
      }
      return cache;
    }
  }

  /**
   * creates a client cache from the factory if one does not already exist
   * @since 6.5
   * @param factory
   * @return the client cache
   */
  public final ClientCache getClientCache(ClientCacheFactory factory) {
    synchronized (CacheTestCase.class) {
      final GemFireCacheImpl gfCache = GemFireCacheImpl.getInstance();
      if (gfCache != null && !gfCache.isClosed()
          && gfCache.getCancelCriterion().cancelInProgress() != null) {
        waitForCriterion(new WaitCriterion() {

          public boolean done() {
            return gfCache.isClosed();
          }

          public String description() {
            return "waiting for cache to close";
          }
        }, 30 * 1000, 300, true);
      }
      if (cache == null || cache.isClosed()) {
        cache = null;
        disconnectFromDS();
        cache = (Cache)factory.create();
      }
      if (cache != null) {
        addExpectedException("java.net.ConnectException");
      }
      return (ClientCache)cache;
    }
  }

  /**
   * same as {@link #getCache()} but with casting
   */
  public final GemFireCacheImpl getGemfireCache() {
    return (GemFireCacheImpl)getCache();
  }
  public static synchronized final boolean hasCache() {
      return cache != null;
  }

  /**
   * Return current cache without creating one.
   */
  public static synchronized final Cache basicGetCache() {
      return cache;
  }

  public static synchronized void disconnectFromDS() {
    closeCache();
    DistributedTestCase.disconnectFromDS();
  }

  /** Close the cache */
  public static synchronized void closeCache() {
    //Workaround for that fact that some classes are now extending
    //CacheTestCase but not using it properly.
    if(cache == null) {
      cache = GemFireCacheImpl.getInstance();
    }
    try {
    if (cache != null) {
      try {
        if (!cache.isClosed()) {
          if (cache instanceof GemFireCacheImpl) {
            CacheTransactionManager txMgr = ((GemFireCacheImpl)cache).getTxManager();
            if (txMgr != null) {
              if (txMgr.exists()) {
                try {
                  // make sure we cleanup this threads txid stored in a thread local
                  txMgr.rollback();
                }catch(Exception ignore) {

                }
              }
            }
          }
          try {
            cache.close();
          }
          catch (VirtualMachineError e) {
            SystemFailure.initiateFailure(e);
            throw e;
          }
          catch (Throwable t) {
          }
          finally {
          }
        }
        // @todo darrel: destroy DiskStore files
      }
      finally {
        cache = null;
      }
    } // cache != null
    } finally {
      //Make sure all pools are closed, even if we never
      //created a cache
      PoolManager.close(false);
    }
  }

  /** Closed the cache in all VMs. */
  protected void closeAllCache() {
    closeCache();
    invokeInEveryVM(CacheTestCase.class, "closeCache");
  }

  @Override
  public void tearDown2() throws Exception {
    // locally destroy all root regions and close the cache
    remoteTearDown();
    // Now invoke it in every VM
    for (int h = 0; h < Host.getHostCount(); h++) {
      Host host = Host.getHost(h);
      for (int v = 0; v < host.getVMCount(); v++) {
        VM vm = host.getVM(v);
        vm.invoke(CacheTestCase.class, "remoteTearDown");
      }
    }
    super.tearDown2();
  }

  /**
   * Local destroy all root regions and close the cache.
   */
  protected synchronized static void remoteTearDown() {
    try {
      DistributionMessageObserver.setInstance(null);
      if (cache != null && !cache.isClosed()) {
        //try to destroy the root regions first so that
        //we clean up any persistent files.
        for (Iterator itr = cache.rootRegions().iterator(); itr.hasNext();) {
          Region root = (Region)itr.next();
//          String name = root.getName();
          //for colocated regions you can't locally destroy a partitioned
          //region.
	  if(root.isDestroyed() || root instanceof HARegion || root instanceof PartitionedRegion) {
            continue;
          }
          try {
            root.localDestroyRegion("teardown");
          }
          catch (VirtualMachineError e) {
            SystemFailure.initiateFailure(e);
            throw e;
          }
          catch (Throwable t) {
            getLogWriter().error(t);
          }
        }
      }
    }
    finally {
      try {
        closeCache();
      }
      catch (VirtualMachineError e) {
        SystemFailure.initiateFailure(e);
        throw e;
      }
      catch (Throwable t) {
        getLogWriter().error("Error in closing the cache ", t);

      }
    }

    try {
      cleanDiskDirs();
    } catch(IOException e) {
      getLogWriter().error("Error cleaning disk dirs", e);
    }
  }

  /**
   * Returns a region with the given name and attributes
   */
  public final Region createRegion(String name,
                                      RegionAttributes attrs)
    throws CacheException {
    return createRegion(name, "root", attrs);
  }

  /**
   * Provide any internal region arguments, typically required when
   * internal use (aka meta-data) regions are needed.
   * @return internal arguements, which may be null.  If null, then default
   * InternalRegionArguments are used to construct the Region
   */
  public InternalRegionArguments getInternalRegionArguments()
  {
    return null;
  }

  final public Region createRegion(String name, String rootName,
                                      RegionAttributes attrs)
    throws CacheException {
    Region root = getRootRegion(rootName);
    if (root == null) {
      // don't put listeners on root region
      RegionAttributes rootAttrs = attrs;
      AttributesFactory fac = new AttributesFactory(attrs);
      ExpirationAttributes expiration = ExpirationAttributes.DEFAULT;

      // fac.setCacheListener(null);
      fac.setCacheLoader(null);
      fac.setCacheWriter(null);
      fac.setPoolName(null);
      fac.setPartitionAttributes(null);
      fac.setRegionTimeToLive(expiration);
      fac.setEntryTimeToLive(expiration);
      fac.setRegionIdleTimeout(expiration);
      fac.setEntryIdleTimeout(expiration);
      rootAttrs = fac.create();
      root = createRootRegion(rootName, rootAttrs);
    }

    InternalRegionArguments internalArgs = getInternalRegionArguments();
    if (internalArgs == null) {
      return root.createSubregion(name, attrs);
    } else {
      try {
        LocalRegion lr = (LocalRegion) root;
        return lr.createSubregion(name, attrs, internalArgs);
      } catch (IOException ioe) {
        AssertionError assErr = new AssertionError("unexpected exception");
        assErr.initCause(ioe);
        throw assErr;
      } catch (ClassNotFoundException cnfe) {
        AssertionError assErr = new AssertionError("unexpected exception");
        assErr.initCause(cnfe);
        throw assErr;
      }
    }
  }

  public final Region getRootRegion() {
    return getRootRegion("root");
  }

  public final Region getRootRegion(String rootName) {
    return getCache().getRegion(rootName);
  }

  protected final Region createRootRegion(RegionAttributes attrs)
  throws RegionExistsException, TimeoutException {
    return createRootRegion("root", attrs);
  }

  public final Region createRootRegion(String rootName, RegionAttributes attrs)
  throws RegionExistsException, TimeoutException {
    return getCache().createRegion(rootName, attrs);
  }

  /**
   * send an unordered message requiring an ack to all connected members
   * in order to flush the unordered communication channel
   */
  public void sendUnorderedMessageToAll() {
    //if (getCache() instanceof distcache.gemfire.GemFireCacheImpl) {
      try {
        com.gemstone.gemfire.distributed.internal.HighPriorityAckedMessage msg = new com.gemstone.gemfire.distributed.internal.HighPriorityAckedMessage();
        msg.send(InternalDistributedSystem.getConnectedInstance().getDM().getNormalDistributionManagerIds(), false);
      }
      catch (Exception e) {
        throw new RuntimeException("Unable to send unordered message due to exception", e);
      }
    //}
  }

  /**
   * send an unordered message requiring an ack to all connected admin members
   * in order to flush the unordered communication channel
   */
//  public void sendUnorderedMessageToAdminMembers() {
//    //if (getCache() instanceof distcache.gemfire.GemFireCacheImpl) {
//      try {
//        com.gemstone.gemfire.distributed.internal.HighPriorityAckedMessage msg = new com.gemstone.gemfire.distributed.internal.HighPriorityAckedMessage();
//        msg.send(DistributedSystemHelper.getAdminMembers(), false);
//      }
//      catch (Exception e) {
//        throw new RuntimeException("Unable to send unordered message due to exception", e);
//      }
//    //}
//  }

  /**
   * send an ordered message requiring an ack to all connected members
   * in order to flush the ordered communication channel
   */
  public void sendSerialMessageToAll() {
    if (getCache() instanceof GemFireCacheImpl) {
      try {
        com.gemstone.gemfire.distributed.internal.SerialAckedMessage msg = new com.gemstone.gemfire.distributed.internal.SerialAckedMessage();
        msg.send(InternalDistributedSystem.getConnectedInstance().getDM().getNormalDistributionManagerIds(), false);
      }
      catch (Exception e) {
        throw new RuntimeException("Unable to send serial message due to exception", e);
      }
    }
  }

  /**
   * @deprecated Use DistributedTestCase.addExpectedException
   */
  @Deprecated
  protected CacheSerializableRunnable addExceptionTag1(final String expectedException) {
    CacheSerializableRunnable addExceptionTag = new CacheSerializableRunnable(
    "addExceptionTag") {
      public void run2()
      {
        getCache().getLogger().info(
            "<ExpectedException action=add>" + expectedException
            + "</ExpectedException>");
      }
    };

    return addExceptionTag;
  }

  /**
   * @deprecated Use DistributedTestCase.addExpectedException
   */
  @Deprecated
  protected CacheSerializableRunnable removeExceptionTag1(final String expectedException) {
    CacheSerializableRunnable removeExceptionTag = new CacheSerializableRunnable(
    "removeExceptionTag") {
      public void run2() throws CacheException {
        getCache().getLogger().info(
            "<ExpectedException action=remove>" + expectedException
            + "</ExpectedException>");
      }
    };
    return removeExceptionTag;
  }

  /**
   * Used to generate a cache.xml. Basically just a CacheCreation
   * with a few more methods implemented.
   */
  static class TestCacheCreation extends CacheCreation {
    private boolean closed = false;
    @Override
    public void close() {
      this.closed = true;
    }
    @Override
    public boolean isClosed() {
      return this.closed;
    }
  }

  public static File getDiskDir() {
    int vmNum = VM.getCurrentVMNum();
    File dir = new File("diskDir", "disk" + String.valueOf(vmNum)).getAbsoluteFile();
    dir.mkdirs();
    return dir;
  }

  /**
   * Return a set of disk directories
   * for persistence tests. These directories
   * will be automatically cleaned up
   * on test case closure.
   */
  public static File[] getDiskDirs() {
    return new File[] {getDiskDir()};
  }

  public static void cleanDiskDirs() throws IOException {
    FileUtil.delete(getDiskDir());
    File[] defaultStoreFiles = new File(".").listFiles(new FilenameFilter() {

      public boolean accept(File dir, String name) {
        return name.startsWith("BACKUPDiskStore-" + System.getProperty("vmid"));
      }
    });

    for(File file: defaultStoreFiles) {
      FileUtil.delete(file);
    }
  }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System;
using System.Collections.Immutable;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using AnalyzerRunner;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Diagnosers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.MSBuild;

namespace IdeCoreBenchmarks
{
    [MemoryDiagnoser]
    [RyuJitX64Job]
    public class CSharpIdeAnalyzerBenchmarks
    {
        private readonly string _solutionPath;

        private Options _options;
        private MSBuildWorkspace _workspace;

        private DiagnosticAnalyzerRunner _diagnosticAnalyzerRunner;

        [Params("CSharpAddBracesDiagnosticAnalyzer")]
        public string AnalyzerName { get; set; }

        public CSharpIdeAnalyzerBenchmarks()
        {
            var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName);
            _solutionPath = Path.Combine(roslynRoot, @"src\Tools\IdeCoreBenchmarks\Assets\Microsoft.CodeAnalysis.sln");

            if (!File.Exists(_solutionPath))
            {
                throw new ArgumentException();
            }
        }

        [GlobalSetup]
        public void Setup()
        {
            var analyzerAssemblyPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Microsoft.CodeAnalysis.CSharp.Features.dll");

            _options = new Options(
                analyzerPath: analyzerAssemblyPath,
                solutionPath: _solutionPath,
                analyzerIds: ImmutableHashSet.Create(AnalyzerName),
                refactoringNodes: ImmutableHashSet<string>.Empty,
                runConcurrent: true,
                reportSuppressedDiagnostics: true,
                applyChanges: false,
                useAll: false,
                iterations: 1,
                usePersistentStorage: false,
                fullSolutionAnalysis: false,
                incrementalAnalyzerNames: ImmutableArray<string>.Empty);

            _workspace = AnalyzerRunnerHelper.CreateWorkspace();
            _diagnosticAnalyzerRunner = new DiagnosticAnalyzerRunner(_workspace, _options);

            _ = _workspace.OpenSolutionAsync(_solutionPath, progress: null, CancellationToken.None).Result;
        }

        [GlobalCleanup]
        public void Cleanup()
        {
            _workspace?.Dispose();
            _workspace = null;
        }

        [Benchmark]
        public async Task RunAnalyzer()
        {
            await _diagnosticAnalyzerRunner.RunAsync(CancellationToken.None).ConfigureAwait(false);
        }
    }
}


text:
<?php
namespace Puppy;

use Pimple\Container;
use Puppy\Controller\FrontController;
use Puppy\Helper\Retriever;
use Puppy\Module\ModulesLoader;
use Puppy\Module\ModulesLoaderProxy;
use Puppy\Route\Router;
use Stash\Pool;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class ApplicationTest
 * @package Puppy
 * @author Raphaël Lefebvre <raphael@raphaellefebvre.be>
 */
class ApplicationTest extends \PHPUnit_Framework_TestCase
{
    private $cwd;

    public function setUp()
    {
        $this->cwd = getcwd();
        chdir(__DIR__ . '/resources');
    }

    public function tearDown()
    {
        chdir($this->cwd);
    }

    public function testRun()
    {
        $application = new Application(new \ArrayObject(), new Request());
        $application->any('', function(){ return 'this is great!'; });

        ob_start();
        $application->run();
        $this->assertSame('this is great!', ob_get_clean());
    }

    public function testRunWithoutController()
    {
        $application = new Application(new \ArrayObject(), new Request());
        $this->setExpectedException('Puppy\Route\RouteException', 'No route found for uri ""');
        $application->run();
    }

    public function testAny()
    {
        $controller = function(){};

        $application = new Application(new \ArrayObject(), new Request());
        $application->any('pattern', $controller);

        /**
         * @var Router $router
         */
        $router = $application->getServices()['router'];
        $route = $router->getRoutes()[0];
        $this->assertSame('pattern', $route->getPattern()->getUri());
        $this->assertSame('', $route->getPattern()->getMethod());
        $this->assertSame('', $route->getPattern()->getContentType());
    }

    public function testAnyWithAdditionalFilter()
    {
        $controller = function(){};

        $application = new Application(new \ArrayObject(), new Request());
        $application->any('pattern', $controller)->method('method')->content('content');

        /**
         * @var Router $router
         */
        $router = $application->getServices()['router'];
        $route = $router->getRoutes()[0];
        $this->assertSame('pattern', $route->getPattern()->getUri());
        $this->assertSame('METHOD', $route->getPattern()->getMethod());
        $this->assertSame('content', $route->getPattern()->getContentType());
    }

    public function testGet()
    {
        $controller = function(){};

        $application = new Application(new \ArrayObject(), new Request());
        $application->get('pattern', $controller);

        /**
         * @var Router $router
         */
        $router = $application->getServices()['router'];
        $route = $router->getRoutes()[0];
        $this->assertSame('pattern', $route->getPattern()->getUri());
        $this->assertSame('GET', $route->getPattern()->getMethod());
        $this->assertSame('', $route->getPattern()->getContentType());
    }

    public function testGetWithAdditionalFilter()
    {
        $controller = function(){};

        $application = new Application(new \ArrayObject(), new Request());
        $application->get('pattern', $controller)->method('method')->content('content');

        /**
         * @var Router $router
         */
        $router = $application->getServices()['router'];
        $route = $router->getRoutes()[0];
        $this->assertSame('pattern', $route->getPattern()->getUri());
        $this->assertSame('METHOD', $route->getPattern()->getMethod());
        $this->assertSame('content', $route->getPattern()->getContentType());
    }

    public function testPost()
    {
        $controller = function(){};

        $application = new Application(new \ArrayObject(), new Request());
        $application->post('pattern', $controller);

        /**
         * @var Router $router
         */
        $router = $application->getServices()['router'];
        $route = $router->getRoutes()[0];
        $this->assertSame('pattern', $route->getPattern()->getUri());
        $this->assertSame('POST', $route->getPattern()->getMethod());
        $this->assertSame('', $route->getPattern()->getContentType());
    }

    public function testPostWithAdditionalFilter()
    {
        $controller = function(){};

        $application = new Application(new \ArrayObject(), new Request());
        $application->post('pattern', $controller)->method('method')->content('content');

        /**
         * @var Router $router
         */
        $router = $application->getServices()['router'];
        $route = $router->getRoutes()[0];
        $this->assertSame('pattern', $route->getPattern()->getUri());
        $this->assertSame('METHOD', $route->getPattern()->getMethod());
        $this->assertSame('content', $route->getPattern()->getContentType());
    }

    public function testJson()
    {
        $controller = function(){};

        $application = new Application(new \ArrayObject(), new Request());
        $application->json('pattern', $controller);

        /**
         * @var Router $router
         */
        $router = $application->getServices()['router'];
        $route = $router->getRoutes()[0];
        $this->assertSame('pattern', $route->getPattern()->getUri());
        $this->assertSame('', $route->getPattern()->getMethod());
        $this->assertSame('application/json', $route->getPattern()->getContentType());
    }

    public function testJsonWithAdditionalFilter()
    {
        $controller = function(){};

        $application = new Application(new \ArrayObject(), new Request());
        $application->json('pattern', $controller)->method('method')->content('content');

        /**
         * @var Router $router
         */
        $router = $application->getServices()['router'];
        $route = $router->getRoutes()[0];
        $this->assertSame('pattern', $route->getPattern()->getUri());
        $this->assertSame('METHOD', $route->getPattern()->getMethod());
        $this->assertSame('content', $route->getPattern()->getContentType());
    }

    public function testFilter()
    {
        $filter = function(){};
        $controller = function(){};

        $application = new Application(new \ArrayObject(), new Request());
        $application->filter($filter, $controller)->method('method')->content('content');

        /**
         * @var Router $router
         */
        $router = $application->getServices()['router'];
        $route = $router->getRoutes()[0];
        $this->assertSame(':all', $route->getPattern()->getUri());
        $this->assertSame('METHOD', $route->getPattern()->getMethod());
        $this->assertSame('content', $route->getPattern()->getContentType());
        $this->assertSame([$filter], $route->getPattern()->getFilters());
    }

    public function testFilterWithAdditionalFilter()
    {
        $filter = function(){};
        $controller = function(){};

        $application = new Application(new \ArrayObject(), new Request());
        $application->filter($filter, $controller);

        /**
         * @var Router $router
         */
        $router = $application->getServices()['router'];
        $route = $router->getRoutes()[0];
        $this->assertSame(':all', $route->getPattern()->getUri());
        $this->assertSame('', $route->getPattern()->getMethod());
        $this->assertSame('', $route->getPattern()->getContentType());
        $this->assertSame([$filter], $route->getPattern()->getFilters());
    }

    public function testInitModules()
    {
        $this->assertTrue(empty($GLOBALS['module_mock_init_1']));
        $this->assertTrue(empty($GLOBALS['module_mock_init_2']));

        $application = new Application(new \ArrayObject(), new Request());
        $application->initModules(new ModulesLoader());

        $this->assertFalse(empty($GLOBALS['module_mock_init_1']));
        $this->assertFalse(empty($GLOBALS['module_mock_init_2']));

        unset($GLOBALS['module_mock_init_1']);
        $this->assertTrue(empty($GLOBALS['module_mock_init_1']));

        unset($GLOBALS['module_mock_init_2']);
        $this->assertTrue(empty($GLOBALS['module_mock_init_2']));
    }

    public function testInitModulesWithoutExistingDir()
    {
        $this->assertTrue(empty($GLOBALS['module_mock_init_1']));
        $this->assertTrue(empty($GLOBALS['module_mock_init_2']));

        $application = new Application(new \ArrayObject(), new Request());
        $application->initModules(new ModulesLoader(['foo']));

        $this->assertTrue(empty($GLOBALS['module_mock_init_1']));
        $this->assertTrue(empty($GLOBALS['module_mock_init_2']));
    }

    public function testInitModulesWithProxy()
    {
        $this->assertTrue(empty($GLOBALS['module_mock_init_1']));
        $this->assertTrue(empty($GLOBALS['module_mock_init_2']));

        $application = new Application(new \ArrayObject(), new Request());
        $application->initModules(new ModulesLoaderProxy(new ModulesLoader(), new Pool()));

        $this->assertFalse(empty($GLOBALS['module_mock_init_1']));
        $this->assertFalse(empty($GLOBALS['module_mock_init_2']));

        unset($GLOBALS['module_mock_init_1']);
        $this->assertTrue(empty($GLOBALS['module_mock_init_1']));

        unset($GLOBALS['module_mock_init_2']);
        $this->assertTrue(empty($GLOBALS['module_mock_init_2']));
    }

    /**
     *
     */
    public function testAddModule()
    {

        $application = new Application(new \ArrayObject(), new Request());

        $module = $this->getMockBuilder('\Puppy\resources\ModuleMock')->getMock();
        $module->expects($this->once())
            ->method('init')
            ->with($application);

        $application->addModule($module);
    }

    /**
     *
     */
    public function testAddService()
    {
        $services = new Container();

        $application = new Application(new \ArrayObject(), new Request(), $services);
        $application->addService(
            'service1',
            function () {
                return 'value1';
            }
        );
        $this->assertSame('value1', $services['service1']);
    }

    /**
     *
     */
    public function testGetServiceWithService()
    {
        $services = new Container();

        $application = new Application(new \ArrayObject(), new Request(), $services);
        $application->addService(
            'service1',
            function () {
                return 'value1';
            }
        );
        $this->assertSame('value1', $application->getService('service1'));
    }

    /**
     *
     */
    public function testGetServiceWithoutService()
    {
        $services = new Container();
        $application = new Application(new \ArrayObject(), new Request(), $services);

        $this->setExpectedException('\InvalidArgumentException', 'Service service1 not found');
        $application->getService('service1');
    }

    public function testAddAppControllerToServices()
    {

        $services = new Container();
        new Application(new \ArrayObject(), new Request(), $services);

        $this->assertArrayHasKey('appController', $services);
        $this->assertInstanceOf('Puppy\Controller\AppController', $services['appController']);
    }

    public function testRequestService()
    {
        $this->expectOutputString('mastermaster');

        //define the master request

        $masterRequest = new Request();
        $masterRequest->server->set('REQUEST_URI', 'master');
        $masterRequest->request->set('request', 'master');

        $application = new Application(new \ArrayObject(), $masterRequest);
        $application->any(':all', function(Request $request, Retriever $retriever){
            $retriever->setLocalVars(['local' => $request->getRequestUri()]);
            return $request->getRequestUri();
        });

        $this->assertSame($masterRequest, $application->getService('request'));
        $application->run(); //expect first "master" output
        $this->assertSame('master', $application->getService('retriever')->get('request'));
        $this->assertSame('master', $application->getService('retriever')->get('local'));

        //define another current request

        $currentRequest = new Request();
        $currentRequest->server->set('REQUEST_URI', 'current');
        $currentRequest->request->set('request', 'current');

        /**
         * @var FrontController $frontController
         */
        $frontController = $application->getService('frontController');
        $response = $frontController->call($currentRequest);

        $this->assertSame($currentRequest, $application->getService('request'));
        $this->assertSame('current', $response->getContent());
        $this->assertSame('current', $application->getService('retriever')->get('request'));
        $this->assertSame('current', $application->getService('retriever')->get('local'));
        $application->run(); //expect second "master" output
    }

    public function testCallWithNewRequest()
    {
        $masterRequest = new Request();
        $masterRequest->server->set('REQUEST_URI', '1');

        $application = new Application(new \ArrayObject(), $masterRequest);

        $application->any('1', function(FrontController $frontController){
            $currentRequest = new Request();
            $currentRequest->server->set('REQUEST_URI', '2');
            return $frontController->call($currentRequest);
        });

        $application->any('2', function(Request $request, RequestStack $requestStack){
            return $requestStack->getMasterRequest()->getRequestUri()
                . '-' . $requestStack->getCurrentRequest()->getRequestUri()
                . '-' . $request->getRequestUri();
        });

        $this->expectOutputString('1-2-2');
        $application->run();
    }

    public function testMirror()
    {
        $masterRequest = new Request();
        $masterRequest->server->set('REQUEST_URI', 'mail');

        $application = new Application(new \ArrayObject(), $masterRequest);
        $application->mirror('mail', 'contact');
        $application->get('contact', function(Request $request){
            return $request->getRequestUri();
        });

        $this->expectOutputString('contact');
        $application->run();
    }

    public function testMirrorWithParams()
    {
        $masterRequest = new Request();
        $masterRequest->server->set('REQUEST_URI', 'mail/123/456');

        $application = new Application(new \ArrayObject(), $masterRequest);
        $application->mirror('mail/:id/:index', 'contact/{id}/{id}');
        $application->get('contact/:id/:index', function(Request $request){
            return $request->getRequestUri();
        });

        $this->expectOutputString('contact/123/123');
        $application->run();
    }

    public function testGroup()
    {
        $masterRequest = new Request();
        $masterRequest->server->set('REQUEST_URI', 'mail/123/456');

        $application = new Application(new \ArrayObject(), $masterRequest);

        $application->group(
            [
                $application->get(
                    'uri1',
                    function (Request $request) {
                        return $request->getRequestUri();
                    }
                ),
                $application->get(
                    'uri2',
                    function (Request $request) {
                        return $request->getRequestUri();
                    }
                ),
            ]
        )
            ->restrict('admin');

        $routes = $application->getService('router')->getRoutes();
        $this->assertCount(2, $routes);
        $this->assertSame('admin/uri1', $routes[0]->getPattern()->getUri());
        $this->assertSame('admin/uri2', $routes[1]->getPattern()->getUri());
    }

    public function testBefore()
    {
        $masterRequest = new Request();
        $masterRequest->server->set('REQUEST_URI', 'uri1');

        $application = new Application(new \ArrayObject(), $masterRequest);

        $application->get(':all', function(Request $request){
            return $request->getRequestUri();
        });

        $application->before(function(Request $request){
            $request->server->set('REQUEST_URI', 'uri2');
        });

        $this->expectOutputString('uri2');
        $application->run();
    }

    public function testAfter()
    {
        $masterRequest = new Request();
        $masterRequest->server->set('REQUEST_URI', 'uri1');

        $application = new Application(new \ArrayObject(), $masterRequest);

        $application->get(':all', function(Request $request){
            return $request->getRequestUri();
        });

        $application->after(function(Response $response){
            $response->setContent('uri2');
        });

        $this->expectOutputString('uri2');
        $application->run();
    }
}


text:
{% load static %}

## Table of Contents

1. Getting Started
2. Prerequisites
3. Analysing Your Data
4. Creating an Experiment
5. Summary Page
6. Mass2Motif Matching
7. Interactive Network Visualisation
8. Combining MS1 Differential Expression or Prevalence with MS2LDA

---

#### 1. Getting Started

To log into MS2lda.org, you need to create an account. However, a guest account is also available to explore the system
without registration. Functionalities are available for most experiments to allow for browsing through example data
sets. However, to create your own experiment, you will need to request an account to ensure that your data is visible to
you and collaborators of your choice.

The following experiments are automatically linked to your account for browsing and exploration:

gnps_binned_005: Mass2Motifs discovered from MS/MS spectra from 5770 GNPS standards (positive ionization mode) with many annotated Mass2Motifs. Guest users have viewing access to this.

massbank_binned_005: Mass2Motifs discovered from MS/MS spectra from 2132 MassBank standards (positive ionization mode) including annotated Mass2Motifs.

Beer6_POS_IPA_MS1_comparisons: Mass2Motifs discovered from MS/MS spectra from an IPA Beer (positive ionization mode). An MS1 analysis comparing IPA beers versus non-IPA beers is available for visualization.

---

#### 2. Prerequisites

To analyse your data in Ms2lda.org, you first need:

1. Your fragmentation data in mzML, MSP or MGF formats
2. A list of MS1 peaks (optional). When fragmentation data in mzML format is provided, this list will be used to seed
   the MS1 peaks during feature extraction so only peaks that match the MS1 list within certain m/z and RT tolerances
   will be used.

Once you have these available, from the Experiment screen, click on the **Create Experiment** button, shown
in (A) below. A screen will appear asking you to upload your data and define
the parameters for feature extraction and inference (see Section 4 for more details). Upon clicking submit, the
experiment will be processed in a job queue. While processing, it is also shown in the list of **Pending Experiments**,
shown in (B) below. Submitted experiments will go 'pending' till they are
finished. Depending on the size of the data and if any other experiments are running, it might take from a few hours
till some longer to finish. Completed experiments are listed on the main page.

---

#### 3. Analysing Your Data

Once processed, LDA experiments (where substructures are discovered in an unsupervised manner) can be found in the list
of LDA experiments. Experiments that are editable are shown in **bold** in the list, while read-only experiments are
shown in normal font weight. Clicking an experiment will expand it into tabs, where additional functionalities can be
selected.

The following functionalities are available for an LDA experiment:

- **Summary Page**: displays a summary of key results in the data, including extracted fragment and loss features,
  discovered Mass2Motifs and spectra that can be explained by these motifs. This is advised to be your first place of
  exploring MS2LDA results.
- **Show Fragmentation Spectra**:  displays the fragmentation spectra in the data, alongside Mass2Motifs that explain
  the features in those spectra.
- **Show Mass2Motifs**: diplays discovered Mass2Motifs.
- **View Experiment Options**: displays a list of configurable options when performing motif matching and visualisating
  the data.
- **Create MS1 Analysis**: if MS1 data is provided, this allows you to create MS1 analysis of case vs. control study
  where the differential prevalence of Mass2Motifs can be compared and visualised.
- **Start Motif Matching**: performs the matching of discovered Mass2Motifs for this data against Mass2Motifs from
  another data. This allows for quick annotations.
- **Manage Motif Matches**: once started, motif matching will run in the background. The results will be shown here and
  can be updated.
- **Start Visualisation**: allows you to visualise Mass2Motifs and fragmentation spectra in a network graph.

Most of these pages including the visualisation have an excellent **Search Function** where Mass2Motifs, Mass2Motif
annotations, and/or parent ions can be quickly and convienently found.

The following sections describe all the functionalities of Ms2lda.org in greater details:

---

#### 4. Creating an Experiment

To upload your own data, please take care to select and submit the correct format and also to fill out the correct
filters for RT and mass intensities in MS1 and MS2 [the defaults are suitable only for Thermo Q-Exactive spectral files]
. Inclusion of noise does not contribute to the substructure discovery, and will make the LDA process running much
slower. Thus, it is very important to check the noise level in your data and modify the minimum MS2 level to include
accordingly. For example, ToF-based machines generate spectra with noise levels typically around 100 a.u. - whereas the
default is set to 5000 for QExactive spectra. We would recommend to, if possible, submit a small subset of the data to
check if things complete as expected. If you have MS1 peak information available, we also advise to run MS2LDA first
without MS1 peak csv to ensure that this is working okay before trying to format the MS1 peak file format correctly and
submitting it along.

If you upload an MS1 peak list with one or multiple files, then those peaks will be used to match the extracted MS1-MS2
pairs to according to thresholds you can put. Please check the website for requirements of the MS1 peak file. One
experiments that you can view contains examples of MS1 comparisons that you then can do to find Mass2Motifs that contain
discriminative metabolites between two groups. Please also note that the MS2 masses are by default binned in 0.005 Da
bins, so please be aware that the masses displayed for them are no longer 'accurate' masses. There is an option now to
choose for different bin sizes in case that is more appropriate for the data.

The following is a walkthrough on how to create your own experiment. Firstly click on **Create Experiment** and give it
an experiment name and a description. Then select the format of the MS2 fragmentation file (either .mzML or .MSP or
.MGF). Finally, upload the fragmentation file in the correct format in the file selector.

Depending on your choice of fragmentation file format, different fields will be shown to configure filtering and feature
extraction parameters. For fragmentation data in .mzML format, the parameters are:

- **Fragmentation isolation window** should be adjusted based on your instrument settings.
- **Mass and retention time tolerances when linking peaks** are only used when the MS1 peaklist is provided. The default
  values should work reasonably well.
- **Minimum and maximum retention time and intensity of MS1 peaks** are used to filter the data. Make sure to adjust
  them based on your instrument settings.
- **Attempt to filter out duplicate MS1 peaks** are used to merge peaks within the specified mass and RT tolerance
  windows.

For fragmentation data in .MSP or .MGF format, the parameters are:

- **Minimum intensity of MS1 peaks to store** is used to filter MS1 peaks by the specified minimum intensity value.
- **Minimum intensity of MS2 peaks to store** is used to filter MS2 peaks by the specified minimum intensity value.

For all formats, the following parameters for LDA inference have to be specified:

- **Number of Mass2Motifs**: specifies the number of Mass2Motifs (topics) to infer in the LDA alrogithm. Based on our
  experience, a value between 300 - 500 are usually sufficient.
- **Number of iterations (for LDA)**:  specifies the number of steps to perform during variational inference. The
  default value of 1000 is usually enough.

Finally press the **Submit Your Experiment** button to submit the experiment. Upon job completion, the experiments that
are in your account now you can view, the ones you will upload yourself you can edit as well – and thus start to
annotate your Mass2Motifs from an LDA run. To help you on the way, you can perform Motif-matching to previously run
experiments. You can find all these functionalities once you click on a finished experiment.

---

#### 5. Summary Page

A good start to exploring LDA results is through the **Summary Page** which shows all the key results for your dataset.
From here you can get a clue of how much spectra are in each Mass2Motif so you can set a reasonable threshold for the
visualization of the network (minimum degree – if put too high, not many data will be displayed). One of the tabs is
called "View Experiment options" - here you can set the thresholds for a fragmented spectrum (document) to belong to a
Mass2Motif. In our experience, a probability threshold of 0.1 and an overlap threshold of 0.3 is a good starting point
to explore the data. By default, both are set at 0.05. A final note on this is that the MS2LDA model requires all
fragmented spectra to be part of at least one Mass2Motif. Therefore, in some cases, fragmented molecules might have a
very high probability but very low overlap with the Mass2Motif - this happens to molecules that have a unique
fragmentation spectrum compared to all other spectra in the data set.

In particular from the Summary page, the discovered Mass2Motifs can be studied and annotated from the Summary Page by
clicking Mass2Motif in the **Mass2Motif Details** table of the Summary Page. The Table contains the degrees and
annotations (if there). When clicking on a Mass2Motif link, details on the selected Mass2Motif are shown. Annotation can
also be assigned from this screen. In the example below, we assign the annotation "Histidine substructure" to this
Mass2Motifs based on the top fragments (110.07176, 156.07684, etc) shown in the table. The Mass2Motifs can also be
assessed through the **Show Mass2Motifs Page**.

---

#### 6. Mass2Motif Matching

For quick annotations of a large number of Mass2Motifs, manual annotation can be tedious. The motif matching
functionality can be used to speed up this process. This functionality is launched from the **Start Motif Matching**
link from the functionality tabs of an experiment. Matching is performed based on the cosine similarity, which is
specified as a user-configurable option. To begin motif matching, select a motifset to match against and specify the
minimum cosine similarity score to select candidate matches. Click the **Start matching** button.

Matching will be performed in the background. Upon completion, match results will be shown in the **Manage Motif
Matches** screen, as shown below. The first column shows the original Mass2Motifs discovered in this dataset. The second
and third columns show the best match Mass2Motifs (according to cosine similarity) in the target dataset. The match
score is shown in the next column. Clicking **Add Link** will create a link between the pair of Mass2Motifs,
transferring their annotations from the matched to the original Mass2Motif. It is important to realize that if the
matched annotation changes, so will the annotation of the linked Mass2Motif.

---

#### 7. Interactive Network Visualisation

Interactive visualisation can be launched from the **Start Visualisation** link from the functionality tabs of an
experiment. The minimum degree is the minimum threshold to set to draw an edge connecting a Mass2Motifs to adjacent
spectra that can be explained by that Mass2Motif, e.g. a value of 5 means edges are drawn only when a Mass2Motif is
connected to 5 spectra (at the specified threshold in the experiment option). Please note that if all Mass2Motifs
contain more than 5 spectra, the network might take a while to load and we advise users to higher the minimum degree for
interactive network visualisation.

The next screen shows the interactive visualisation. Circles are Mass2Motifs, while squares are spectra (fragmented
metabolites). If the network appears as a small pile of circles, please use the left-click mouse to select a Mass2Motif
and drag it slightly away from the pile - the network will 'explode' as result. The network can be enlarged or made
smaller by zooming in or out using the mouse wheel or a similar action. Selecting (double-clicking on) a Mass2Motif in
the network will display more information in other panels, including the fragmentation spectra that are explained by
this motif and the counts of occurrences of this motif amongst the spectra. Associated spectra (fragmented metabolites)
will be highlighted as well after selecting the Mass2Motif. Annotated Mass2Motifs will be coloured red in the network
and the annotations will be visible when hoovering over them with the mouse. Other Mass2Motifs will appear orange and
Mass2Motif numbers will appear when hoovering over them with the mouse. Similarly, information on the fragmented
metabolites including the precursor ion will appear when hoovering over the squares with the mouse. Motif nodes,
annotations, and fragmented ions in the network can also be searched through the search box at the top of the page and
subsequently quickly and convienently selected in the network.

---

#### 8. Combining MS1 Differential Expression or Prevalence with MS2LDA

Where available, MS1 analysis can be performed to map differential expression or prevalence of metabolites based on
their MS1 intensities. In order to do so, you will need to upload a CSV file that includes the fragmented sample. Please
look carefully at the requirements for the CSV file at the bottom of the **Create Experiment** page. Please also note
that this is currently possible alongside an mzml file only. During the preprocessing, the fragmented features of the
fragmentation mzml file will be matched to those present in the CSV file based on their m/z values and retention times,
so ensure that the retention times are comparable and that the m/z and retention time matching parameters are set
correctly. Once the MS1 features are matched, MS1 analysis can be done using the **Create MS1 analysis**. The list of
sample names is available in the middle of the page (see figure below), and after selection of samples (e.g., 5
treatment replicates of which one was fragmented) the arrows can be used to move the samples to group 1 on the left.
Similarly, group 2 (on the right) can be populated. A t-test comparative analysis is performed with group 1 over group

2.

In order to analyze the MS1 analysis, it needs to be mapped on the network in the visualisation page. After loading the
network in the visualisation page, the user can toggle **Show MS1 analysis in the network** at the left bottom of the
page which will change the appearance of the network (see Figure below). Now, Mass2Motifs are coloured green - the
greener they are, the more differential metabolites contain that particular Mass2Motif. Additionally, differential
metabolites are coloured (red is up, blue is down - the darker, the larger the fold change) and sized according to their
significance, the larger the significance. As in the regular network, users can click on Mass2Motifs to view the spectra
and other statistics. However, the Mass2Motif and/or number is now accompagnied by the PLAGE score (the higher, in the
more differential metabolites the Mass2Motif is present, independent on the direction of the fold change). The user can
return to the 'standard network view' by detoggling the **Show MS1 analysis in the network** option.


text:
<templateSet group="SQF">
	<template name="forspec" value="for [{$ITER_VAR$=$ITER_VAR_VAL$;},{$ITER_COND$},{$ITER_OPERATION$}] do {$END$};"
			  description="Create a for loop" toReformat="false" toShortenFQNames="true">
		<variable name="ITER_VAR" expression="" defaultValue="_i" alwaysStopAt="true"/>
		<variable name="ITER_VAR_VAL" expression="" defaultValue="0" alwaysStopAt="true"/>
		<variable name="ITER_COND" expression="" defaultValue="condition" alwaysStopAt="true"/>
		<variable name="ITER_OPERATION" expression="" defaultValue="_i=_i+1" alwaysStopAt="true"/>
		<context>
			<option name="SQF_CONTEXT" value="true"/>
		</context>
	</template>
</templateSet>


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">

  <title>Qt 4.3: Creating New Models</title>
  <link rel="prev" href="model-view-model.html" />
  <link rel="contents" href="model-view-programming.html" />
  <link rel="next" href="model-view-view.html" />
  <link href="classic.css" rel="stylesheet" type="text/css" />

  	Home · All Classes · Main Classes · Grouped Classes · Modules · Functions

[Previous: Model Classes]
[Contents]
[Next: View Classes]

Creating New Models

Introduction

Designing a Model

A Read-Only Example Model

Dimensions of The Model

Model Headers and Data

An Editable Model

Making the Model Editable

Inserting and Removing Rows

Next Steps

Introduction

The separation of functionality between the model/view components allows models to be created that can take advantage of existing views. This approach lets us present data from a variety of sources using standard graphical user interface components, such as QListView, QTableView, and QTreeView.

The QAbstractItemModel class provides an interface that is flexible enough to support data sources that arrange information in hierarchical structures, allowing for the possibility that data will be inserted, removed, modified, or sorted in some way. It also provides support for drag and drop operations.

The QAbstractListModel and QAbstractTableModel classes provide support for interfaces to simpler non-hierarchical data structures, and are easier to use as a starting point for simple list and table models.

In this chapter, we create a simple read-only model to explore the basic principles of the model/view architecture. Later in this chapter, we will adapt this simple model so that items can be modified by the user.

For an example of a more complex model, see the Simple Tree Model example.

The requirements of QAbstractItemModel subclasses is described in more detail in the Model Subclassing Reference document.

Designing a Model

When creating a new model for an existing data structure, it is important to consider which type of model should be used to provide an interface onto the data. If the data structure can be represented as a list or table of items, you can subclass QAbstractListModel or QAbstractTableModel since these classes provide suitable default implementations for many functions.

However, if the underlying data structure can only be represented by a hierarchical tree structure, it is necessary to subclass QAbstractItemModel. This approach is taken in the Simple Tree Model example.

In this chapter, we will implement a simple model based on a list of strings, so the QAbstractListModel provides an ideal base class on which to build.

Whatever form the underlying data structure takes, it is usually a good idea to supplement the standard QAbstractItemModel API in specialized models with one that allows more natural access to the underlying data structure. This makes it easier to populate the model with data, yet still enables other general model/view components to interact with it using the standard API. The model described below provides a custom constructor for just this purpose.

A Read-Only Example Model

The model implemented here is a simple, non-hierarchical, read-only data model based on the standard QStringListModel class. It has a QStringList as its internal data source, and implements only what is needed to make a functioning model. To make the implementation easier, we subclass QAbstractListModel because it defines sensible default behavior for list models, and it exposes a simpler interface than the QAbstractItemModel class.

When implementing a model it is important to remember that QAbstractItemModel does not store any data itself, it merely presents an interface that the views use to access the data. For a minimal read-only model it is only necessary to implement a few functions as there are default implementations for most of the interface. The class declaration is as follows:

 class StringListModel : public QAbstractListModel
 {
     Q_OBJECT

 public:
     StringListModel(const QStringList &strings, QObject *parent = 0)
         : QAbstractListModel(parent), stringList(strings) {}

     int rowCount(const QModelIndex &parent = QModelIndex()) const;
     QVariant data(const QModelIndex &index, int role) const;
     QVariant headerData(int section, Qt::Orientation orientation,
                         int role = Qt::DisplayRole) const;

 private:
     QStringList stringList;
 };

Apart from the model's constructor, we only need to implement two functions: rowCount() returns the number of rows in the model and data() returns an item of data corresponding to a specified model index.

Well behaved models also implement headerData() to give tree and table views something to display in their headers.

Note that this is a non-hierarchical model, so we don't have to worry about the parent-child relationships. If our model was hierarchical, we would also have to implement the index() and parent() functions.

The list of strings are stored internally in the <tt>stringList</tt> private member variable.

Dimensions of The Model

We want the number of rows in the model to be the same as the number of strings in the string list. We implement the rowCount() function with this in mind:

 int StringListModel::rowCount(const QModelIndex &parent) const
 {
     return stringList.count();
 }

Since the model is non-hierarchical, we can safely ignore the model index corresponding to the parent item. By default, models derived from QAbstractListModel only contain one column, so we do not need to reimplement the columnCount() function.

Model Headers and Data

For items in the view, we want to return the strings in the string list. The data() function is responsible for returning the item of data that corresponds to the index argument:

 QVariant StringListModel::data(const QModelIndex &index, int role) const
 {
     if (!index.isValid())
         return QVariant();

     if (index.row() >= stringList.size())
         return QVariant();

     if (role == Qt::DisplayRole)
         return stringList.at(index.row());
     else
         return QVariant();
 }

We only return a valid QVariant if the model index supplied is valid, the row number is within the range of items in the string list, and the requested role is one that we support.

Some views, such as QTreeView and QTableView, are able to display headers along with the item data. If our model is displayed in a view with headers, we want the headers to show the row and column numbers. We can provide information about the headers by subclassing the headerData() function:

 QVariant StringListModel::headerData(int section, Qt::Orientation orientation,
                                      int role) const
 {
     if (role != Qt::DisplayRole)
         return QVariant();

     if (orientation == Qt::Horizontal)
         return QString("Column %1").arg(section);
     else
         return QString("Row %1").arg(section);
 }

Again, we return a valid QVariant only if the model index is valid and the role is one that we support. The orientation of the header is also taken into account when deciding the exact data to return.

Not all views display headers with the item data, and those that do may be configured to hide them. Nonetheless, it is recommended that you implement the headerData() function to provide relevant information about the data provided by the model.

An item can have several roles, giving out different data depending on the role specified. The items in our model only have one role, DisplayRole, so we return the data for items irrespective of the role specified. However, we could reuse the data we provide for the DisplayRole in other roles, such as the ToolTipRole that views can use to display information about items in a tooltip.

An Editable Model

The read-only model shows how simple choices could be presented to the user but, for many applications, an editable list model is much more useful. We can modify the read-only model to make the items editable by implementing two extra functions: flags() and setData(). The following function declarations are added to the class definition:

     Qt::ItemFlags flags(const QModelIndex &index) const;
     bool setData(const QModelIndex &index, const QVariant &value,
                  int role = Qt::EditRole);

Making the Model Editable

A delegate checks whether an item is editable before creating an editor. The model must let the delegate know that its items are editable. We do this by returning the correct flags for each item in the model; in this case, we enable all items and make them both selectable and editable:

 Qt::ItemFlags StringListModel::flags(const QModelIndex &index) const
 {
     if (!index.isValid())
         return Qt::ItemIsEnabled;

     return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
 }

Note that we do not have to know how the delegate performs the actual editing process. We only have to provide a way for the delegate to set the data in the model. This is achieved through the setData() function:

 bool StringListModel::setData(const QModelIndex &index,
                               const QVariant &value, int role)
 {
     if (index.isValid() && role == Qt::EditRole) {

         stringList.replace(index.row(), value.toString());
         emit dataChanged(index, index);
         return true;
     }
     return false;
 }

In this model, the item in the string list that corresponds to the model index is replaced by the value provided. However, before we can modify the string list, we must make sure that the index is valid, the item is of the correct type, and that the role is supported. By convention, we insist that the role is the EditRole since this is the role used by the standard item delegate. The underlying data in this model is the same for all roles, so this detail just makes it easier to integrate the model with standard components.

When the data has been set, the model must let the views know that some data has changed. This is done by emitting the dataChanged() signal. Since only one item of data has changed, the range of items specified in the signal is limited to just one model index.

Inserting and Removing Rows

It is possible to change the number of rows and columns in a model. In the string list model it only makes sense to change the number of rows, so we only reimplement the functions for inserting and removing rows. These are declared in the class definition:

     bool insertRows(int position, int rows, const QModelIndex &index = QModelIndex());
     bool removeRows(int position, int rows, const QModelIndex &index = QModelIndex());

Since rows in this model correspond to strings in a list, the <tt>insertRows()</tt> function inserts a number of empty strings into the string list before the specified position. The number of strings inserted is equivalent to the number of rows specified.

The parent index is normally used to determine where in the model the rows should be added. In this case, we only have a single top-level list of strings, so we just insert empty strings into that list.

 bool StringListModel::insertRows(int position, int rows, const QModelIndex &parent)
 {
     beginInsertRows(QModelIndex(), position, position+rows-1);

     for (int row = 0; row < rows; ++row) {
         stringList.insert(position, "");
     }

     endInsertRows();
     return true;
 }

The model first calls the beginInsertRows() function to inform other components that the number of rows is about to change. The function specifies the row numbers of the first and last new rows to be inserted, and the model index for their parent item. After changing the string list, it calls endInsertRows() to complete the operation and inform other components that the dimensions of the model have changed, returning true to indicate success.

The function to remove rows from the model is also simple to write. The rows to be removed from the model are specified by the position and the number of rows given. We ignore the parent index to simplify our implementation, and just remove the corresponding items from the string list.

 bool StringListModel::removeRows(int position, int rows, const QModelIndex &parent)
 {
     beginRemoveRows(QModelIndex(), position, position+rows-1);

     for (int row = 0; row < rows; ++row) {
         stringList.removeAt(position);
     }

     endRemoveRows();
     return true;
 }

The beginRemoveRows() function is always called before any underlying data is removed, and specifies the first and last rows to be removed. This allows other components to access the data before it becomes unavailable. After the rows have been removed, the model emits endRemoveRows() to finish the operation and let other components know that the dimensions of the model have changed.

Next Steps

We can display the data provided by this model, or any other model, using the QListView class to present the model's items in the form of a vertical list. For the string list model, this view also provides a default editor so that the items can be manipulated. We examine the possibilities made available by the standard view classes in the chapter on View Classes.

The Model Subclassing Reference document discusses the requirements of QAbstractItemModel subclasses in more detail, and provides a guide to the virtual functions that must be implemented to enable various features in different types of models.

[Previous: Model Classes]
[Contents]
[Next: View Classes]

<address>

Copyright © 2008 Trolltech
Trademarks

Qt 4.3.5

</address>


text:
package resources.tests

class Adoc:
  def foo = 123


text:
<?php

declare(strict_types=1);

namespace Sylius\Behat\Behaviour;

use Behat\Mink\Element\NodeElement;

trait ChecksCodeImmutability
{
    abstract protected function getCodeElement(): NodeElement;

    public function isCodeDisabled(): bool
    {
        return 'disabled' === $this->getCodeElement()->getAttribute('disabled');
    }
}


text:
package cat.nyaa.autobloodmoon.mobs;

import cat.nyaa.nyaacore.configuration.ISerializable;
import org.bukkit.configuration.ConfigurationSection;

import java.util.ArrayList;

public class Mob implements ISerializable {
    @Serializable(name = "mobtype")
    private String mobType;
    @Serializable(name = "skills")
    private ArrayList<String> skills;

    public Mob() {

    }

    public Mob(String type, ArrayList<String> skills) {
        this.mobType = type;
        this.skills = skills;
    }

    public String getMobType() {
        return mobType;
    }

    public void setMobType(String mobType) {
        this.mobType = mobType;
    }

    public ArrayList<String> getSkills() {
        return skills;
    }

    public void setSkills(ArrayList<String> skills) {
        this.skills = skills;
    }

    @Override
    public void deserialize(ConfigurationSection config) {
        ISerializable.deserialize(config, this);
    }

    @Override
    public void serialize(ConfigurationSection config) {
        ISerializable.serialize(config, this);
    }

}