text:
__author__ = 'fmoscato'

"""
The Publication DAO  handles interactions with the publication collection
The DAO provides 3 levels interface (da scrivere meglio)
1 - ADMIN can add publications + validate
2- search publications
3- users level
"""

import sys
from datetime import datetime

import pymongo.errors

import constants as c
import handle_asdc_author

class PublicationDAO(object):

    def __init__(self, database):
        self.db = database
        self.publications = database.publications

    def add_publication(self, **kwargs):
        """
        insert publication.
        param: **kwargs
        return : true || false
        """

        print "inserting publication entry ", kwargs['biblicode']

        magazine = (kwargs["biblicode"].split('.')[0])[4:]

        if magazine.startswith('arXiv'):
            magazine = 'arXiv'

        #this piece is done for the not refeered publications, that some times can have 00 instead
        #of a valid month
        try:
            pub_date = datetime.strptime(kwargs["pub_date"], "%m/%Y")
        except ValueError:
            print "guffy pub_date: %s" % kwargs["pub_date"]
            pub_date = datetime.strptime("01/%s" % (kwargs["pub_date"].split("/")[1]), "%m/%Y")

        # Build a new publication
        publication = {"_id": kwargs["biblicode"],
                       "title": unicode(kwargs["Title"], 'utf-8', 'ignore'),
                       "authors": unicode(kwargs["authors"], 'utf-8', 'ignore'),
                       "mission": kwargs["mission"],
                       "pub_date": pub_date,
                       "DOI": kwargs["DOI"],
                       "Keywords": kwargs["Keywords"],
                       "URL": c.URL_ADS + kwargs["biblicode"],
                       "Origin": kwargs["Origin"],
                       "Magazine": magazine,
                       "Abstract": unicode(kwargs["Abstract"], 'utf-8', 'ignore'),
                       # we are assuming that all the publications belongs to the users
                       #they have to explicit say that don't belong to them
                       "asdc_auth": [dict(author=usr, validate=True)for usr in kwargs["asdc_author"]],
                       "publication": unicode(kwargs["Publication"], 'utf-8', 'ignore'),
                       "is_open": kwargs.get("is_open", True),
                       "is_refeered": kwargs["is_refeered"]}

        # now insert the publication
        try:
            self.publications.insert(publication)
            print "Inserted the publication: ", kwargs['biblicode']
        except pymongo.errors.DuplicateKeyError:
            #it's OK. same biblicode can have multiple ASDC users
            # then need only to be updated: fields that can be updated:
            #1- asdc_authors 2- missions
            #this is can be done only if the publication is open
            #otherwise skip
            try:
                pub = self.get_publication_by_biblicode(kwargs["biblicode"])
                print "biblicode %s and state %s " % (pub['biblicode'], pub['is_open'])
                if pub["is_open"]:
                    self.publications.update({"_id": kwargs["biblicode"]},
                                             {"$set":
                                             {"asdc_auth": [dict(author=usr, validate=True)for usr in kwargs["asdc_author"]],
                                              "mission": kwargs["mission"],
                                              "authors": unicode(kwargs["authors"], 'utf-8', 'ignore')}})
                else:

                    print ("skipping update for publication :%s - already validated " % kwargs["biblicode"])

            except pymongo.errors.OperationFailure:
               print "Error updating publication %s: %s" % (kwargs["biblicode"], sys.exc_info()[0])
        except pymongo.errors.OperationFailure:
            print "Error inserting publication %s: %s" % (kwargs["biblicode"], sys.exc_info()[0])

        return True

    def remove_publication(self, _id):

        try:

            print "removing publication %s" % _id

            self.publications.remove({'_id': _id})

        except pymongo.errors.OperationFailure:
            print "oops, mongo error"
            return False

        return True

    # return an array of publications still open sorting descending for pub_date, in short format
    def get_open_publications(self, is_refeered, start_date=None, end_date=None, ):

        pub = []

        try:

            if not start_date and not end_date:

                cursor = self.publications.find({'is_open': True, 'is_refeered': is_refeered}
                                                ).sort('pub_date', pymongo.DESCENDING)

            else:

                cursor = self.publications.find({'is_open': True, 'is_refeered': is_refeered,
                                                 'pub_date': {'$gte': start_date, '$lte': end_date}}).sort('pub_date', direction=-1)

            for publication in cursor:

                pub.append({'title': publication['title'],
                            'authors': publication['authors'],
                            'biblicode': publication['_id'],
                            'pub_date': publication['pub_date'].strftime("%B %Y"),
                            'is_refeered':publication['is_refeered']})

        except pymongo.errors.OperationFailure:
            print "oops, mongo error"
            return False

        return pub

    def get_publications_to_close(self, is_refeered, start_date, end_date, ):

        pub = []

        try:

            cursor = self.publications.find({'is_open': True, 'is_refeered': is_refeered,
                                             'pub_date': {'$gte': start_date, '$lte': end_date}}
                                            ).sort('pub_date', pymongo.DESCENDING)

            for publication in cursor:

                pub.append({'title': publication['title'],
                            'asdc_auth': publication['asdc_auth'],
                            'biblicode': publication['_id'],
                            'pub_date': publication['pub_date'].strftime("%B %Y"),
                            'mission': publication['mission'],
                            'is_refeered': publication['is_refeered'],
                            'DOI': publication['DOI']})

        except pymongo.errors.OperationFailure:
            print "oops, mongo error"
            return False

        return pub

     # returns an array of valide publications sorted for ascending pub_date, in short format
    def get_closed_publications(self, is_refeered, start_date=None, end_date=None):

        pub = []

        if not start_date and not end_date:

            cursor = self.publications.find({'is_open': False, 'is_refeered': is_refeered}).sort('pub_date')

        else:

            cursor = self.publications.find({"is_open": False, 'is_refeered': is_refeered,
                                            "pub_date": {"$gte": start_date, "$lte": end_date}
                                             }).sort('pub_date', pymongo.ASCENDING)

        for publication in cursor:

            pub.append({'title': publication['title'],
                        'URL': publication['URL'],
                        'authors': publication['authors'],
                        'asdc_auth': publication['asdc_auth'],
                        'mission': publication['mission'],
                        'biblicode': publication['_id'],
                        'pub_date': publication['pub_date'].strftime("%B %Y"),
                        'is_refeered': publication['is_refeered']})

        return pub

    def close_publication(self, biblicode):

        try:
            self.publications.update({"_id": biblicode},
                                     {"$set": {'is_open': False}})

        except pymongo.errors.OperationFailure:
            print "Mongo error, closing publication %s" % biblicode
            return False
        return True

    # this is needed at user level
    def get_publication_to_validate(self, author, is_refeered):

        cursor = self.publications.find({'asdc_auth.author': author, 'is_refeered': is_refeered,
                                         "is_open": True}).sort('pub_date', direction=1)
        pub = []

        for publication in cursor:

            pub.append({'title': publication['title'],
                        'asdc_auth': publication['asdc_auth'],
                        'authors': publication['authors'],
                        'biblicode': publication['_id'],
                        'pub_date': publication['pub_date'].strftime("%B %Y"),
                        'mission': publication['mission'],
                        'is_refeered':publication['is_refeered'],
                        'DOI': publication['DOI']})

        return pub

    # this is needed at user level
    #user has to specify in the publications are not valid
    def invalidate_publication(self, biblicode, user):

        try:
            #to find the author list
            record = self.publications.find_one({'_id': biblicode}, {'authors': 1, '_id': 0})

            #update on the publication entry for valide and update the title for the user (remove his/her part)
            self.publications.update({'_id': biblicode, 'asdc_auth.author': user},
                                     {'$set': {'asdc_auth.$.validate': False,
                                               'authors': handle_asdc_author.update_asdc_authors(record['authors'], user)}})

        except pymongo.errors.OperationFailure as e:
            print "Mongo error, closing publication %s" % biblicode
            return False
        return True

    def update_authors_mission(self, biblicode, auth_list):

        try:
            #to find the author list
            record = self.publications.find_one({'_id': biblicode}, {'authors': 1, '_id': 0})
            asdc_names = [(asdc.split("_"))[0] for asdc in auth_list]
            #update the entry and update the asdc authors and total authors
            self.publications.update({'_id': biblicode},
                                     {'$set':
                                            {'asdc_auth': [dict(author=usr, validate=True)for usr in asdc_names],
                                             'authors': handle_asdc_author.overwrite_asdc_authors(record['authors'],
                                                                                auth_list)}})

        except pymongo.errors.OperationFailure as e:
            print e
            print "Mongo error, updating authors per biblicode %s" % biblicode
            return False
        return True

    # this is needed at user level
    def update_missions(self, biblicode, missions_list):

        try:
            self.publications.update({'_id': biblicode},
                                     {'$set': {'mission': missions_list}})

        except pymongo.errors.OperationFailure:
            print "Mongo error, updating missions in publication %s" % biblicode
            return False
        return True

    # here methods for publications search (the search is done only on the close publications):
    # the search can be done
    # 1- biblicode (return single publication with detail)
    # 2- DOI       (return single publication with detail)
    # 3- Author    (return a list of publications)
    # 4- Mission   (return a list of publications)
    # 5- Magazine  (return a list of publications)

    # find a publiction corresponding to a particular biblicode
    def get_publication_by_biblicode(self, biblicode):

        publication = self.publications.find_one({'_id':  biblicode})

        pub = None

        if publication:

            pub = dict(title=publication['title'], authors=publication['authors'],
                       biblicode=publication['_id'], pub_date=publication['pub_date'].strftime("%B %Y"),
                       is_refeered=publication['is_refeered'], URL=publication['URL'],
                       is_open=publication['is_open'],
                       DOI=publication['DOI'], Origin=publication['Origin'],
                       Abstract=publication['Abstract'], Keywords=publication["Keywords"])

        return pub

    #return an array of publications that match with the biblicode pattern
    def get_publications_by_biblicode(self, biblicode, is_refeered):

        publications = self.publications.find({'_id': {'$regex': biblicode},
                                               'is_refeered': is_refeered,
                                               'is_open': False})

        pub = []

        for p in publications:

            pub.append({'title': p['title'],
                        'authors': p['authors'],
                        'URL': p['URL'],
                        'biblicode': p['_id'],
                        'pub_date': p['pub_date'].strftime("%B %Y"),
                        'is_refeered': p['is_refeered']})

        return pub

     #return an array of publications that match with the DOI pattern
    def get_publications_by_DOI(self, DOI, is_refeered):

        publications = self.publications.find({'DOI': {'$regex': DOI},
                                               'is_refeered': is_refeered,
                                               'is_open': False})

        pub = []

        for p in publications:

            pub.append({'title': p['title'],
                        'authors': p['authors'],
                        'URL': p['URL'],
                        'biblicode': p['_id'],
                        'pub_date': p['pub_date'].strftime("%B %Y"),
                        'is_refeered': p['is_refeered']})

        return pub

    #returns an array of valide publications per author
    def get_closed_publications_author(self, author, is_refeered, start_date=None, end_date=None, mission=None):

        pipe = None

        if not start_date and not end_date and not mission:

            pipe = [{'$unwind': '$asdc_auth'},
                    {'$match': {'is_refeered': is_refeered, 'is_open': False,
                                'asdc_auth.validate': True, 'asdc_auth.author': author}},
                    {'$sort': {'pub_date': -1}}]

        elif not start_date and not end_date and mission:

            pipe = [{'$unwind': '$asdc_auth'},
                    {'$match': {'is_refeered': is_refeered, 'is_open': False, 'mission': mission,
                                'asdc_auth.validate': True, 'asdc_auth.author': author}},
                    {'$sort': {'pub_date': -1}}]

        elif start_date and end_date and not mission:

            pipe = [{'$unwind': '$asdc_auth'},
                    {'$match': {'is_refeered': is_refeered, 'is_open': False,
                                'asdc_auth.validate': True, 'asdc_auth.author': author,
                                'pub_date': {'$gte': start_date, '$lte': end_date}}},
                    {'$sort': {'pub_date': -1}}]

        elif start_date and end_date and mission:

            pipe = [{'$unwind': '$asdc_auth'},
                    {'$match': {'is_refeered': is_refeered, 'is_open': False, 'mission': mission,
                                'asdc_auth.validate': True, 'asdc_auth.author': author,
                                'pub_date': {'$gte': start_date, '$lte': end_date}}},
                    {'$sort': {'pub_date': -1}}]

        res = self.publications.aggregate(pipeline=pipe)
        pub = []

        for publication in res['result']:

            pub.append({'title': publication['title'],
                        'authors': publication['authors'],
                        'URL': publication['URL'],
                        'biblicode': publication['_id'],
                        'pub_date': publication['pub_date'].strftime("%B %Y"),
                        'is_refeered': publication['is_refeered']})

        return pub

    def get_closed_publications_mission(self, mission, is_refeered, start_date=None, end_date=None):

        cursor = []

        if not start_date and not end_date:

            cursor = self.publications.find({'mission': {'$regex': mission, '$options': 'i'},
                                             'is_refeered': is_refeered,
                                             "is_open": False}).sort('pub_date', pymongo.DESCENDING)
        elif start_date and end_date:

            cursor = self.publications.find({'mission': {'$regex': mission, '$options': 'i'},
                                             'is_refeered': is_refeered,
                                             'pub_date': {'$gte': start_date, '$lte': end_date},
                                             "is_open": False}).sort('pub_date', pymongo.DESCENDING)
        pub = []

        for publication in cursor:

            pub.append({'title': publication['title'],
                        'URL': publication['URL'],
                        'authors': publication['authors'],
                        'biblicode': publication['_id'],
                        'pub_date': publication['pub_date'].strftime("%B %Y"),
                        'is_refeered': publication['is_refeered']})

        return pub

    def get_closed_publications_journal(self, journal, is_refeered, start_date=None, end_date=None):

        cursor = []

        if not start_date and not end_date:

            cursor = self.publications.find({'Magazine': {'$regex': journal, '$options': 'i'},
                                             'is_refeered': is_refeered,
                                             "is_open": False}).sort('pub_date', pymongo.DESCENDING)
        elif start_date and end_date:

            cursor = self.publications.find({'Magazine': {'$regex': journal, '$options': 'i'},
                                             'is_refeered': is_refeered,
                                             'pub_date': {'$gte': start_date, '$lte': end_date},
                                             "is_open": False}).sort('pub_date', pymongo.DESCENDING)
        pub = []

        for publication in cursor:

            pub.append({'title': publication['title'],
                        'URL': publication['URL'],
                        'authors': publication['authors'],
                        'biblicode': publication['_id'],
                        'pub_date': publication['pub_date'].strftime("%B %Y"),
                        'is_refeered': publication['is_refeered']})

        return pub


