text:
/* @module Dataset */

var _ = require('lodash');
var csv = require('csv-streamify');
var csvOptions = {objectMode: true, delimiter: '\t'};
var highland = require('highland');
var httpErrors = require('./http-errors.js');
var hyperquest = require('hyperquest');
var internalContext = require('./context.json');
var Rx = require('rx');
var RxNode = require('rx-node');
var URI = require('URIjs');
var Utils = require('./utils.js');

/**
 * Used internally to create a new Dataset instance. See related
 * {@link http://bridgedb.org/apidoc/2.0/org/bridgedb/DataSource.html|DataSource}
 * from BridgeDb-Java.
 * @class
 * @memberof BridgeDb
 * @param {Object} instance
 */
var Dataset = function(instance) {
  'use strict';

  var jsonldRx = instance.jsonldRx;

  /**
   * See {@link http://rdfs.org/ns/void#Dataset|void:Dataset}
   * @typedef {Object} Dataset Dataset with as many as possible of the properties listed below.
   * @property {JsonldContext} @context JSON-LD context.
   * @property {Iri} id Preferred IRI for identifying a dataset.
   * @property {String[]} owl:sameAs Alternate IRI for identifying a dataset.
   *                    See {@link http://www.w3.org/TR/owl-ref/#sameAs-def|owl:sameAs}.
   * @property {String} name Official, standardized name for the data set.
   *  See {@link http://schema.org/name|schema:name}.
   * @property {String} webPage See
   *  {@link http://bridgedb.org/apidoc/2.0/org/bridgedb/DataSource.html#getMainUrl()|
   *    Java documentation} and {@link http://www.w3.org/2001/XMLSchema#anyURI|xsd:anyURI}.
   * @property {String} uriRegexPattern See
   *  {@link http://rdfs.org/ns/void#uriRegexPattern|void:uriRegexPattern}.
   * @property {Iri} exampleResource See
   *  {@link http://rdfs.org/ns/void#exampleResource|void:exampleResource}.
   * @property {String} exampleIdentifier See
   *  {@link http://identifiers.org/idot/exampleIdentifier|idot:exampleIdentifier}.
   * @property {String} organism Provided only if the dataset is for a single organism. See
   *  {@link http://www.biopax.org/release/biopax-level3.owl#organism|biopax:organism}.
   * @property {String} _bridgeDbType Biological type, as used at BridgeDb. See
   *  {@link
   *  http://bridgedb.org/apidoc/2.0/org/bridgedb/DataSource.Builder.html#type(java.lang.String)|
   *  Java documentation}.
   * @property {JsonldType} type {@link http://rdfs.org/ns/void#Dataset|void:Dataset}
   * @property {String|String[]} subject Subject of the database, such as the biological type of
   *  its contained entity references. Biological type as used in GPML at WikiPathways and in
   *  PathVisio-Java:
   *  {@link http://vocabularies.wikipathways.org/gpml#Type|gpml:Type}.
   *  Biological type as used in Biopax: see the domain for
   *  {@link
   *  http://www.biopax.org/release/biopax-level3.owl#entityReference|biopax:entityReference}.
   * @property {Boolean} _isPrimary See Java documentation for
   *  {@link http://bridgedb.org/apidoc/2.0/org/bridgedb/DataSource.html#isPrimary()|"isPrimary"}
   *  and for
   *  {@link http://bridgedb.org/apidoc/2.0/org/bridgedb/DataSource.Builder.html#primary(boolean)|
   *  "primary" method}.
   * @property {String} identifierPattern Regular expression for the identifiers from this dataset.
   *  See {@link http://identifiers.org/idot/identifierPattern|idot:identifierPattern}.
   * @property {String} preferredPrefix Abbreviation as used by identifiers.org to identify a
   *  dataset. See {@link http://identifiers.org/idot/preferredPrefix|idot:preferredPrefix}.
   *  @example: 'ncbigene'
   * @property {String[]} alternatePrefix Abbreviation as used elsewhere to identify a dataset,
   *  such as at BridgeDb (bridgeDbSystemCode located both here and on its own).
   *  See {@link http://identifiers.org/idot/alternatePrefix|idot:alternatePrefix}.
   * @property {String} bridgeDbSystemCode See
   *  {@link http://bridgedb.org/apidoc/2.0/org/bridgedb/DataSource.html#getSystemCode()|
   *    Java documentation}.
   * @property {String} bridgeDbDatasourceName Name for the data set as used in the
   *  BridgeDb project.
   */

  /**
   * At least one of the following properties must be provided.
   * @typedef {Object} DatasetArgs
   * @property {Iri} [id]
   * @property {String} [preferredPrefix]
   * @property {String|String[]} [bridgeDbSystemCode]
   * @property {String|String[]} [name]
   * @property {String} [identifier] The identifier of the entity reference. This property
   *                                   will only be used if no other properties return results,
   *                                   because many different datasets have overlapping
   *                                   identifierPatterns.
   */

  /**
   * @private
   *
   * Get all biological datasets supported by BridgeDb, with all
   * available metadata, largely as specified in
   * {@link
   * https://github.com/bridgedb/BridgeDb/blob/master/org.bridgedb.bio/
   * resources/org/bridgedb/bio/datasources.txt|
   * datasources.txt}.
   *
   * @return {Stream<Dataset>} datasetStream
   */
  function _getAll() {
    function init() {

      /*
      return RxNode.fromReadableStream(
        hyperquest(instance.config.datasetsMetadataIri, {
          withCredentials: false
        })
        .pipe(csv(csvOptions))
      )
      //*/

      return highland(
        hyperquest(instance.config.datasetsMetadataIri, {
          withCredentials: false
        })
        .pipe(csv(csvOptions))
      )
      .map(function(array) {
        return {
          '@context': internalContext,
          bridgeDbDatasourceName: array[0],
          bridgeDbSystemCode: array[1],
          webPage: array[2],
          _iriPattern: array[3],
          exampleIdentifier: array[4],
          _bridgeDbType: array[5],
          // TODO this is returning organism as a string
          // when elsewhere we are using organism as an
          // object. Will that cause problems?
          organism: array[6],
          _isPrimary: array[7] === '1',
          _miriamRootUrn: array[8],
          identifierPattern: array[9],
          name: array[10]
        };
      })
      .map(function(dataset) {

        // remove empty properties

        return _.omit(dataset, function(value) {
          return value === '' ||
            _.isNaN(value) ||
          _.isNull(value) ||
          _.isUndefined(value);
        });
      })
      .map(function(dataset) {
        var iriPattern = dataset._iriPattern;
        var identifierPattern = dataset.identifierPattern;
        if (!!iriPattern) {
          dataset.uriRegexPattern = iriPattern.replace(
            '$id',
            _getIdentifierPatternWithoutBeginEndRestriction(identifierPattern)
          );

          // if '$id' is at the end of the iriPattern
          var indexOfSid = iriPattern.length - 3;
          if (iriPattern.indexOf('$id') === indexOfSid) {
            dataset['owl:sameAs'] = dataset['owl:sameAs'] || [];
            dataset['owl:sameAs'].push(iriPattern.substr(0, indexOfSid));
          }
        }

        dataset.type = 'Dataset';

        return dataset;
      })
      .map(function(dataset) {
        if (!!dataset._miriamRootUrn &&
            dataset._miriamRootUrn.indexOf('urn:miriam:') > -1) {

          dataset.preferredPrefix =
            dataset._miriamRootUrn.substring(11,
              dataset._miriamRootUrn.length);
          dataset.id =
            'http://identifiers.org/' + dataset.preferredPrefix + '/';
          dataset['owl:sameAs'] = dataset['owl:sameAs'] || [];
          dataset['owl:sameAs'].push(dataset._miriamRootUrn);
        }
        delete dataset._miriamRootUrn;
        return dataset;
      })
      .map(function(dataset) {
        if (!!dataset._bridgeDbType) {
          dataset.subject = [];
          /* Example of using 'subject' (from the VOID docs <http://www.w3.org/TR/void/#subject>):
              :Bio2RDF a void:Dataset;
                  dcterms:subject <http://purl.uniprot.org/core/Gene>;
                  .

          The closest concepts from the GPML, BioPAX and MESH vocabularies are included below.

          Note that in BioPAX, 'ProteinReference' is to 'Protein' as
              'Class' is to 'Instance' or
              'platonic ideal of http://identifiers.org/uniprot/P78527' is to
                    'one specific example of http://identifiers.org/uniprot/P78527'
          with the same logic applying for Dna, Rna and SmallMolecule. As such, it appears the
          subject of Uniprot is best described in BioPAX terms as biopax:ProteinReference instead
          of biopax:Protein.

          It is unclear whether the subject of Entrez Gene is biopax:DnaReference or biopax:Gene,
          but I'm going with biopax:DnaReference for now because it appears to be analogous to
          ProteinReference and SmallMoleculeReference.
          //*/
          if (dataset._bridgeDbType === 'gene' ||
              // TODO should the following two conditions be removed?
              dataset._bridgeDbType === 'probe' ||
              dataset.preferredPrefix === 'go') {
            dataset.subject.push('gpml:GeneProduct');
            dataset.subject.push('biopax:DnaReference');
          } else if (dataset._bridgeDbType === 'probe') {
            dataset.subject.push('probe');
          } else if (dataset._bridgeDbType === 'rna') {
            dataset.subject.push('gpml:Rna');
            dataset.subject.push('biopax:RnaReference');
          } else if (dataset._bridgeDbType === 'protein') {
            dataset.subject.push('gpml:Protein');
            dataset.subject.push('biopax:ProteinReference');
          } else if (dataset._bridgeDbType === 'metabolite') {
            dataset.subject.push('gpml:Metabolite');
            dataset.subject.push('biopax:SmallMoleculeReference');
          } else if (dataset._bridgeDbType === 'pathway') {
            // BioPAX does not have a term for pathways that is analogous to
            // biopax:ProteinReference for proteins.
            dataset.subject.push('gpml:Pathway');
            dataset.subject.push('biopax:Pathway');
          } else if (dataset._bridgeDbType === 'ontology') {
            dataset.subject.push('owl:Ontology');
          } else if (dataset._bridgeDbType === 'interaction') {
            dataset.subject.push('biopax:Interaction');
          }
        }

        dataset.alternatePrefix = [
          dataset.bridgeDbSystemCode
        ];

        return dataset;
      });
    }

    return Utils._runOnceGlobal('dataset', init);
  }

  function _getIdentifierPatternWithoutBeginEndRestriction(identifierPattern) {
    identifierPattern = identifierPattern || '.*';
    var identifierPatternWithoutBeginEndRestriction =
      '(' + identifierPattern.replace(/(^\^|\$$)/g, '') + ')';
    return identifierPatternWithoutBeginEndRestriction;
  }

  /**
   * Get one dataset, which will be the first dataset that matches
   * at least one of the provided argument(s).
   *
   * @param {DatasetArgs} args
   * @return {Stream<Dataset>} datasetsStream
   */
  function get(args) {
    return query(args).head();
  }

  /**
   * Get all datasets, or find the datasets that match at least one of the provided argument(s).
   *
   * @param {DatasetArgs} [args] If no args specified, will return all datasets.
   * @return {Stream<Dataset>} datasetsStream
   */
  function query(args) {
    if (_.isEmpty(args)) {
      return _getAll()
      .map(jsonldRx._matcher._removeNormalizedProperties);
    }

    // preferred keys for identifying a dataset
    var keysThatIdentifyDatasets = [
      'id',
      'preferredPrefix',
      'bridgeDbDatasourceName',
      'alternatePrefix',
      'name'
    ];

    var alternateFilters =  [];
    if (!!args.exampleResource) {
      alternateFilters.push(
        highland.curry(function(exampleResource, referenceDataset) {
          var uriRegexPatternRegExp =
              new RegExp(referenceDataset.uriRegexPattern);
          return !!exampleResource &&
            !!referenceDataset.uriRegexPattern &&
            uriRegexPatternRegExp.test(exampleResource);
        }, args.exampleResource)
      );
    }
    if (!!args.exampleIdentifier) {
      alternateFilters.push(
        highland.curry(function(exampleIdentifier, referenceDataset) {
          var identifierPatternRegExp =
              new RegExp(referenceDataset.identifierPattern);
          return !!exampleIdentifier &&
            !!referenceDataset.identifierPattern &&
            identifierPatternRegExp.test(exampleIdentifier);
        }, args.exampleIdentifier)
      );
    }

    return _getAll()
      /*
      .filter(function(dataset) {
        // TODO Make it optional whether to apply this filter.

        // Dataset subjects that indicate the dataset should not be used for identifying
        // a BioPAX Entity Reference for a gpml:DataNode.
        var nonApplicableSubjects = [
          'interaction',
          'ontology',
          'probe',
          'experiment',
          'publication',
          'model',
          'organism'
        ];
        return dataset._isPrimary &&
            !!dataset.id &&
            nonApplicableSubjects.indexOf(dataset._bridgeDbType) === -1;
      })
      //*/
      .collect()
      .flatMap(function(datasets) {
        //*
        var wpPreferredDatasets = [
          'ensembl',
          'ncbigene',
          'chebi',
          'cas',
          'hmdb',
          'uniprot',
          'kegg.compound'
        ];

        datasets.sort(function(dataset1, dataset2) {
          var preferredPrefix1 = dataset1.preferredPrefix;
          var preferredPrefix2 = dataset2.preferredPrefix;
          var preferenceIndex1 = wpPreferredDatasets.indexOf(preferredPrefix1);
          var preferenceIndex2 = wpPreferredDatasets.indexOf(preferredPrefix2);
          var preferred1 = preferenceIndex1 > -1;
          var preferred2 = preferenceIndex2 > -2;
          if (preferred1 && !preferred2) {
            return -1;
          } else if (!preferred1 && preferred2) {
            return 1;
          } else if (preferred1 && preferred2) {
            return preferred1 > preferred2;
          }

          var isPrimary1 = dataset1._isPrimary;
          var isPrimary2 = dataset2._isPrimary;
          if (isPrimary1 && !isPrimary2) {
            return -1;
          } else if (!isPrimary1 && isPrimary2) {
            return 1;
          }

          // does it have a preferredPrefix?
          if (preferredPrefix1 && !preferredPrefix2) {
            return -1;
          } else if (!preferredPrefix1 && preferredPrefix2) {
            return 1;
          }

          return preferredPrefix1 > preferredPrefix2;
        });
        //*/
        /*
        // TODO We should distinguish between exact and fuzzy matches.
        // For fuzzy matches, we should allow for setting priorities.
        // input:
        {exact: [
          'id', // a string indicates usage of pluck syntax
          'preferredPrefix',
          function(candidate, argument) {
            // TODO below will not actually work
            return uriRegexPatternRegExp.test(exampleResource);
          }.bind(null, exampleResource),
          'bridgeDbDatasourceName'
        ],
        fuzzy: [
          'name',
          function(candidate, argument) {
            // TODO below will not actually work
            return identifierPatternRegExp.test(exampleIdentifier);
          }.bind(null, exampleIdentifier),
          function(candidate, entityType) {
            var entityTypes = jsonldRx.arrayifyClean(entityType);
            var datasetSubjects = jsonldRx.arrayifyClean(candidate.subject);
            return !_.isEmpty(_.intersection(entityReferenceTypes, datasetSubjects));
          }.bind(null, entityType),
          '_isPrimary'
        ]}

        // output
        {
          match: {},
          score: 0 // 0: exact match. 3: we found a match with the third fuzzy filter.
        }
        //*/
        return jsonldRx.tieredFind(
          args,
          highland(datasets),
          'datasetsFormattedForComparison',
          keysThatIdentifyDatasets,
          alternateFilters
        );
      });
  }

  function convertPreferredPrefixToSystemCode(preferredPrefix) {
    return getByPreferredPrefix(preferredPrefix)
      .map(function(dataset) {
      if (!dataset) {
        var message = 'No BridgeDb-supported dataset available for ' +
           'preferredPrefix + "' + preferredPrefix + '"';
        return new Error(message);
      }
      return dataset.bridgeDbSystemCode;
    });
  }

  return {
    convertPreferredPrefixToSystemCode:
      convertPreferredPrefixToSystemCode,
    get:get,
    _getIdentifierPatternWithoutBeginEndRestriction:
      _getIdentifierPatternWithoutBeginEndRestriction,
    query:query
  };
};

module.exports = Dataset;


text:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WeaponStoneThrower : Weapon
{
    [SerializeField]
    private GameObject m_stoneOriginal;
    [SerializeField]
    private SteamVR_TrackedObject m_weaponController;

    private GameObject m_stone;
    private SteamVR_Controller.Device m_weaponControllerDevice;
    private bool m_touchedDown;

    private void Start()
    {
        m_weaponControllerDevice = SteamVR_Controller.Input((int)m_weaponController.index);
    }

    private void Update()
    {
        bool touchedDown = m_weaponControllerDevice.GetTouchDown(SteamVR_Controller.ButtonMask.Trigger);
        // Set true only when touched down and do not reset. (Reset in FixedUpdate)
        if (touchedDown)
            m_touchedDown = true;
    }

    private void FixedUpdate()
    {
        if (!m_touchedDown)
            return;
        if (m_stone == null)
            return;
        ThrowStone();
        StartCoroutine(InstantiateStone(3));

        // Reset m_touchedDown.
        m_touchedDown = false;
    }

    private void ThrowStone()
    {
        Transform origin = m_weaponController.origin;
        if (origin == null)
            origin = m_weaponController.transform.parent;

        Vector3 velocity, angularVelocity;
        if (origin == null)
        {
            velocity = origin.TransformVector(m_weaponControllerDevice.velocity);
            angularVelocity = origin.TransformVector(m_weaponControllerDevice.angularVelocity);
        }
        else
        {
            velocity = m_weaponControllerDevice.velocity;
            angularVelocity = m_weaponControllerDevice.angularVelocity;
        }

        Stone stoneScript = m_stone.GetComponent<Stone>();
        m_stone = null;

        stoneScript.SetThrown(velocity, angularVelocity);
    }

    /// <param name="timeout">Real time seconds</param>
    private IEnumerator InstantiateStone(float timeout)
    {
        timeout = Mathf.Max(timeout, 0);
        yield return new WaitForSecondsRealtime(timeout);
        m_stone = Instantiate(m_stoneOriginal, transform) as GameObject;

    }

    protected override void OnEnter(Collider other)
    {
        // Nothing.
    }

    protected override void OnExit(Collider other)
    {
        // Nothing.
    }

    protected override void OnStay(Collider other)
    {
        // Nothing.
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.bookkeeper.proto;

import org.apache.bookkeeper.auth.ClientAuthProvider;
import org.apache.bookkeeper.auth.AuthProviderFactoryFactory;
import org.apache.bookkeeper.bookie.Bookie;
import org.apache.bookkeeper.client.BKException;
import org.apache.bookkeeper.conf.ServerConfiguration;
import org.apache.bookkeeper.conf.ClientConfiguration;
import org.apache.bookkeeper.net.BookieSocketAddress;
import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback;
import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ReadEntryCallback;
import org.apache.bookkeeper.proto.PerChannelBookieClient.ConnectionState;
import org.apache.bookkeeper.test.BookKeeperClusterTestCase;
import org.apache.bookkeeper.util.OrderedSafeExecutor;
import org.apache.bookkeeper.util.SafeRunnable;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.socket.ClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.protobuf.ExtensionRegistry;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.junit.Assert.*;

/**
 * Tests for PerChannelBookieClient. Historically, this class has
 * had a few race conditions, so this is what these tests focus on.
 */
public class TestPerChannelBookieClient extends BookKeeperClusterTestCase {
    private final static Logger LOG = LoggerFactory.getLogger(TestPerChannelBookieClient.class);

    ExtensionRegistry extRegistry = ExtensionRegistry.newInstance();
    ClientAuthProvider.Factory authProvider;

    public TestPerChannelBookieClient() throws Exception {
        super(1);
        authProvider = AuthProviderFactoryFactory.newClientAuthProviderFactory(
                new ClientConfiguration(), extRegistry);
    }

    /**
     * Test that a race does not exist between connection completion
     * and client closure. If a race does exist, this test will simply
     * hang at releaseExternalResources() as it is uninterruptible.
     * This specific race was found in
     * {@link https://issues.apache.org/jira/browse/BOOKKEEPER-485}.
     */
    @Test(timeout=60000)
    public void testConnectCloseRace() throws Exception {
        ClientSocketChannelFactory channelFactory
            = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
                                                Executors.newCachedThreadPool());
        OrderedSafeExecutor executor = getOrderedSafeExecutor();

        BookieSocketAddress addr = getBookie(0);
        for (int i = 0; i < 1000; i++) {
            PerChannelBookieClient client = new PerChannelBookieClient(executor, channelFactory, addr,
                    authProvider, extRegistry);
            client.connectIfNeededAndDoOp(new GenericCallback<PerChannelBookieClient>() {
                    @Override
                    public void operationComplete(int rc, PerChannelBookieClient client) {
                        // do nothing, we don't care about doing anything with the connection,
                        // we just want to trigger it connecting.
                    }
                });
            client.close();
        }
        channelFactory.releaseExternalResources();
        executor.shutdown();
    }

    public OrderedSafeExecutor getOrderedSafeExecutor() {
        return OrderedSafeExecutor.newBuilder()
            .name("PCBC")
            .numThreads(1)
            .traceTaskExecution(true)
            .traceTaskWarnTimeMicroSec(TimeUnit.MILLISECONDS.toMicros(100))
            .build();
    }

    /**
     * Test race scenario found in {@link https://issues.apache.org/jira/browse/BOOKKEEPER-5}
     * where multiple clients try to connect a channel simultaneously. If not synchronised
     * correctly, this causes the netty channel to get orphaned.
     */
    @Test(timeout=60000)
    public void testConnectRace() throws Exception {
        GenericCallback<PerChannelBookieClient> nullop = new GenericCallback<PerChannelBookieClient>() {
            @Override
            public void operationComplete(int rc, PerChannelBookieClient pcbc) {
                // do nothing, we don't care about doing anything with the connection,
                // we just want to trigger it connecting.
            }
        };
        ClientSocketChannelFactory channelFactory
            = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
                                                Executors.newCachedThreadPool());
        OrderedSafeExecutor executor = getOrderedSafeExecutor();

        BookieSocketAddress addr = getBookie(0);
        for (int i = 0; i < 100; i++) {
            PerChannelBookieClient client = new PerChannelBookieClient(executor, channelFactory, addr,
                                                                       authProvider, extRegistry);
            for (int j = i; j < 10; j++) {
                client.connectIfNeededAndDoOp(nullop);
            }
            client.close();
        }
        channelFactory.releaseExternalResources();
        executor.shutdown();
    }

    /**
     * Test that all resources are freed if connections and disconnections
     * are interleaved randomly.
     *
     * {@link https://issues.apache.org/jira/browse/BOOKKEEPER-620}
     */
    @Test(timeout=60000)
    public void testDisconnectRace() throws Exception {
        final GenericCallback<PerChannelBookieClient> nullop = new GenericCallback<PerChannelBookieClient>() {
            @Override
            public void operationComplete(int rc, PerChannelBookieClient client) {
                // do nothing, we don't care about doing anything with the connection,
                // we just want to trigger it connecting.
            }
        };
        final int ITERATIONS = 100000;
        ClientSocketChannelFactory channelFactory
            = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
                                                Executors.newCachedThreadPool());
        OrderedSafeExecutor executor = getOrderedSafeExecutor();
        BookieSocketAddress addr = getBookie(0);

        final PerChannelBookieClient client = new PerChannelBookieClient(executor, channelFactory,
                addr, authProvider, extRegistry);
        final AtomicBoolean shouldFail = new AtomicBoolean(false);
        final AtomicBoolean inconsistent = new AtomicBoolean(false);
        final AtomicBoolean running = new AtomicBoolean(true);
        final CountDownLatch disconnectRunning = new CountDownLatch(1);
        Thread connectThread = new Thread() {
                public void run() {
                    try {
                        if (!disconnectRunning.await(10, TimeUnit.SECONDS)) {
                            LOG.error("Disconnect thread never started");
                            shouldFail.set(true);
                        }
                    } catch (InterruptedException ie) {
                        LOG.error("Connect thread interrupted", ie);
                        Thread.currentThread().interrupt();
                        running.set(false);
                    }
                    for (int i = 0; i < ITERATIONS && running.get(); i++) {
                        client.connectIfNeededAndDoOp(nullop);
                    }
                    running.set(false);
                }
            };
        Thread disconnectThread = new Thread() {
                public void run() {
                    disconnectRunning.countDown();
                    while (running.get()) {
                        client.disconnect();
                    }
                }
            };
        Thread checkThread = new Thread() {
                public void run() {
                    ConnectionState state;
                    Channel channel;
                    while (running.get()) {
                        synchronized (client) {
                            state = client.state;
                            channel = client.channel;

                            if ((state == ConnectionState.CONNECTED
                                 && (channel == null
                                     || !channel.isConnected()))
                                || (state != ConnectionState.CONNECTED
                                    && channel != null
                                    && channel.isConnected())) {
                                LOG.error("State({}) and channel({}) inconsistent " + channel,
                                          state, channel == null ? null : channel.isConnected());
                                shouldFail.set(true);
                                running.set(false);
                            }
                        }
                    }
                }
            };
        connectThread.start();
        disconnectThread.start();
        checkThread.start();

        connectThread.join();
        disconnectThread.join();
        checkThread.join();
        assertFalse("Failure in threads, check logs", shouldFail.get());
        client.close();
        channelFactory.releaseExternalResources();
        executor.shutdown();
    }

    /**
     * Test that requests are completed even if the channel is disconnected
     * {@link https://issues.apache.org/jira/browse/BOOKKEEPER-668}
     */
    @Test(timeout=60000)
    public void testRequestCompletesAfterDisconnectRace() throws Exception {
        ServerConfiguration conf = killBookie(0);

        Bookie delayBookie = new Bookie(conf) {
            @Override
            public ByteBuffer readEntry(long ledgerId, long entryId)
                    throws IOException, NoLedgerException {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException ie) {
                    throw new IOException("Interrupted waiting", ie);
                }
                return super.readEntry(ledgerId, entryId);
            }
        };
        bsConfs.add(conf);
        bs.add(startBookie(conf, delayBookie));

        ClientSocketChannelFactory channelFactory
            = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),
                                                Executors.newCachedThreadPool());
        final OrderedSafeExecutor executor = getOrderedSafeExecutor();
        BookieSocketAddress addr = getBookie(0);

        final PerChannelBookieClient client = new PerChannelBookieClient(executor, channelFactory,
                addr, authProvider, extRegistry);
        final CountDownLatch completion = new CountDownLatch(1);
        final ReadEntryCallback cb = new ReadEntryCallback() {
                @Override
                public void readEntryComplete(int rc, long ledgerId, long entryId,
                                              ChannelBuffer buffer, Object ctx) {
                    completion.countDown();
                }
            };

        client.connectIfNeededAndDoOp(new GenericCallback<PerChannelBookieClient>() {
            @Override
            public void operationComplete(final int rc, PerChannelBookieClient pcbc) {
                if (rc != BKException.Code.OK) {
                    executor.submitOrdered(1, new SafeRunnable() {
                        @Override
                        public void safeRun() {
                            cb.readEntryComplete(rc, 1, 1, null, null);
                        }
                    });
                    return;
                }

                client.readEntryAndFenceLedger(1, "00000111112222233333".getBytes(), 1, cb, null);
            }
        });

        Thread.sleep(1000);
        client.disconnect();
        client.close();
        channelFactory.releaseExternalResources();
        executor.shutdown();

        assertTrue("Request should have completed", completion.await(5, TimeUnit.SECONDS));
    }
}