text:
module Carto
  module Db
    class InvalidConfiguration < RuntimeError; end

    class Connection

      SCHEMA_PUBLIC = 'public'.freeze
      SCHEMA_CARTODB = 'cartodb'.freeze
      SCHEMA_IMPORTER = 'cdb_importer'.freeze
      SCHEMA_GEOCODING = 'cdb'.freeze
      SCHEMA_CDB_DATASERVICES_API = 'cdb_dataservices_client'.freeze
      SCHEMA_AGGREGATION_TABLES = 'aggregation'.freeze

      class << self
        def connect(db_host, db_name, options = {})
          validate_options(options)
          if options[:statement_timeout]
            filtered_options = options.reject { |k, _| k == :statement_timeout }
            _, conn = connect(db_host, db_name, filtered_options)
            conn.execute(%{ SET statement_timeout TO #{options[:statement_timeout]} })
          end

          configuration = get_db_configuration_for(db_host, db_name, options)

          conn = $pool.fetch(configuration) do
            get_database(options, configuration)
          end

          database = Carto::Db::Database.new(db_host, conn)

          if block_given?
            yield(database, conn)
          else
            return database, conn
          end
        ensure
          if options[:statement_timeout]
            filtered_options = options.reject { |k, _| k == :statement_timeout }
            _, conn = connect(db_host, db_name, filtered_options)
            conn.execute(%{ SET statement_timeout TO DEFAULT })
          end
        end

        private

        def get_database(options, configuration)
          resolver = ActiveRecord::Base::ConnectionSpecification::Resolver.new(
            configuration, get_connection_name(options[:as])
          )
          conn = ActiveRecord::Base.connection_handler.establish_connection(
            get_connection_name(options[:as]), resolver.spec
          ).connection

          # TODO: Maybe we should avoid doing this kind of operations here or remove it because
          #       all internal calls to functions should use the schema name like if we were using
          #       namespaces to avoid collisions and problems
          if options[:as] != :cluster_admin
            conn.execute(%{ SET search_path TO #{build_search_path(options[:user_schema])} })
          end
          conn
        end

        def build_search_path(user_schema, quote_user_schema = true)
          quote_char = quote_user_schema ? "\"" : ""
          "#{quote_char}#{user_schema}#{quote_char}, #{SCHEMA_CARTODB}, #{SCHEMA_CDB_DATASERVICES_API}, #{SCHEMA_PUBLIC}"
        end

        def get_connection_name(kind = :carto_db_connection)
          kind.to_s
        end

        def get_db_configuration_for(db_host, db_name, options)
          logger = (Rails.env.development? || Rails.env.test? ? ::Rails.logger : nil)

          # TODO: proper AR config when migration is complete
          base_config = ::SequelRails.configuration.environment_for(Rails.env)
          config = {
            orm:      'ar',
            adapter:  "postgresql",
            logger:   logger,
            host:     db_host,
            username: base_config['username'],
            password: base_config['password'],
            database: db_name,
            port:     base_config['port'],
            encoding: base_config['encoding'].nil? ? 'unicode' : base_config['encoding']
          }

          case options[:as]
          when :superuser
            config
          when :cluster_admin
            config.merge(
              database: 'postgres'
            )
          when :public_user
            config.merge(
              username: CartoDB::PUBLIC_DB_USER,
              password: CartoDB::PUBLIC_DB_USER_PASSWORD
            )
          when :public_db_user
            config.merge(
              username: options[:username],
              password: CartoDB::PUBLIC_DB_USER_PASSWORD
            )
          else
            config.merge(
              username: options[:username],
              password: options[:password]
            )
          end
        end

        def validate_options(options)
          if !options[:user_schema] && options[:as] != :cluster_admin
            CartoDB::Logger.error(message: 'Connection needs user schema if the user is not the cluster admin',
                                  params: { user_type: options[:as],
                                            username: options[:username],
                                            schema: options[:user_schema] })
            raise Carto::Db::InvalidConfiguration.new('Connection needs user schema if user is not the cluster admin')
          end

          ## If we don't pass user type we are using a regular user and username/password is mandatory
          if !options[:as] && (!options[:username] || !options[:password])
            CartoDB::Logger.error(message: 'Db connection needs username/password for regular user',
                                  params: { user_type: options[:as], username: options[:username] })
            raise Carto::Db::InvalidConfiguration.new('Db connection needs user username/password for regular user')
          end
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
Ext.ns('MShop');

MShop.UrlManager = function(href) {
    this.href = href || null;
    this.tmpl = new Ext.Template(MShop.config.urlTemplate);
    this.data = {
        site : MShop.config.site['locale.site.code'],
        lang : MShop.i18n.lang,
        tab : MShop.config.activeTab
    };
};

MShop.UrlManager.prototype = {
    redirect : function(config) {
        if(typeof config == 'object') {
            if(config.hasOwnProperty('site')) {
                this.setSiteCode(config.site);
            }

            if(MShop.i18n.hasOwnProperty('lang')) {
                this.setLanguageCode(config.lang);
            }

            if(config.hasOwnProperty('tab')) {
                this.setActiveTab(config.tab);
            }
        }
        window.location.href = this.tmpl.apply(this.data);
    },

    setActiveTab : function(value) {
        this.data.tab = parseInt(value, 10);
    },

    getActiveTab : function() {
        return this.data.tab;
    },

    getLanguageCode : function() {
        return this.data.lang;
    },

    setSiteCode : function(siteCode) {
        this.data.site = siteCode;
    },

    setLanguageCode : function(languageCode) {
        this.data.lang = languageCode;
    },

    getAbsoluteUrl : function(url) {

        if(url.substr(0, 4) !== 'http' && url.substr(0, 5) !== 'data:') {
            return MShop.config.baseurl.content + '/' + url;
        }

        return url;
    }
};


text:
require 'rails_helper'

RSpec.describe Mark, type: :model do
  describe '(factory)' do
    context ':mark_only' do
      subject { build(:mark_only) }
      it { is_expected.to_not be_valid }
    end

    context ':mark' do
      subject { build(:mark) }
      it { is_expected.to be_valid }
    end
  end

  describe '#date' do
    it { is_expected.to validate_presence_of(:date) }
  end

  describe '#goal' do
    it { is_expected.to belong_to(:goal) }
    it { is_expected.to validate_presence_of(:goal) }
  end

  describe '#value' do
    it { is_expected.to validate_presence_of(:value) }
    it do
      is_expected.to validate_numericality_of(:value)
        .only_integer
        .is_greater_than_or_equal_to(0)
        .is_less_than_or_equal_to(1000000000)
    end
  end
end


text:
namespace Falcor
{
    public abstract class SimpleKey : KeySegment
    {
        public override bool IsSimpleKey => true;
        public override KeySet AsKeySet() => new KeySet(this);

        public static implicit operator SimpleKey(string value) => new StringKey(value);

        public static implicit operator SimpleKey(bool value) => new BooleanKey(value);
    }
}


text:
import json
import logging
import os

from .env import DVC_NO_ANALYTICS

logger = logging.getLogger(__name__)

def collect_and_send_report(args=None, return_code=None):
    """
    Collect information from the runtime/environment and the command
    being executed into a report and send it over the network.

    To prevent analytics from blocking the execution of the main thread,
    sending the report is done in a separate process.

    The inter-process communication happens through a file containing the
    report as a JSON, where the _collector_ generates it and the _sender_
    removes it after sending it.
    """
    import tempfile

    from dvc.daemon import daemon

    report = {}

    # Include command execution information on the report only when available.
    if args and hasattr(args, "func"):
        report.update({"cmd_class": args.func.__name__})

    if return_code is not None:
        report.update({"cmd_return_code": return_code})

    with tempfile.NamedTemporaryFile(delete=False, mode="w") as fobj:
        json.dump(report, fobj)
    daemon(["analytics", fobj.name])

def is_enabled():
    from dvc.config import Config, to_bool
    from dvc.utils import env2bool

    if env2bool("DVC_TEST"):
        return False

    enabled = not os.getenv(DVC_NO_ANALYTICS)
    if enabled:
        enabled = to_bool(
            Config(validate=False).get("core", {}).get("analytics", "true")
        )

    logger.debug("Analytics is {}abled.".format("en" if enabled else "dis"))

    return enabled

def send(path):
    """
    Side effect: Removes the report after sending it.

    The report is generated and stored in a temporary file, see:
    `collect_and_send_report`. Sending happens on another process,
    thus, the need of removing such file afterwards.
    """
    import requests

    url = "https://analytics.dvc.org"
    headers = {"content-type": "application/json"}

    with open(path, encoding="utf-8") as fobj:
        report = json.load(fobj)

    report.update(_runtime_info())

    try:
        requests.post(url, json=report, headers=headers, timeout=5)
    except requests.exceptions.RequestException:
        logger.debug("failed to send analytics report", exc_info=True)

    os.remove(path)

def _scm_in_use():
    from dvc.exceptions import NotDvcRepoError
    from dvc.repo import Repo
    from dvc.scm import SCM, NoSCM
    from dvc.scm.base import SCMError

    try:
        scm = SCM(root_dir=Repo.find_root())
        return type(scm).__name__
    except SCMError:
        return NoSCM.__name__
    except NotDvcRepoError:
        pass

def _runtime_info():
    """
    Gather information from the environment where DVC runs to fill a report.
    """
    from dvc import __version__
    from dvc.utils import is_binary

    return {
        "dvc_version": __version__,
        "is_binary": is_binary(),
        "scm_class": _scm_in_use(),
        "system_info": _system_info(),
        "user_id": _find_or_create_user_id(),
    }

def _system_info():
    import platform
    import sys

    import distro

    system = platform.system()

    if system == "Windows":
        version = sys.getwindowsversion()

        return {
            "os": "windows",
            "windows_version_build": version.build,
            "windows_version_major": version.major,
            "windows_version_minor": version.minor,
            "windows_version_service_pack": version.service_pack,
        }

    if system == "Darwin":
        return {"os": "mac", "mac_version": platform.mac_ver()[0]}

    if system == "Linux":
        return {
            "os": "linux",
            "linux_distro": distro.id(),
            "linux_distro_like": distro.like(),
            "linux_distro_version": distro.version(),
        }

    # We don't collect data for any other system.
    raise NotImplementedError

def _find_or_create_user_id():
    """
    The user's ID is stored on a file under the global config directory.

    The file should contain a JSON with a "user_id" key:

        {"user_id": "16fd2706-8baf-433b-82eb-8c7fada847da"}

    IDs are generated randomly with UUID.
    """
    import uuid

    from dvc.config import Config
    from dvc.lock import Lock, LockError
    from dvc.utils.fs import makedirs

    config_dir = Config.get_dir("global")
    fname = os.path.join(config_dir, "user_id")
    lockfile = os.path.join(config_dir, "user_id.lock")

    # Since the `fname` and `lockfile` are under the global config,
    # we need to make sure such directory exist already.
    makedirs(config_dir, exist_ok=True)

    try:
        with Lock(lockfile):
            try:
                with open(fname, encoding="utf-8") as fobj:
                    user_id = json.load(fobj)["user_id"]

            except (FileNotFoundError, ValueError, KeyError):
                user_id = str(uuid.uuid4())

                with open(fname, "w", encoding="utf-8") as fobj:
                    json.dump({"user_id": user_id}, fobj)

            return user_id

    except LockError:
        logger.debug(f"Failed to acquire '{lockfile}'")


text:
use super::*;
use eth2_hashing::hash;

/// Merkleizes bytes and returns the root, using a simple algorithm that does not optimize to avoid
/// processing or storing padding bytes.
///
/// **Note**: This function is generally worse than using the `crate::merkle_root` which uses
/// `MerkleHasher`. We only keep this function around for reference testing.
///
/// The input `bytes` will be padded to ensure that the number of leaves is a power-of-two.
///
/// ## CPU Performance
///
/// Will hash all nodes in the tree, even if they are padding and pre-determined.
///
/// ## Memory Performance
///
///  - Duplicates the input `bytes`.
///  - Stores all internal nodes, even if they are padding.
///  - Does not free up unused memory during operation.
pub fn merkleize_standard(bytes: &[u8]) -> Hash256 {
    // If the bytes are just one chunk (or less than one chunk) just return them.
    if bytes.len() <= HASHSIZE {
        let mut o = bytes.to_vec();
        o.resize(HASHSIZE, 0);
        return Hash256::from_slice(&o[0..HASHSIZE]);
    }

    let leaves = num_sanitized_leaves(bytes.len());
    let nodes = num_nodes(leaves);
    let internal_nodes = nodes - leaves;

    let num_bytes = std::cmp::max(internal_nodes, 1) * HASHSIZE + bytes.len();

    let mut o: Vec<u8> = vec![0; internal_nodes * HASHSIZE];

    o.append(&mut bytes.to_vec());

    assert_eq!(o.len(), num_bytes);

    let empty_chunk_hash = hash(&[0; MERKLE_HASH_CHUNK]);

    let mut i = nodes * HASHSIZE;
    let mut j = internal_nodes * HASHSIZE;

    while i >= MERKLE_HASH_CHUNK {
        i -= MERKLE_HASH_CHUNK;

        j -= HASHSIZE;
        let hash = match o.get(i..i + MERKLE_HASH_CHUNK) {
            // All bytes are available, hash as usual.
            Some(slice) => hash(slice),
            // Unable to get all the bytes.
            None => {
                match o.get(i..) {
                    // Able to get some of the bytes, pad them out.
                    Some(slice) => {
                        let mut bytes = slice.to_vec();
                        bytes.resize(MERKLE_HASH_CHUNK, 0);
                        hash(&bytes)
                    }
                    // Unable to get any bytes, use the empty-chunk hash.
                    None => empty_chunk_hash.clone(),
                }
            }
        };

        o[j..j + HASHSIZE].copy_from_slice(&hash);
    }

    Hash256::from_slice(&o[0..HASHSIZE])
}

fn num_sanitized_leaves(num_bytes: usize) -> usize {
    let leaves = (num_bytes + HASHSIZE - 1) / HASHSIZE;
    leaves.next_power_of_two()
}

fn num_nodes(num_leaves: usize) -> usize {
    2 * num_leaves - 1
}


text:
{-|
Module      : Database.Relational.Where
Description : Definition of WHERE.
Copyright   : (c) Alexander Vieth, 2015
Licence     : BSD3
Maintainer  : aovieth@gmail.com
Stability   : experimental
Portability : non-portable (GHC only)
-}

{-# LANGUAGE AutoDeriveTypeable #-}
{-# LANGUAGE PolyKinds #-}

module Database.Relational.Where (

      WHERE(..)

    ) where

data WHERE relation condition = WHERE relation condition


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Interface IAgentService
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Interface IAgentService
   ">
    <meta name="generator" content="docfx 2.52.0.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Interface IAgentService

Namespace: SchedulingClients.Core.AgentServiceReference

Assembly: SchedulingClients.Core.dll

Syntax

[ServiceContract(ConfigurationName = "AgentServiceReference.IAgentService")]
public interface IAgentService

Methods

    |
    Improve this Doc

    View Source

GetAllAgentData()

Declaration

[OperationContract(Action = "http://tempuri.org/IAgentService/GetAllAgentData", ReplyAction = "http://tempuri.org/IAgentService/GetAllAgentDataResponse")]
ServiceCallResultDto<AgentDto[]> GetAllAgentData()

Returns

        Type
        Description

        GAAPICommon.Core.Dtos.ServiceCallResultDto<GAAPICommon.Core.Dtos.AgentDto[]>

    |
    Improve this Doc

    View Source

GetAllAgentDataAsync()

Declaration

[OperationContract(Action = "http://tempuri.org/IAgentService/GetAllAgentData", ReplyAction = "http://tempuri.org/IAgentService/GetAllAgentDataResponse")]
Task<ServiceCallResultDto<AgentDto[]>> GetAllAgentDataAsync()

Returns

        Type
        Description

        System.Threading.Tasks.Task<GAAPICommon.Core.Dtos.ServiceCallResultDto<GAAPICommon.Core.Dtos.AgentDto[]>>

    |
    <a href="https://github.com/GuidanceAutomation/SchedulingClients/new/devel/apiSpec/new?filename=SchedulingClients_Core_AgentServiceReference_IAgentService_GetAllAgentsInLifetimeState_GAAPICommon_Architecture_AgentLifetimeState_.md&value=---%0Auid%3A%20SchedulingClients.Core.AgentServiceReference.IAgentService.GetAllAgentsInLifetimeState(GAAPICommon.Architecture.AgentLifetimeState)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

    View Source

GetAllAgentsInLifetimeState(AgentLifetimeState)

Declaration

[OperationContract(Action = "http://tempuri.org/IAgentService/GetAllAgentsInLifetimeState", ReplyAction = "http://tempuri.org/IAgentService/GetAllAgentsInLifetimeStateResponse")]
ServiceCallResultDto<AgentDto[]> GetAllAgentsInLifetimeState(AgentLifetimeState agentLifetimeState)

Parameters

        Type
        Name
        Description

        GAAPICommon.Architecture.AgentLifetimeState
        agentLifetimeState

Returns

        Type
        Description

        GAAPICommon.Core.Dtos.ServiceCallResultDto<GAAPICommon.Core.Dtos.AgentDto[]>

    |
    <a href="https://github.com/GuidanceAutomation/SchedulingClients/new/devel/apiSpec/new?filename=SchedulingClients_Core_AgentServiceReference_IAgentService_GetAllAgentsInLifetimeStateAsync_GAAPICommon_Architecture_AgentLifetimeState_.md&value=---%0Auid%3A%20SchedulingClients.Core.AgentServiceReference.IAgentService.GetAllAgentsInLifetimeStateAsync(GAAPICommon.Architecture.AgentLifetimeState)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

    View Source

GetAllAgentsInLifetimeStateAsync(AgentLifetimeState)

Declaration

[OperationContract(Action = "http://tempuri.org/IAgentService/GetAllAgentsInLifetimeState", ReplyAction = "http://tempuri.org/IAgentService/GetAllAgentsInLifetimeStateResponse")]
Task<ServiceCallResultDto<AgentDto[]>> GetAllAgentsInLifetimeStateAsync(AgentLifetimeState agentLifetimeState)

Parameters

        Type
        Name
        Description

        GAAPICommon.Architecture.AgentLifetimeState
        agentLifetimeState

Returns

        Type
        Description

        System.Threading.Tasks.Task<GAAPICommon.Core.Dtos.ServiceCallResultDto<GAAPICommon.Core.Dtos.AgentDto[]>>

    |
    Improve this Doc

    View Source

GetAPISemVer()

Declaration

[OperationContract(Action = "http://tempuri.org/IService/GetAPISemVer", ReplyAction = "http://tempuri.org/IService/GetAPISemVerResponse")]
ServiceCallResultDto<SemVerDto> GetAPISemVer()

Returns

        Type
        Description

        GAAPICommon.Core.Dtos.ServiceCallResultDto<GAAPICommon.Core.Dtos.SemVerDto>

    |
    Improve this Doc

    View Source

GetAPISemVerAsync()

Declaration

[OperationContract(Action = "http://tempuri.org/IService/GetAPISemVer", ReplyAction = "http://tempuri.org/IService/GetAPISemVerResponse")]
Task<ServiceCallResultDto<SemVerDto>> GetAPISemVerAsync()

Returns

        Type
        Description

        System.Threading.Tasks.Task<GAAPICommon.Core.Dtos.ServiceCallResultDto<GAAPICommon.Core.Dtos.SemVerDto>>

    |
    <a href="https://github.com/GuidanceAutomation/SchedulingClients/new/devel/apiSpec/new?filename=SchedulingClients_Core_AgentServiceReference_IAgentService_SetAgentLifetimeState_System_Int32_GAAPICommon_Architecture_AgentLifetimeState_.md&value=---%0Auid%3A%20SchedulingClients.Core.AgentServiceReference.IAgentService.SetAgentLifetimeState(System.Int32%2CGAAPICommon.Architecture.AgentLifetimeState)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

    View Source

SetAgentLifetimeState(Int32, AgentLifetimeState)

Declaration

[OperationContract(Action = "http://tempuri.org/IAgentService/SetAgentLifetimeState", ReplyAction = "http://tempuri.org/IAgentService/SetAgentLifetimeStateResponse")]
[ServiceKnownType(typeof(ServiceCallResultDto<AgentDto[]>))]
[ServiceKnownType(typeof(ServiceCallResultDto<SemVerDto>))]
ServiceCallResultDto SetAgentLifetimeState(int agentId, AgentLifetimeState desiredState)

Parameters

        Type
        Name
        Description

        System.Int32
        agentId

        GAAPICommon.Architecture.AgentLifetimeState
        desiredState

Returns

        Type
        Description

        GAAPICommon.Core.Dtos.ServiceCallResultDto

    |
    <a href="https://github.com/GuidanceAutomation/SchedulingClients/new/devel/apiSpec/new?filename=SchedulingClients_Core_AgentServiceReference_IAgentService_SetAgentLifetimeStateAsync_System_Int32_GAAPICommon_Architecture_AgentLifetimeState_.md&value=---%0Auid%3A%20SchedulingClients.Core.AgentServiceReference.IAgentService.SetAgentLifetimeStateAsync(System.Int32%2CGAAPICommon.Architecture.AgentLifetimeState)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

    View Source

SetAgentLifetimeStateAsync(Int32, AgentLifetimeState)

Declaration

[OperationContract(Action = "http://tempuri.org/IAgentService/SetAgentLifetimeState", ReplyAction = "http://tempuri.org/IAgentService/SetAgentLifetimeStateResponse")]
Task<ServiceCallResultDto> SetAgentLifetimeStateAsync(int agentId, AgentLifetimeState desiredState)

Parameters

        Type
        Name
        Description

        System.Int32
        agentId

        GAAPICommon.Architecture.AgentLifetimeState
        desiredState

Returns

        Type
        Description

        System.Threading.Tasks.Task<GAAPICommon.Core.Dtos.ServiceCallResultDto>

                    Improve this Doc

                    View Source

              Back to top

            Generated by DocFX


text:
'use strict';

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const playerSchema = require("./player").schema;

/**
* Schema for a team
*/
const teamSchema = new Schema({
    team_name : {type : String, required : true},
    divisions : {},
    shortID : {type : String, required : true},
    registration_number : String
});

/**
* Gets a team's record
* @param tournament tournament to check
* @return team record
*/
teamSchema.methods.getRecord = function(tournament) {
    const record = {wins : 0, losses : 0, ties : 0};
    tournament.games.forEach(current => {
        if ((current.team1.team_id == this._id && current.team1.score > current.team2.score)
                || (current.team2.team_id == this._id && current.team2.score > current.team1.score)) {
            record.wins++;
        } else if ((current.team1.team_id == this._id && current.team1.score < current.team2.score)
                || (current.team2.team_id == this._id && current.team2.score < current.team1.score)) {
            record.losses++;
        } else if ((current.team1.team_id == this._id && current.team1.score == current.team2.score)
                || (current.team2.team_id == this._id && current.team2.score == current.team1.score)) {
            record.ties++;
        }
    });
    return record;
}

/**
* Get's a team's record given constraints
* @param tournament tournament to check
* @param constraints bounds on rounds
*/
teamSchema.methods.getRecordFiltered = function(tournament, constraints) {
    const record = {"wins" : 0, "losses" : 0, "ties" : 0};
    const filteredGames = tournament.games.filter(game => {
        return game.round >= constraints.minround && game.round <= constraints.maxround;
    });
    filteredGames.forEach(current => {
        if ((current.team1.team_id == this._id && current.team1.score > current.team2.score)
                || (current.team2.team_id == this._id && current.team2.score > current.team1.score)) {
            record.wins++;
        } else if ((current.team1.team_id == this._id && current.team1.score < current.team2.score)
                || (current.team2.team_id == this._id && current.team2.score < current.team1.score)) {
            record.losses++;
        } else if ((current.team1.team_id == this._id && current.team1.score == current.team2.score)
                || (current.team2.team_id == this._id && current.team2.score == current.team1.score)) {
            record.ties++;
        }
    });
    return record;
}

/**
* Gets win percentage given a team's record
* @param record team's record
* @param team's win %
*/
teamSchema.methods.getWinPercentage = function(record) {
    if (record.wins + record.losses == 0) {
        return 0;
    } else {
        return +(record.wins / (record.wins + record.losses)).toFixed(3);
    }
}

/**
* Gets a team's ppg
* @param tournament tournament to check
* @return team ppg
*/
teamSchema.methods.getPointsPerGame = function(tournament) {
    let totalPoints = 0;
    let totalGames = 0;
    tournament.games.forEach(currentGame => {
        if (currentGame.team1.team_id == this._id) {
            totalPoints += currentGame.team1.score;
            totalGames++;
        } else if (currentGame.team2.team_id == this._id) {
            totalPoints += currentGame.team2.score;
            totalGames++;
        }
    });
    if (totalGames == 0) {
        return 0;
    } else {
        return (totalPoints / totalGames).toFixed(2);
    }
}

/**
* Gets a team's ppg given constraints
* @param tournament tournament to check
* @param constraints limits on rounds
*/
teamSchema.methods.getPointsPerGameFiltered = function(tournament, constraints) {
    let totalPoints = 0;
    let totalGames = 0;
    const filteredGames = tournament.games.filter(game => {
        return game.round >= constraints.minround && game.round <= constraints.maxround;
    });
    filteredGames.forEach(currentGame => {
        if (currentGame.team1.team_id == this._id) {
            totalPoints += currentGame.team1.score;
            totalGames++;
        } else if (currentGame.team2.team_id == this._id) {
            totalPoints += currentGame.team2.score;
            totalGames++;
        }
    });
    if (totalGames == 0) {
        return 0;
    } else {
        return (totalPoints / totalGames).toFixed(2);
    }
}

/**
* Get a team's opponent ppg
* @param tournament tournament to check
* @return opponent ppg
*/
teamSchema.methods.getOpponentPPG = function(tournament) {
    let totalPoints = 0;
    let totalGames = 0;
    tournament.games.forEach(currentGame => {
        if (currentGame.team1.team_id == this._id) {
            totalPoints += currentGame.team2.score;
            totalGames++;
        } else if (currentGame.team2.team_id == this._id) {
            totalPoints += currentGame.team1.score;
            totalGames++;
        }
    });
    if (totalGames == 0) {
        return 0;
    } else {
        return +(totalPoints / totalGames).toFixed(2);
    }
}

/**
* Get a team's opponent ppg given constraints
* @param tournament tournament to check
* @param constraints bounds on rounds
*/
teamSchema.methods.getOpponentPPGFiltered = function(tournament, constraints) {
    let totalPoints = 0;
    let totalGames = 0;
    const filteredGames = tournament.games.filter(game => {
        return game.round >= constraints.minround && game.round <= constraints.maxround;
    });
    filteredGames.forEach(currentGame => {
        if (currentGame.team1.team_id == this._id) {
            totalPoints += currentGame.team2.score;
            totalGames++;
        } else if (currentGame.team2.team_id == this._id) {
            totalPoints += currentGame.team1.score;
            totalGames++;
        }
    });
    if (totalGames == 0) {
        return 0;
    } else {
        return +(totalPoints / totalGames).toFixed(2);
    }
}

/**
* Get a team's total tossups
* @param tournament tournament to check
* @return a team's total tossups in JSON
*/
teamSchema.methods.getTossupTotals = function(tournament) {
    const pointTotals = {};
    for (let pointValue in tournament.pointScheme) {
        if (tournament.pointScheme.hasOwnProperty(pointValue)) {
            pointTotals[pointValue] = 0;
        }
    }
    tournament.games.forEach(current => {
        if (current.team1.team_id == this._id && current.team1.playerStats) {
            for (let player in current.team1.playerStats) {
                if (current.team1.playerStats.hasOwnProperty(player)) {
                    const stats = current.team1.playerStats[player];
                    for (let pointValue in tournament.pointScheme) {
                        if (tournament.pointScheme.hasOwnProperty(pointValue)) {
                            if (stats[pointValue] && pointTotals[pointValue] != undefined) {
                                pointTotals[pointValue] += parseFloat(stats[pointValue]);
                            }
                        }
                    }
                }
            }
        } else if (current.team2.team_id == this._id && current.team2.playerStats) {
            for (let player in current.team2.playerStats) {
                if (current.team2.playerStats.hasOwnProperty(player)) {
                    const stats = current.team2.playerStats[player];
                    for (let pointValue in tournament.pointScheme) {
                        if (tournament.pointScheme.hasOwnProperty(pointValue)) {
                            if (stats[pointValue] && pointTotals[pointValue] != undefined) {
                                pointTotals[pointValue] += parseFloat(stats[pointValue]);
                            }
                        }
                    }
                }
            }
        }
    });
    return pointTotals;
}

/**
* Get a team's total tossups
* @param tournament tournament to check
* @param constraints limits on rounds
* @return a team's total tossups in JSON
*/
teamSchema.methods.getTossupTotalsFiltered = function(tournament, constraints) {
    const pointTotals = {};
    for (let pointValue in tournament.pointScheme) {
        if (tournament.pointScheme.hasOwnProperty(pointValue)) {
            pointTotals[pointValue] = 0;
        }
    }
    const filteredGames = tournament.games.filter(function(game) {
        return game.round >= constraints.minround && game.round <= constraints.maxround;
    });
    filteredGames.forEach(current => {
        if (current.team1.team_id == this._id && current.team1.playerStats) {
            for (let player in current.team1.playerStats) {
                if (current.team1.playerStats.hasOwnProperty(player)) {
                    const stats = current.team1.playerStats[player];
                    for (let pointValue in tournament.pointScheme) {
                        if (tournament.pointScheme.hasOwnProperty(pointValue)) {
                            if (stats[pointValue] && pointTotals[pointValue] != undefined) {
                                pointTotals[pointValue] += parseFloat(stats[pointValue]);
                            }
                        }
                    }
                }
            }
        } else if (current.team2.team_id == this._id && current.team2.playerStats) {
            for (let player in current.team2.playerStats) {
                if (current.team2.playerStats.hasOwnProperty(player)) {
                    const stats = current.team2.playerStats[player];
                    for (let pointValue in tournament.pointScheme) {
                        if (tournament.pointScheme.hasOwnProperty(pointValue)) {
                            if (stats[pointValue] && pointTotals[pointValue] != undefined) {
                                pointTotals[pointValue] += parseFloat(stats[pointValue]);
                            }
                        }
                    }
                }
            }
        }
    });
    return pointTotals;
}

teamSchema.methods.getOvertimeGets = function(tournament) {
    const thisTeam = this;
    try {
        let numGets = tournament.games.filter(game => {
            return game.team1.team_id == thisTeam._id || game.team2.team_id == thisTeam._id;
        }).map(game => {
            if (game.team1.team_id == thisTeam._id) {
                return game.team1.overtimeTossupsGotten || 0;
            } else {
                return game.team2.overtimeTossupsGotten || 0;
            }
        }).reduce((prevTUTotal, currentTUTotal) => {
            return prevTUTotal + currentTUTotal;
        });
        return numGets;
    } catch (lengthZeroException) {
        return 0;
    }
}

teamSchema.methods.getOvertimeGetsFiltered = function(tournament, constraints) {
    const thisTeam = this;
    try {
        let numGets = tournament.games.filter(game => {
            return (game.team1.team_id == thisTeam._id || game.team2.team_id == thisTeam._id)
                && (game.round >= constraints.minround && game.round <= constraints.maxround);
        }).map(game => {
            if (game.team1.team_id == thisTeam._id) {
                return game.team1.overtimeTossupsGotten || 0;
            } else {
                return game.team2.overtimeTossupsGotten || 0;
            }
        }).reduce((prevTUTotal, currentTUTotal) => {
            return prevTUTotal + currentTUTotal;
        });
        return numGets;
    } catch (lengthZeroException) {
        return 0;
    }
}

teamSchema.methods.getOvertimeGetsOneGame = function(game) {
    if (game.team1.team_id == this._id) {
        return game.team1.overtimeTossupsGotten || 0;
    } else {
        return game.team2.overtimeTossupsGotten || 0;
    }
}

/**
* Get a team's tossups in one game by summing the player totals
* @param game game to check
* @param tournament to check
* @return tossup totals for one game
*/
teamSchema.methods.getTossupTotalsOneGame = function(game, tournament) {
    const pointTotals = {};
    for (let pointValue in tournament.pointScheme) {
        if (tournament.pointScheme.hasOwnProperty(pointValue)) {
            pointTotals[pointValue] = 0;
        }
    }
    if (game.team1.team_id == this._id && game.team1.playerStats) {
        for (let player in game.team1.playerStats) {
            if (game.team1.playerStats.hasOwnProperty(player)) {
                const stats = game.team1.playerStats[player];
                for (let pointValue in tournament.pointScheme) {
                    if (tournament.pointScheme.hasOwnProperty(pointValue)) {
                        if (stats[pointValue] && pointTotals[pointValue] != undefined) {
                            pointTotals[pointValue] += parseFloat(stats[pointValue]);
                        }
                    }
                }
            }
        }
    } else if (game.team2.team_id == this._id && game.team2.playerStats) {
        for (let player in game.team2.playerStats) {
            if (game.team2.playerStats.hasOwnProperty(player)) {
                const stats = game.team2.playerStats[player];
                for (let pointValue in tournament.pointScheme) {
                    if (tournament.pointScheme.hasOwnProperty(pointValue)) {
                        if (stats[pointValue] && pointTotals[pointValue] != undefined) {
                            pointTotals[pointValue] += parseFloat(stats[pointValue]);
                        }
                    }
                }
            }
        }
    }
    return pointTotals;

}

/**
* Get a team's total bous points
* @param tournament tournament to check
* @return total bonus points
*/
teamSchema.methods.getTotalBonusPoints = function(tournament) {
    const pointTotals = this.getTossupTotals(tournament);
    let totalPoints = 0;
    tournament.games.forEach(currentGame => {
        if (currentGame.team1.team_id == this._id) {
            totalPoints += currentGame.team1.score - currentGame.team1.bouncebacks;
        } else if (currentGame.team2.team_id == this._id) {
            totalPoints += currentGame.team2.score - currentGame.team2.bouncebacks;
        }
    });
    for (let point in pointTotals) {
        if (pointTotals.hasOwnProperty(point)) {
            totalPoints -= parseFloat(point) * parseFloat(pointTotals[point]);
        }
    }
    return totalPoints;
}

/**
* Get a team's total bous points given constraints
* @param tournament tournament to check
* @param constraints bounds on rounds
* @return total bonus points
*/
teamSchema.methods.getTotalBonusPointsFiltered = function(tournament, constraints) {
    const filteredGames = tournament.games.filter(game => {
        return game.round >= constraints.minround && game.round <= constraints.maxround;
    });
    const pointTotals = this.getTossupTotalsFiltered(tournament, constraints);
    let totalPoints = 0;
    filteredGames.forEach(currentGame => {
        if (currentGame.team1.team_id == this._id) {
            totalPoints += currentGame.team1.score - currentGame.team1.bouncebacks;
        } else if (currentGame.team2.team_id == this._id) {
            totalPoints += currentGame.team2.score - currentGame.team2.bouncebacks;
        }
    });
    for (let point in pointTotals) {
        if (pointTotals.hasOwnProperty(point)) {
            totalPoints -= parseFloat(point) * parseFloat(pointTotals[point]);
        }
    }
    return totalPoints;
}

/**
* Gets a team's bonus points for one game
* @param game game to check
* @param tournament tournament to check
* @return bonus points for team
*/
teamSchema.methods.getBonusPointsOneGame = function(game, tournament) {
    const pointTotals = this.getTossupTotalsOneGame(game, tournament);
    let bonusPoints = 0;
    if (game.team1.team_id == this._id) {
        bonusPoints += game.team1.score - game.team1.bouncebacks;
    } else {
        bonusPoints += game.team2.score - game.team2.bouncebacks;
    }
    for (let point in pointTotals) {
        if (pointTotals.hasOwnProperty(point)) {
            bonusPoints -= parseFloat(point) * parseFloat(pointTotals[point]);
        }
    }
    return bonusPoints;

}

/**
* Get total tossups a team has gotten
* @param tournament tournament to check
* @return team's total gets
*/
teamSchema.methods.getTotalGets = function(tournament) {
    const pointTotals = this.getTossupTotals(tournament);
    let totalGets = 0;
    for (let values in pointTotals) {
        if (pointTotals.hasOwnProperty(values) && tournament.pointsTypes[values] != "N") {
            totalGets += pointTotals[values];
        }
    }
    return totalGets;
}

/**
* Get total tossups a team has gotten given constraints
* @param tournament tournament to check
* @param constraints bounds on rounds
* @return team's total gets
*/
teamSchema.methods.getTotalGetsFiltered = function(tournament, constraints) {
    const pointTotals = this.getTossupTotalsFiltered(tournament, constraints);
    let totalGets = 0;
    for (let values in pointTotals) {
        if (pointTotals.hasOwnProperty(values) && tournament.pointsTypes[values] != "N") {
            totalGets += pointTotals[values];
        }
    }
    return totalGets;
}

/**
* Get total gets for one game
* @param game game to check
* @param tournament tournament to check
* @return total gets for one game
*/
teamSchema.methods.getTotalGetsOneGame = function(game, tournament) {
    const pointTotals = this.getTossupTotalsOneGame(game, tournament);
    let totalGets = 0;
    for (let values in pointTotals) {
        if (pointTotals.hasOwnProperty(values) && tournament.pointsTypes[values] != "N") {
            totalGets += pointTotals[values];
        }
    }
    return totalGets;
}

/**
* Get a team's total negs
* @param tournament tournament to check
* @return a team's total negs
*/
teamSchema.methods.getTotalNegs = function(tournament) {
    const pointTotals = this.getTossupTotals(tournament);
    let totalNegs = 0;
    for (let values in pointTotals) {
        if (pointTotals.hasOwnProperty(values) && tournament.pointsTypes[values] == "N") {
            totalNegs += pointTotals[values];
        }
    }
    return totalNegs;
}

/**
* Get total tossups a team has heard
* @param tournament tournament to check
* @return tossups heard
*/
teamSchema.methods.getTossupsHeard = function(tournament) {
    let totalTossups = 0;
    tournament.games.forEach(currentGame => {
        if (currentGame.team1.team_id == this._id || currentGame.team2.team_id == this._id) {
            totalTossups += currentGame.tossupsheard;
        }
    });
    return totalTossups;
}

/**
* Get total tossups a team has heard given constraints
* @param tournament tournament to check
* @param constraints bounds on rounds
* @return tossups heard
*/
teamSchema.methods.getTossupsHeardFiltered = function(tournament, constraints) {
    let totalTossups = 0;
    const filteredGames = tournament.games.filter(game => {
        return game.round >= constraints.minround && game.round <= constraints.maxround;
    });
    filteredGames.forEach(currentGame => {
        if (currentGame.team1.team_id == this._id || currentGame.team2.team_id == this._id) {
            totalTossups += currentGame.tossupsheard;
        }
    });
    return totalTossups;
}

/**
* Get a team's points per bonus
* @param tournament tournament to check
* @return team's overall points-per-bonus
*/
teamSchema.methods.getOverallPPB = function(tournament) {
    const totalBonusPoints = this.getTotalBonusPoints(tournament);
    const totalGets = this.getTotalGets(tournament) - this.getOvertimeGets(tournament);
    if (totalGets == 0) {
        return 0;
    }
    return +(totalBonusPoints / totalGets).toFixed(2);
}

/**
* Get a team's points per bonus given constraints
* @param tournament tournament to check
* @param constraints bounds on rounds
* @return team's overall points-per-bonus
*/
teamSchema.methods.getOverallPPBFiltered = function(tournament, constraints) {
    const totalBonusPoints = this.getTotalBonusPointsFiltered(tournament, constraints);
    const totalGets = this.getTotalGetsFiltered(tournament, constraints) - this.getOvertimeGetsFiltered(tournament, constraints);
    if (totalGets == 0) {
        return 0;
    }
    return +(totalBonusPoints / totalGets).toFixed(2);
}

/**
* Get a team's ppb for one game
* @param game game to check
* @param tournament tournament to check
* @return points-per-bonus for one game
*/
teamSchema.methods.getPPBOneGame = function(game, tournament) {
    const bonusPoints = this.getBonusPointsOneGame(game, tournament);
    const totalGets = this.getTotalGetsOneGame(game, tournament) - this.getOvertimeGetsOneGame(game);
    if (totalGets == 0) {
        return 0;
    }
    return +(bonusPoints / totalGets).toFixed(2);
}

/**
* Get team's margin of victory
* @param tournament tournament to check
* @return avg margin of victory
*/
teamSchema.methods.getAverageMarginOfVictory = function(tournament) {
    return +(this.getPointsPerGame(tournament) - this.getOpponentPPG(tournament)).toFixed(3);
}

/**
* Get team's margin of victory given constraints
* @param tournament tournament to check
* @param constraints bounds on rounds
* @return avg margin of victory
*/
teamSchema.methods.getAverageMarginOfVictoryFiltered = function(tournament, constraints) {
    return +(this.getPointsPerGameFiltered(tournament, constraints) - this.getOpponentPPGFiltered(tournament, constraints)).toFixed(3);
}

/**
* Get all of a team's bounceback points
* @param tournament tournament to check
* @return total bounceback points
*/
teamSchema.methods.getTotalBouncebackPoints = function(tournament) {
    let totalBouncebackPoints = 0;
    tournament.games.forEach(currentGame => {
        if (currentGame.team1.team_id == this._id) {
            totalBouncebackPoints += currentGame.team1.bouncebacks;
        } else if (currentGame.team2.team_id == this._id) {
            totalBouncebackPoints += currentGame.team2.bouncebacks;
        }
    });
    return totalBouncebackPoints;
}

/**
* Get all of a team's overall statistical information given constraints
* @param tournament tournament to check
* @param constraints bounds on rounds
* @return average information about a team's stats
*/
teamSchema.methods.getAverageInformationFiltered = function(tournament, constraints) {
    const record = this.getRecordFiltered(tournament, constraints);
    const teamInfo = {};
    let activePhase = "";
    for (let i = 0; i < tournament.phases.length; i++) {
        if (tournament.phases[i].active) {
            activePhase = tournament.phases[i].phase_id;
            break;
        }
    }
    teamInfo["Division"] = this.divisions ? this.divisions[activePhase] : "";
    teamInfo["Team"] = this.team_name;
    teamInfo["W"] = record.wins;
    teamInfo["L"] = record.losses;
    teamInfo["T"] = record.ties;
    teamInfo["Win %"] = this.getWinPercentage(record);
    teamInfo["PPG"] = this.getPointsPerGameFiltered(tournament, constraints);
    teamInfo["PAPG"] = this.getOpponentPPGFiltered(tournament, constraints);
    teamInfo["Margin"] = this.getAverageMarginOfVictoryFiltered(tournament, constraints);
    teamInfo.pointTotals = this.getTossupTotalsFiltered(tournament, constraints);
    teamInfo["TUH"] = this.getTossupsHeardFiltered(tournament, constraints);
    teamInfo["Bonus Points"] = this.getTotalBonusPointsFiltered(tournament, constraints);
    teamInfo["PPB"] = this.getOverallPPBFiltered(tournament, constraints);
    return {id : this.shortID, stats : teamInfo};
}

/**
* Get all of a team's overall statistical information
* @param tournament tournament to check
* @return average information about a team's stats
*/
teamSchema.methods.getAverageInformation = function(tournament) {
    const record = this.getRecord(tournament);
    const teamInfo = {};
    teamInfo["Team"] = this.team_name;
    if (tournament.divisions.length !== 0 && tournament.currentPhaseID != 1
        && this.divisions && this.divisions[tournament.currentPhaseID]) {
        teamInfo["Division"] = !this.divisions ? "" : this.divisions[tournament.currentPhaseID];
    } else if (tournament.divisions.length !== 0) {
        teamInfo["Division"] = "";
    }
    teamInfo["W"] = record.wins;
    teamInfo["L"] = record.losses;
    teamInfo["T"] = record.ties;
    teamInfo["Win %"] = this.getWinPercentage(record);
    teamInfo["PPG"] = this.getPointsPerGame(tournament);
    teamInfo["PAPG"] = this.getOpponentPPG(tournament);
    teamInfo["Margin"] = this.getAverageMarginOfVictory(tournament);
    teamInfo.pointTotals = this.getTossupTotals(tournament);
    teamInfo["TUH"] = this.getTossupsHeard(tournament);
    teamInfo["Bonus Points"] = this.getTotalBonusPoints(tournament);
    teamInfo["PPB"]= this.getOverallPPB(tournament);
    return {id : this.shortID, stats : teamInfo};
}

/**
* Get all of a team's overall statistical info about all games played
* @param tournament tournament to check
* @return all information about a team's games
*/
teamSchema.methods.getAllGamesInformation = function(tournament, teamMap) {
    let playedGames = [];
    tournament.games.forEach(currentGame => {
        if (currentGame.team1.team_id == this._id || currentGame.team2.team_id == this._id) {
            const formattedGame = this.formatGameInformation(currentGame, tournament, teamMap);
            playedGames.push(formattedGame);
        }
    });
    playedGames.sort((first, second) => {
        return first["Round"] - second["Round"];
    });
    return playedGames;
}

/**
* Get all of a team's overall statistical info about all games played given constraints
* @param tournament tournament to check
* @param constraints bounds on rounds
* @return all information about a team's games
*/
teamSchema.methods.getAllGamesInformationFiltered = function(tournament, constraints, teamMap) {
    let playedGames = [];
    const filteredGames = tournament.games.filter(game => {
        return game.round >= constraints.minround && game.round <= constraints.maxround;
    });
    filteredGames.forEach(currentGame => {
        if (currentGame.team1.team_id == this._id || currentGame.team2.team_id == this._id) {
            const formattedGame = this.formatGameInformation(currentGame, tournament, teamMap);
            playedGames.push(formattedGame);
        }
    });
    playedGames.sort((first, second) => {
        return first["Round"] - second["Round"];
    });
    return playedGames;
}

/**
* Formats a team's game information to get ready for presentation
* @param game game to check
* @param tournament tournament to check
* @return formatted info about a game
*/
teamSchema.methods.formatGameInformation = function(game, tournament, teamMap) {
    const gameinfo = {};
    gameinfo["Round"] = game.round;
    if (game.team1.team_id == this._id) {
        gameinfo["Opponent"] = teamMap[game.team2.team_id].name;
        if (game.team1.score > game.team2.score) {
            gameinfo["Result"] = "W";
        } else if (game.team2.score > game.team1.score) {
            gameinfo["Result"] = "L";
        } else {
            gameinfo["Result"] = "T";
        }
        gameinfo["Score"] = game.team1.score;
        gameinfo["Opponent Score"] = game.team2.score;
        gameinfo.pointValues = this.getTossupTotalsOneGame(game, tournament);
        gameinfo["TUH"] = game.tossupsheard;
        gameinfo["Bonus Points"] = this.getBonusPointsOneGame(game, tournament);
        gameinfo["PPB"] = this.getPPBOneGame(game, tournament);
    } else {
        gameinfo["Opponent"] = teamMap[game.team1.team_id].name;
        if (game.team1.score > game.team2.score) {
            gameinfo["Result"] = "L";
        } else if (game.team2.score > game.team1.score) {
            gameinfo["Result"] = "W";
        } else {
            gameinfo["Result"] = "T";
        }
        gameinfo["Score"] = game.team2.score;
        gameinfo["Opponent Score"] = game.team1.score;
        gameinfo.pointValues = this.getTossupTotalsOneGame(game, tournament);
        gameinfo["TUH"] = game.tossupsheard;
        gameinfo["Bonus Points"] = this.getBonusPointsOneGame(game, tournament);
        gameinfo["PPB"] = this.getPPBOneGame(game, tournament);
    }
    return gameinfo;
}

/**
* Gets stats about players on this team
* @param tournament tournament to get players from
* @return array of player statistics
*/
teamSchema.methods.getPlayerStats = function(tournament, teamMap) {
    let playerStats = [];
    const team = this;
    const filtered = tournament.players.filter(function(player) {
        return player.teamID == team._id;
    });
    filtered.forEach(player => {
        playerStats.push(player.getAllInformation(tournament, teamMap));
    });
    return playerStats;
}

/**
* Gets total statistics about a game
* @param tournament tournament to check
* @return statistics about all a team's games
*/
teamSchema.methods.getTotalGameStats = function(tournament) {
    const totals = this.getAverageInformation(tournament);
    const record = this.getRecord(tournament);
    let gp = 0;
    for (let total in record) {
        if (record.hasOwnProperty(total)) {
            gp += record[total];
        }
    }
    totals.stats["Score"] = totals.stats["PPG"] * gp;
    totals.stats["Opponent Score"] = totals.stats["PAPG"] * gp;
    totals.stats.pointValues = totals.stats.pointTotals;
    return totals.stats;
}

module.exports = mongoose.model("Team", teamSchema);


text:
<form id="mainForm" method="post" action="http://plnkr.co/edit/?p=preview" target="_self"><input type="hidden" name="files[app/di_demo.ts]" value="import {Component} from 'angular2/core';
import {UiTabs, UiPane} from './ui_tabs';

class Detail {
  title: string;
  text: string;
}

@Component({
  selector: 'di-demo',
  template: `

Tabs Demo

    <ui-tabs>
      <template ui-pane title='Overview' active="true">
        You have {{details.length}} details.
      </template>
      <template *ngFor="#detail of details" ui-pane [title]="detail.title">
        {{detail.text}}

        <button class="btn" (click)="removeDetail(detail)">Remove</button>
      </template>
      <template ui-pane title='Summary'>
        Next last ID is {{id}}.
      </template>
    </ui-tabs>

    <button class="btn" (click)="addDetail()">Add Detail</button>
    `,
    directives: [UiTabs, UiPane]
})
export class DiDemo {
  details: Detail[] = [];
  id: number = 0;

  addDetail() {
    this.id++;
    this.details.push({
      title: `Detail ${this.id}`,
      text: `Some detail text for ${this.id}...`
    });
  }

  removeDetail(detail:Detail) {
    this.details = this.details.filter((d) => d !== detail);
  }
}

"><input type="hidden" name="files[app/main.ts]" value="import {bootstrap} from 'angular2/platform/browser';
import {DiDemo}    from './di_demo';

bootstrap(DiDemo);

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/"><input type="hidden" name="files[app/ui_tabs.ts]" value="import {Component, Directive, Input, QueryList,
        ViewContainerRef, TemplateRef, ContentChildren} from 'angular2/core';

@Directive({
  selector: '[ui-pane]'
})
export class UiPane {
  @Input() title: string;
  private _active:boolean = false;

  constructor(public viewContainer: ViewContainerRef,
              public templateRef: TemplateRef) { }

  @Input() set active(active: boolean) {
    if (active == this._active) return;
    this._active = active;
    if (active) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.remove(0);
    }
  }

  get active(): boolean {
    return this._active;
  }
}

@Component({
  selector: 'ui-tabs',
  template: `

        {{pane.title}}

    <ng-content></ng-content>
    `,
    styles:['a { cursor: pointer; cursor: hand; }']
})
export class UiTabs {
  @ContentChildren(UiPane) panes: QueryList<UiPane>;

  select(pane: UiPane) {
    this.panes.toArray().forEach((p: UiPane) => p.active = p == pane);
  }
}

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/"><input type="hidden" name="files[styles.css]" value="/* Master Styles */
h1 {
  color: #369;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 250%;
}
h2, h3 {
  color: #444;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: lighter;
}
body {
  margin: 2em;
}
body, input[text], button {
  color: #888;
  font-family: Cambria, Georgia;
}
a {
  cursor: pointer;
  cursor: hand;
}
button {
  font-family: Arial;
  background-color: #eee;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  cursor: hand;
}
button:hover {
  background-color: #cfd8dc;
}
button:disabled {
  background-color: #eee;
  color: #aaa;
  cursor: auto;
}

/* Navigation link styles */
nav a {
  padding: 5px 10px;
  text-decoration: none;
  margin-top: 10px;
  display: inline-block;
  background-color: #eee;
  border-radius: 4px;
}
nav a:visited, a:link {
  color: #607D8B;
}
nav a:hover {
  color: #039be5;
  background-color: #CFD8DC;
}
nav a.router-link-active {
  color: #039be5;
}

/* items class */
.items {
  margin: 0 0 2em 0;
  list-style-type: none;
  padding: 0;
  width: 24em;
}
.items li {
  cursor: pointer;
  position: relative;
  left: 0;
  background-color: #EEE;
  margin: .5em;
  padding: .3em 0;
  height: 1.6em;
  border-radius: 4px;
}
.items li:hover {
  color: #607D8B;
  background-color: #DDD;
  left: .1em;
}
.items li.selected:hover {
  background-color: #BBD8DC;
  color: white;
}
.items .text {
  position: relative;
  top: -3px;
}
.items {
  margin: 0 0 2em 0;
  list-style-type: none;
  padding: 0;
  width: 24em;
}
.items li {
  cursor: pointer;
  position: relative;
  left: 0;
  background-color: #EEE;
  margin: .5em;
  padding: .3em 0;
  height: 1.6em;
  border-radius: 4px;
}
.items li:hover {
  color: #607D8B;
  background-color: #DDD;
  left: .1em;
}
.items li.selected {
  background-color: #CFD8DC;
  color: white;
}

.items li.selected:hover {
  background-color: #BBD8DC;
}
.items .text {
  position: relative;
  top: -3px;
}
.items .badge {
  display: inline-block;
  font-size: small;
  color: white;
  padding: 0.8em 0.7em 0 0.7em;
  background-color: #607D8B;
  line-height: 1em;
  position: relative;
  left: -1px;
  top: -4px;
  height: 1.8em;
  margin-right: .8em;
  border-radius: 4px 0 0 4px;
}

/* everywhere else */
* {
  font-family: Arial, Helvetica, sans-serif;
}

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/"><input type="hidden" name="files[index.html]" value="<!DOCTYPE html>

    <title>Angular 2 Tabs</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" href="styles.css">

    <di-demo class="container" style="display: block">Loading...</di-demo>

"><input type="hidden" name="tags[0]" value="angular2"><input type="hidden" name="tags[1]" value="example"><input type="hidden" name="private" value="true"><input type="hidden" name="description" value="Angular 2 Example - Tabs"></form>


text:
package org.apache.commons.javaflow.suite;

import junit.framework.TestCase;
import junitx.util.PrivateAccessor;
import org.apache.commons.javaflow.Continuation;
import org.apache.commons.javaflow.bytecode.StackRecorder;
import org.apache.commons.javaflow.rewrite.Invoker;
import org.apache.commons.javaflow.rewrite.Simple;
import org.apache.commons.javaflow.rewrite.SimpleSerializable;

import java.io.*;
import java.lang.reflect.Proxy;

@SuppressWarnings("unchecked")
public final class SerializationTestCase extends TestCase {

	private File output;

	private boolean fromSuite() {
		final String cl = this.getClass().getClassLoader().getClass().getName();
		return cl.contains("ClassTransformerClassLoader");
	}

	public void testSuspend() throws Exception {
		assertTrue(fromSuite());
		final SimpleSerializable r = new SimpleSerializable();
		assertTrue(r.g == -1);
		assertTrue(r.l == -1);
		Continuation c1 = Continuation.startWith(r);
		assertTrue(r.g == 0);
		assertTrue(r.l == 0);

		output = File.createTempFile("continuation", "xml");
		output.deleteOnExit();

		saveJDK(c1, output);

	}

	public class ObjectInputStreamExt extends ObjectInputStream {

		private ClassLoader classloader;

		public ObjectInputStreamExt(InputStream in, ClassLoader loader) throws IOException {
			super(in);
			this.classloader = loader;
		}

		@SuppressWarnings("rawtypes")
		protected Class resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException {

			return Class.forName(classDesc.getName(), true, classloader);
		}

		@SuppressWarnings("rawtypes")
		protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
			Class[] cinterfaces = new Class[interfaces.length];
			for (int i = 0; i < interfaces.length; i++) {
				cinterfaces[i] = Class.forName(interfaces[i], true, classloader);
			}

			try {
				return Proxy.getProxyClass(classloader, cinterfaces);
			} catch (IllegalArgumentException e) {
				throw new ClassNotFoundException(null, e);
			}
		}
	}

	private void saveJDK(final Object c1, final File output) throws IOException {
		final ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(output));
		oos.writeObject(c1);
		oos.close();
	}

	private Object loadJDK(final File input) throws IOException, ClassNotFoundException {
		final ObjectInputStream ois = new ObjectInputStreamExt(new FileInputStream(input), this.getClass().getClassLoader());
		final Object o = ois.readObject();
		ois.close();
		return o;
	}

	public void testResume() throws Exception {
		assertTrue(fromSuite());
		testSuspend();
		assertTrue("suspend must succeed to create the output first", output != null);

		assertEquals(output.length(), 562);

		final Object o = loadJDK(output);

		assertTrue(o instanceof Continuation);
		final Continuation c1 = (Continuation) o;
		final StackRecorder sr1 = (StackRecorder) PrivateAccessor.getField(c1, "stackRecorder");
		final Runnable r1 = (Runnable) PrivateAccessor.getField(sr1, "runnable");
		assertEquals(SimpleSerializable.class.getName(), r1.getClass().getName());

		final SimpleSerializable ss1 = (SimpleSerializable) r1;
		assertTrue(ss1.g == 0);
		assertTrue(ss1.l == 0);
		final Continuation c2 = Continuation.continueWith(c1);
		final StackRecorder sr2 = (StackRecorder) PrivateAccessor.getField(c2, "stackRecorder");
		final Runnable r2 = (Runnable) PrivateAccessor.getField(sr2, "runnable");
		assertEquals(SimpleSerializable.class.getName(), r2.getClass().getName());
		final SimpleSerializable ss2 = (SimpleSerializable) r2;
		assertTrue(ss2.g == 1);
		assertTrue(ss2.l == 1);
		assertTrue(r1 == r2);
	}

	public void testSerializableCheck() throws Exception {
		assertTrue(fromSuite());
		final Runnable r1 = new Simple();
		Continuation c1 = Continuation.startWith(r1);
		assertTrue(c1 != null);
		assertTrue(!c1.isSerializable());

		final Runnable r2 = new SimpleSerializable();
		Continuation c2 = Continuation.startWith(r2);
		assertTrue(c2 != null);
		assertTrue(c2.isSerializable());

		final Runnable r3 = new SimpleSerializable();
		Continuation c3 = Continuation.startWith(new Invoker(r3));
		assertTrue(c3 != null);
		assertTrue(c3.isSerializable());
		// the invoker should not appear on the stack as it should not be instrumented
		// and by that not hinder serialization (in cocoon the continuation is always called
		// through such an invoker)
	}
}


text:
/* eslint-disable no-console */
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const moment = require('moment');

app.get('/', (req, res) => {
  res.send('hello');
});

function generateTempObservation(nodeId) {
  return {
    feature_of_interest: 'temperature',
    node_id: nodeId,
    sensor: 'tempx',
    results: {
      temperature: 19 + Math.floor(Math.random() * 10),
    },
    datetime: moment().format(),
  };
}

function generateGasObservation(nodeId) {
  return {
    feature_of_interest: 'gas_concentration',
    node_id: nodeId,
    sensor: 'gasx',
    results: {
      co: null,
      so2: null,
      o3: null,
      h2s: Math.random() * (3 / 4),
      no2: null,
    },
    datetime: moment().format(),
  };
}

io.on('connection', (socket) => {
  console.log('a user connected');

  // Emit some data every 30 seconds
  setInterval(() => {
    socket.emit('data', generateGasObservation('00A'));
    socket.emit('data', generateGasObservation('00B'));
    socket.emit('data', generateTempObservation('00A'));
    socket.emit('data', generateTempObservation('00B'));
  }, 30000);
});

http.listen(8081, () => {
  console.log('listening on *:8081');
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<mvc:annotation-driven />
	<context:annotation-config />
	<context:component-scan base-package="com.*" />

	<!--configure view resolver -->

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
	<mvc:resources mapping="/resources/**" location="/resources/" />

</beans>