text:
package org.jetbrains.jps.incremental.scala.sources

import com.intellij.openapi.util.io.FileFilters

import java.util
import java.util.Collections
import org.jetbrains.jps.builders.java.{JavaModuleBuildTargetType, JavaSourceRootDescriptor, ResourcesTargetType}
import org.jetbrains.jps.builders.storage.BuildDataPaths
import org.jetbrains.jps.builders.{AdditionalRootsProviderService, BuildTarget}
import org.jetbrains.jps.incremental.ModuleBuildTarget
import org.jetbrains.jps.incremental.scala.SourceDependenciesProviderService
import org.jetbrains.jps.model.java.{JavaSourceRootProperties, JavaSourceRootType}
import org.jetbrains.jps.model.module.JpsModuleSourceRoot

import scala.jdk.CollectionConverters._

class SourceDependenciesRootsProviderService
  extends AdditionalRootsProviderService[JavaSourceRootDescriptor](JavaModuleBuildTargetType.ALL_TYPES) {

  override def getAdditionalRoots(target: BuildTarget[JavaSourceRootDescriptor],
                                  dataPaths: BuildDataPaths): util.List[JavaSourceRootDescriptor] = {

    target match {
      case target: ModuleBuildTarget =>
        val sourceDepModules = SourceDependenciesProviderService.getSourceDependenciesFor(target)
        val sourceRoots = sourceDepModules.flatMap(_.getSourceRoots(rootType(target)).asScala)
        sourceRoots.map(descriptor(_, target)).asJava
      case _ =>
        super.getAdditionalRoots(target, dataPaths)
    }
  }

  private def descriptor(sourceRoot: JpsModuleSourceRoot, target: ModuleBuildTarget): JavaSourceRootDescriptor = {
    val packagePrefix = sourceRoot.getProperties match {
      case j: JavaSourceRootProperties => j.getPackagePrefix
      case _ => ""
    }
    new JavaSourceRootDescriptor(sourceRoot.getFile, target, false, false, packagePrefix, Collections.emptySet(), FileFilters.EVERYTHING)
  }

  private def rootType(moduleBuildTarget: ModuleBuildTarget): JavaSourceRootType =
    if (moduleBuildTarget.isTests) JavaSourceRootType.TEST_SOURCE
    else JavaSourceRootType.SOURCE

}


text:
package com.thedragons.database.server;

import com.google.gson.Gson;

import java.io.*;
import java.net.*;
import java.util.HashMap;

/**
 * Authentication of user accounts and storage and retrieval of save data.
 */
public class AuthStorage {

    /**
     * Validates an account name.
     * @param acctName is the account name to validate.
     * @return true if valid and false if invalid.
     * @throws IOException if buffer read failed.
     */
	private boolean validAcct(String acctName) throws IOException {
        //alphanumeric only and 2-12 characters
        boolean isAccount = true;
		if (!acctName.matches("^[a-zA-Z0-9]{2,13}$")) {
            System.out.println(">>> Account name is not valid.");
            isAccount = false;
        } else { //see if account exists
            BufferedReader reader = new BufferedReader(new FileReader("users.txt"));
            String line;
            while ((line = reader.readLine()) != null) {
                String[] credentials = line.split(" ");
                if (acctName.equals(credentials[0])) {
                    isAccount = false;
                }
            }
            reader.close();
		}
		return isAccount;
	}

    /**
     * Adds a new account.
     * @param acctName is the account name to add.
     * @param password is the password associated with the account.
     * @return true if the account was added and false if it was not added.
     * @throws IOException if file creation failed.
     */
	public boolean addAcct(String acctName, String password) throws IOException {
        //checking for if this is first user
        File u = new File("users.txt");
        if (!u.exists()) {
            try {
                u.createNewFile();
            } catch(IOException e){
                System.out.println(e);
            }
        }

		if (validAcct(acctName)) {
            if (password.contains(" ")) {
                return false;
            }
            FileWriter out;
			try {
				out = new FileWriter("users.txt", true);//1 is for append
			} catch (IOException e) {
					System.out.println(e);
                    return false;
			}
			out.write(acctName+" "+password+"\n");
			out.close();

			File d = new File(acctName);//making folder for users data
			d.mkdir();

            File file = new File(acctName + "/saves.txt");
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch(IOException e){
                    System.out.println(e);
                }
            }
            return true;
		}
        return false;
	}

    /**
     * Logs in an account.
     * @param acctName is the account name to login.
     * @param password is the password associated with the account.
     * @return true if the login succeeded and false if it failed.
     * @throws IOException if read file failed.
     */
	public boolean checkAccount(String acctName, String password) throws IOException {
        boolean isAccount = false;

        BufferedReader reader = new BufferedReader(new FileReader("users.txt"));
        String line;
        while ((line = reader.readLine()) != null) {
            String[] credentials = line.split(" ");
            if (acctName.equals(credentials[0]) && password.equals(credentials[1])) {
                isAccount = true;
            }
        }
        reader.close();

        return isAccount;
	}

    /**
     * Gets and returns the list of saves for an account.
     * @param acctName is the account name to retrieve the saves for.
     * @return true if the save list was retrieved and false if it was not.
     * @throws IOException if read file failed.
     */
    public String getSaves(String acctName) throws IOException {
        BufferedReader in;
        try {
            in = new BufferedReader(new FileReader(acctName+"/saves.txt"));
        } catch (IOException e) {
            System.out.println(e);
            return "";
        }
        String s;
        String saves = "";
        while ((s = in.readLine()) != null) {
            saves += s + "-=-";
        }
        HashMap<String, String> outMap = new HashMap<>();
        outMap.put("saves", saves);
        Gson gson = new Gson();
        String output = gson.toJson(outMap);
        in.close();
        return output;
    }

    /**
     * Saves data for an account.
     * @param acctName is the account name to saves the data for.
     * @param saveName is the file name to save the data in.
     * @param content is the data to save.
     * @throws IOException if the file creation failed.
     */
	public void saveData(String acctName, String saveName, String content) throws IOException {
        File t = new File(acctName+"/"+saveName+".bin");
        if (!t.exists()) {
            FileWriter saves;
            try {
                saves = new FileWriter(acctName + "/saves.txt", true); //1 is for append
            } catch (IOException e) {
                System.out.println(e);
                return;
            }
            saves.write(saveName + "\n");
            saves.close();
        }

        FileWriter out;
		try {
			out = new FileWriter(acctName+"/"+saveName+".bin");
		} catch (IOException e) {
				System.out.println(e);
                return;
		}
		out.write(content);
		out.close();
	}

    /**
     * Loads data for an account.
     * @param acctName is the account name to load the data for.
     * @param saveName is the file name to load the data from.
     * @return true if the data was loaded and false if it was not.
     * @throws IOException if the file was not read.
     */
	public String loadData(String acctName, String saveName) throws IOException {
        BufferedReader in;
		try {
            in = new BufferedReader(new FileReader(acctName+"/"+saveName+".bin"));
		} catch (IOException e) {
				System.out.println(e);
                return "";
		}
		String s = "";
		String outPut = "";
		while ((s = in.readLine()) != null) {
            outPut += s;
        }
		in.close();
        return outPut;
	}
}


text:
{{ convertToDate({ dt: weatherDay.dt }) | date: dateFormat }}

        Daytime temperature: {{ convertToStandard({ daytimeTemp: weatherDay.temp.day }) }}


text:
@interface EVESettingViewController : BaseViewController

@end


text:
'use strict';

var isStream = require('is-stream');

function inspectStream(stream) {
  if (!isStream(stream)) {
    return;
  }

  var streamType = stream.constructor.name;
  // Avoid StreamStream
  if (streamType === 'Stream') {
    streamType = '';
  }

  return '<' + streamType + 'Stream>';
}

module.exports = inspectStream;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/REC-html40/loose.dtd">

  <title>Description of Instructions</title>
  <meta name="keywords" content="Instructions">
  <meta name="description" content="Instructions:">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html © 2005 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../m2html.css">

Instructions

PURPOSE

Instructions:

SYNOPSIS

This is a script file.

DESCRIPTION

 Instructions:

 Place the matlab package anywhere on your computer and
 add it to your matlab path. This can be done by pulling down the
 File tab in the Matlab editor. Make sure that you use "Add with
 subfolders". For future use, you can save this path by clicking
 "save". Do the same for the data directory. This contains
 some LIP data used by the testing script testscript.m.

 Help is available in the doc directory.
 First read the help in chronux.m that discusses variables that
 are used repeatedly by the library and the important issue of
 units.

CROSS-REFERENCE INFORMATION

This function calls:

This function is called by:

SOURCE CODE

0001 % Instructions:
0002 %
0003 % Place the matlab package anywhere on your computer and
0004 % add it to your matlab path. This can be done by pulling down the
0005 % File tab in the Matlab editor. Make sure that you use "Add with
0006 % subfolders". For future use, you can save this path by clicking
0007 % "save". Do the same for the data directory. This contains
0008 % some LIP data used by the testing script testscript.m.
0009 %
0010 % Help is available in the doc directory.
0011 % First read the help in chronux.m that discusses variables that
0012 % are used repeatedly by the library and the important issue of
0013 % units.

<address>Generated on Fri 12-Aug-2011 11:36:15 by m2html © 2005</address>