text:
package org.elder.sourcerer.subscription;

import org.elder.sourcerer.EventRepository;
import org.elder.sourcerer.EventSubscriptionHandler;
import org.elder.sourcerer.EventSubscriptionPositionSource;
import org.elder.sourcerer.SubscriptionToken;
import org.elder.sourcerer.SubscriptionWorkerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Custom subscriber to work around the fact that buffer does not appear to respect back pressure,
 * in RxJava or Project Reactor! This has the added benefit of not requiring time windows, but
 * rather process updates in batch automatically if the subscriber is not fast enough to keep up
 * with them sent one by one - i.e. normally batch in replay model, and one by one delivery when
 * live - but without added latency in the live case.
 * <p>
 * This implementation uses a dedicated worker thread per subscription, which is expensive but easy
 * to manage.
 *
 * @param <T> The type of events the subscription handles.
 */
public class EventSubscriptionManager<T> {
    private static final Logger logger = LoggerFactory.getLogger(EventSubscriptionManager.class);

    private final SubscriptionWorker subscriptionWorker;
    private final Thread workerThread;

    public EventSubscriptionManager(
            final EventRepository<T> repository,
            final EventSubscriptionPositionSource positionSource,
            final EventSubscriptionHandler<T> subscriptionHandler,
            final SubscriptionWorkerConfig config) {
        this.subscriptionWorker = new SubscriptionWorker<>(
                repository,
                positionSource,
                subscriptionHandler,
                config);
        this.workerThread = new Thread(subscriptionWorker, "event-subscription-worker");
        this.workerThread.setUncaughtExceptionHandler(uncaughtExceptionHandler());
    }

    public SubscriptionToken start() {
        workerThread.start();
        return subscriptionWorker;
    }

    private Thread.UncaughtExceptionHandler uncaughtExceptionHandler() {
        return (thread, throwable) -> {
            logger.error("Uncaught exception in worker - stopped: ", throwable);
        };
    }
}


text:
<!DOCTYPE html>

        <title ng-bind="pageTitle"></title>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
        <link href="vendor/animate.css/animate.min.css" rel="stylesheet">
        <link href="vendor/albumize-master/css/albumize.css" rel="stylesheet">

        <% styles.forEach( function ( file ) { %>
        <link rel="stylesheet" type="text/css" href="<%= file %>" /><% }); %>

        <% scripts.forEach( function ( file ) { %>
        <% }); %>

ANTHONY_BENAVENTE

                    Home

                    Portfolio

                    Resume

                    About

                            Home

                            Portfolio

                            Resume

                            About

Site Links

Home

Portfolio

Resume

About

Social Media

 Github

 Bitbucket

 Twitter

 Instagram

 Facebook

 LinkedIn

                    <form class="contact-form">

Let me know what you think!

                            <input name="name" type="text" placeholder="Name">

                            <input name="email" type="email" placeholder="Email Address">

                            <input name="phone" type="tel" placeholder="Phone Number">

                            <textarea name="notes" placeholder="Feedback, comments, and questions are welcome!"></textarea>

                        <button class="sm-left md-right" type="button">Submit</button>
                    </form>

                    Copyright © 2013 -  Anthony Benavente

                    Email:  anthony.m.benavente@gmail.com

redpajama_set_name: RedPajamaGithub


text:
package media

import (
	"testing"

	"github.com/stretchr/testify/require"
)

func TestDefaultTypes(t *testing.T) {
	for _, test := range []struct {
		tp               Type
		expectedMainType string
		expectedSubType  string
		expectedSuffix   string
		expectedType     string
		expectedString   string
	}{
		{CalendarType, "text", "calendar", "ics", "text/calendar", "text/calendar+ics"},
		{CSSType, "text", "css", "css", "text/css", "text/css+css"},
		{CSVType, "text", "csv", "csv", "text/csv", "text/csv+csv"},
		{HTMLType, "text", "html", "html", "text/html", "text/html+html"},
		{JavascriptType, "application", "javascript", "js", "application/javascript", "application/javascript+js"},
		{JSONType, "application", "json", "json", "application/json", "application/json+json"},
		{RSSType, "application", "rss", "xml", "application/rss", "application/rss+xml"},
		{TextType, "text", "plain", "txt", "text/plain", "text/plain+txt"},
	} {
		require.Equal(t, test.expectedMainType, test.tp.MainType)
		require.Equal(t, test.expectedSubType, test.tp.SubType)
		require.Equal(t, test.expectedSuffix, test.tp.Suffix)

		require.Equal(t, test.expectedType, test.tp.Type())
		require.Equal(t, test.expectedString, test.tp.String())

	}

}

func TestGetByType(t *testing.T) {
	types := Types{HTMLType, RSSType}

	mt, found := types.GetByType("text/HTML")
	require.True(t, found)
	require.Equal(t, mt, HTMLType)

	_, found = types.GetByType("text/nono")
	require.False(t, found)
}

func TestFromTypeString(t *testing.T) {
	f, err := FromString("text/html")
	require.NoError(t, err)
	require.Equal(t, HTMLType, f)

	f, err = FromString("application/custom")
	require.NoError(t, err)
	require.Equal(t, Type{MainType: "application", SubType: "custom", Suffix: "custom"}, f)

	f, err = FromString("application/custom+pdf")
	require.NoError(t, err)
	require.Equal(t, Type{MainType: "application", SubType: "custom", Suffix: "pdf"}, f)

	f, err = FromString("noslash")
	require.Error(t, err)

}

func TestDecodeTypes(t *testing.T) {

	var tests = []struct {
		name        string
		maps        []map[string]interface{}
		shouldError bool
		assert      func(t *testing.T, name string, tt Types)
	}{
		{
			"Redefine JSON",
			[]map[string]interface{}{
				map[string]interface{}{
					"application/json": map[string]interface{}{
						"suffix": "jsn"}}},
			false,
			func(t *testing.T, name string, tt Types) {
				require.Len(t, tt, len(DefaultTypes))
				json, found := tt.GetBySuffix("jsn")
				require.True(t, found)
				require.Equal(t, "application/json+jsn", json.String(), name)
			}},
		{
			"Add custom media type",
			[]map[string]interface{}{
				map[string]interface{}{
					"text/hugo": map[string]interface{}{
						"suffix": "hgo"}}},
			false,
			func(t *testing.T, name string, tt Types) {
				require.Len(t, tt, len(DefaultTypes)+1)
				// Make sure we have not broken the default config.
				_, found := tt.GetBySuffix("json")
				require.True(t, found)

				hugo, found := tt.GetBySuffix("hgo")
				require.True(t, found)
				require.Equal(t, "text/hugo+hgo", hugo.String(), name)
			}},
		{
			"Add media type invalid key",
			[]map[string]interface{}{
				map[string]interface{}{
					"text/hugo+hgo": map[string]interface{}{}}},
			true,
			func(t *testing.T, name string, tt Types) {

			}},
	}

	for _, test := range tests {
		result, err := DecodeTypes(test.maps...)
		if test.shouldError {
			require.Error(t, err, test.name)
		} else {
			require.NoError(t, err, test.name)
			test.assert(t, test.name, result)
		}
	}
}


text:
The idea was to create a "universal" tool to have fun with UPnP enabled devices, which could run on vanilla Python (no SOAPpy, no other unsupported crap).

# Project state

This is in deep alpha -- that is, it hardly works.

That said, this is what we have at the moment:

* Discovery of UPnP capable devices via multicast SSDP
* Unicast SSDP query
* UPnP related set of classes allowing to parse device and service descriptors
* Action invocation (somewhat rudimentary at the point)

This is what we don't have yet:

* Proper command line handling
* Handling of errors and corner cases


text:
package io.seata.server.storage.db.lock;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.sql.DataSource;
import io.seata.common.exception.DataAccessException;
import io.seata.common.exception.StoreException;
import io.seata.common.util.CollectionUtils;
import io.seata.common.util.IOUtil;
import io.seata.common.util.LambdaUtils;
import io.seata.common.util.StringUtils;
import io.seata.config.Configuration;
import io.seata.config.ConfigurationFactory;
import io.seata.core.constants.ConfigurationKeys;
import io.seata.core.constants.ServerTableColumnsName;
import io.seata.core.exception.BranchTransactionException;
import io.seata.core.model.LockStatus;
import io.seata.core.store.LockDO;
import io.seata.core.store.LockStore;
import io.seata.core.store.db.sql.lock.LockStoreSqlFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static io.seata.common.DefaultValues.DEFAULT_LOCK_DB_TABLE;
import static io.seata.core.exception.TransactionExceptionCode.LockKeyConflictFailFast;

/**
 * The type Data base lock store.
 *
 * @author zhangsen
 */
public class LockStoreDataBaseDAO implements LockStore {

    private static final Logger LOGGER = LoggerFactory.getLogger(LockStoreDataBaseDAO.class);

    /**
     * The constant CONFIG.
     */
    protected static final Configuration CONFIG = ConfigurationFactory.getInstance();

    /**
     * The Lock store data source.
     */
    protected DataSource lockStoreDataSource;

    /**
     * The Lock table.
     */
    protected String lockTable;

    /**
     * The Db type.
     */
    protected String dbType;

    /**
     * Instantiates a new Data base lock store dao.
     *
     * @param lockStoreDataSource the log store data source
     */
    public LockStoreDataBaseDAO(DataSource lockStoreDataSource) {
        this.lockStoreDataSource = lockStoreDataSource;
        lockTable = CONFIG.getConfig(ConfigurationKeys.LOCK_DB_TABLE, DEFAULT_LOCK_DB_TABLE);
        dbType = CONFIG.getConfig(ConfigurationKeys.STORE_DB_TYPE);
        if (StringUtils.isBlank(dbType)) {
            throw new StoreException("there must be db type.");
        }
        if (lockStoreDataSource == null) {
            throw new StoreException("there must be lockStoreDataSource.");
        }
    }

    @Override
    public boolean acquireLock(LockDO lockDO) {
        return acquireLock(Collections.singletonList(lockDO));
    }

    @Override
    public boolean acquireLock(List<LockDO> lockDOs) {
        return acquireLock(lockDOs, true, false);
    }

    @Override
    public boolean acquireLock(List<LockDO> lockDOs, boolean autoCommit, boolean skipCheckLock) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Set<String> dbExistedRowKeys = new HashSet<>();
        boolean originalAutoCommit = true;
        if (lockDOs.size() > 1) {
            lockDOs = lockDOs.stream().filter(LambdaUtils.distinctByKey(LockDO::getRowKey)).collect(Collectors.toList());
        }
        try {
            conn = lockStoreDataSource.getConnection();
            if (originalAutoCommit = conn.getAutoCommit()) {
                conn.setAutoCommit(false);
            }
            List<LockDO> unrepeatedLockDOs = lockDOs;

            //check lock
            if (!skipCheckLock) {

                boolean canLock = true;
                //query
                String checkLockSQL = LockStoreSqlFactory.getLogStoreSql(dbType).getCheckLockableSql(lockTable, lockDOs.size());
                ps = conn.prepareStatement(checkLockSQL);
                for (int i = 0; i < lockDOs.size(); i++) {
                    ps.setString(i + 1, lockDOs.get(i).getRowKey());
                }
                rs = ps.executeQuery();
                String currentXID = lockDOs.get(0).getXid();
                boolean failFast = false;
                while (rs.next()) {
                    String dbXID = rs.getString(ServerTableColumnsName.LOCK_TABLE_XID);
                    if (!StringUtils.equals(dbXID, currentXID)) {
                        if (LOGGER.isInfoEnabled()) {
                            String dbPk = rs.getString(ServerTableColumnsName.LOCK_TABLE_PK);
                            String dbTableName = rs.getString(ServerTableColumnsName.LOCK_TABLE_TABLE_NAME);
                            long dbBranchId = rs.getLong(ServerTableColumnsName.LOCK_TABLE_BRANCH_ID);
                            LOGGER.info("Global lock on [{}:{}] is holding by xid {} branchId {}", dbTableName, dbPk, dbXID, dbBranchId);
                        }
                        if (!autoCommit) {
                            int status = rs.getInt(ServerTableColumnsName.LOCK_TABLE_STATUS);
                            if (status == LockStatus.Rollbacking.getCode()) {
                                failFast = true;
                            }
                        }
                        canLock = false;
                        break;
                    }

                    dbExistedRowKeys.add(rs.getString(ServerTableColumnsName.LOCK_TABLE_ROW_KEY));
                }
                if (!canLock) {
                    conn.rollback();
                    if (failFast) {
                        throw new StoreException(new BranchTransactionException(LockKeyConflictFailFast));
                    }
                    return false;
                }
                // If the lock has been exists in db, remove it from the lockDOs
                if (CollectionUtils.isNotEmpty(dbExistedRowKeys)) {
                    unrepeatedLockDOs = lockDOs.stream().filter(lockDO -> !dbExistedRowKeys.contains(lockDO.getRowKey()))
                            .collect(Collectors.toList());
                }
                if (CollectionUtils.isEmpty(unrepeatedLockDOs)) {
                    conn.rollback();
                    return true;
                }
            }

            // lock
            if (unrepeatedLockDOs.size() == 1) {
                LockDO lockDO = unrepeatedLockDOs.get(0);
                if (!doAcquireLock(conn, lockDO)) {
                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("Global lock acquire failed, xid {} branchId {} pk {}", lockDO.getXid(), lockDO.getBranchId(), lockDO.getPk());
                    }
                    conn.rollback();
                    return false;
                }
            } else {
                if (!doAcquireLocks(conn, unrepeatedLockDOs)) {
                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("Global lock batch acquire failed, xid {} branchId {} pks {}", unrepeatedLockDOs.get(0).getXid(),
                            unrepeatedLockDOs.get(0).getBranchId(), unrepeatedLockDOs.stream().map(lockDO -> lockDO.getPk()).collect(Collectors.toList()));
                    }
                    conn.rollback();
                    return false;
                }
            }
            conn.commit();
            return true;
        } catch (SQLException e) {
            throw new StoreException(e);
        } finally {
            IOUtil.close(rs, ps);
            if (conn != null) {
                try {
                    if (originalAutoCommit) {
                        conn.setAutoCommit(true);
                    }
                    conn.close();
                } catch (SQLException e) {
                }
            }
        }
    }

    @Override
    public boolean unLock(LockDO lockDO) {
        return unLock(Collections.singletonList(lockDO));
    }

    @Override
    public boolean unLock(List<LockDO> lockDOs) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = lockStoreDataSource.getConnection();
            conn.setAutoCommit(true);

            //batch release lock
            String batchDeleteSQL = LockStoreSqlFactory.getLogStoreSql(dbType).getBatchDeleteLockSql(lockTable, lockDOs.size());
            ps = conn.prepareStatement(batchDeleteSQL);
            ps.setString(1, lockDOs.get(0).getXid());
            for (int i = 0; i < lockDOs.size(); i++) {
                ps.setString(i + 2, lockDOs.get(i).getRowKey());
            }
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new StoreException(e);
        } finally {
            IOUtil.close(ps, conn);
        }
        return true;
    }

    @Override
    public boolean unLock(String xid) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = lockStoreDataSource.getConnection();
            conn.setAutoCommit(true);
            //batch release lock by branch list
            String batchDeleteSQL = LockStoreSqlFactory.getLogStoreSql(dbType).getBatchDeleteLockSqlByXid(lockTable);
            ps = conn.prepareStatement(batchDeleteSQL);
            ps.setString(1, xid);
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new StoreException(e);
        } finally {
            IOUtil.close(ps, conn);
        }
        return true;
    }

    @Override
    public boolean unLock(Long branchId) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = lockStoreDataSource.getConnection();
            conn.setAutoCommit(true);
            //batch release lock by branchId
            String batchDeleteSQL = LockStoreSqlFactory.getLogStoreSql(dbType).getBatchDeleteLockSqlByBranchId(lockTable);
            ps = conn.prepareStatement(batchDeleteSQL);
            ps.setLong(1, branchId);
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new StoreException(e);
        } finally {
            IOUtil.close(ps, conn);
        }
        return true;
    }

    @Override
    public boolean isLockable(List<LockDO> lockDOs) {
        Connection conn = null;
        try {
            conn = lockStoreDataSource.getConnection();
            conn.setAutoCommit(true);
            if (!checkLockable(conn, lockDOs)) {
                return false;
            }
            return true;
        } catch (SQLException e) {
            throw new DataAccessException(e);
        } finally {
            IOUtil.close(conn);
        }
    }

    @Override
    public void updateLockStatus(String xid, LockStatus lockStatus) {
        String updateStatusLockByGlobalSql =
            LockStoreSqlFactory.getLogStoreSql(dbType).getBatchUpdateStatusLockByGlobalSql(lockTable);
        try (Connection conn = lockStoreDataSource.getConnection();
            PreparedStatement ps = conn.prepareStatement(updateStatusLockByGlobalSql)) {
            conn.setAutoCommit(true);
            ps.setInt(1, lockStatus.getCode());
            ps.setString(2, xid);
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new DataAccessException(e);
        }
    }

    /**
     * Do acquire lock boolean.
     *
     * @param conn   the conn
     * @param lockDO the lock do
     * @return the boolean
     */
    protected boolean doAcquireLock(Connection conn, LockDO lockDO) {
        PreparedStatement ps = null;
        try {
            //insert
            String insertLockSQL = LockStoreSqlFactory.getLogStoreSql(dbType).getInsertLockSQL(lockTable);
            ps = conn.prepareStatement(insertLockSQL);
            ps.setString(1, lockDO.getXid());
            ps.setLong(2, lockDO.getTransactionId());
            ps.setLong(3, lockDO.getBranchId());
            ps.setString(4, lockDO.getResourceId());
            ps.setString(5, lockDO.getTableName());
            ps.setString(6, lockDO.getPk());
            ps.setString(7, lockDO.getRowKey());
            ps.setInt(8, LockStatus.Locked.getCode());
            return ps.executeUpdate() > 0;
        } catch (SQLException e) {
            if (e instanceof SQLIntegrityConstraintViolationException) {
                return false;
            }
            throw new StoreException(e);
        } finally {
            IOUtil.close(ps);
        }
    }

    /**
     * Do acquire lock boolean.
     *
     * @param conn    the conn
     * @param lockDOs the lock do list
     * @return the boolean
     */
    protected boolean doAcquireLocks(Connection conn, List<LockDO> lockDOs) throws SQLException {
        PreparedStatement ps = null;
        try {
            //insert
            String insertLockSQL = LockStoreSqlFactory.getLogStoreSql(dbType).getInsertLockSQL(lockTable);
            ps = conn.prepareStatement(insertLockSQL);
            for (LockDO lockDO : lockDOs) {
                ps.setString(1, lockDO.getXid());
                ps.setLong(2, lockDO.getTransactionId());
                ps.setLong(3, lockDO.getBranchId());
                ps.setString(4, lockDO.getResourceId());
                ps.setString(5, lockDO.getTableName());
                ps.setString(6, lockDO.getPk());
                ps.setString(7, lockDO.getRowKey());
                ps.setInt(8, lockDO.getStatus());
                ps.addBatch();
            }
            return ps.executeBatch().length == lockDOs.size();
        } catch (SQLIntegrityConstraintViolationException e) {
            LOGGER.error("Global lock batch acquire error: {}", e.getMessage(), e);
            //return false,let the caller go to conn.rollabck()
            return false;
        } catch (SQLException e) {
            throw e;
        } finally {
            IOUtil.close(ps);
        }
    }

    /**
     * Check lock boolean.
     *
     * @param conn    the conn
     * @param lockDOs the lock do
     * @return the boolean
     */
    protected boolean checkLockable(Connection conn, List<LockDO> lockDOs) {
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //query
            String checkLockSQL = LockStoreSqlFactory.getLogStoreSql(dbType).getCheckLockableSql(lockTable, lockDOs.size());
            ps = conn.prepareStatement(checkLockSQL);
            for (int i = 0; i < lockDOs.size(); i++) {
                ps.setString(i + 1, lockDOs.get(i).getRowKey());
            }
            rs = ps.executeQuery();
            while (rs.next()) {
                String xid = rs.getString("xid");
                if (!StringUtils.equals(xid, lockDOs.get(0).getXid())) {
                    return false;
                }
            }
            return true;
        } catch (SQLException e) {
            throw new DataAccessException(e);
        } finally {
            IOUtil.close(rs, ps);
        }
    }

    /**
     * Sets lock table.
     *
     * @param lockTable the lock table
     */
    public void setLockTable(String lockTable) {
        this.lockTable = lockTable;
    }

    /**
     * Sets db type.
     *
     * @param dbType the db type
     */
    public void setDbType(String dbType) {
        this.dbType = dbType;
    }

    /**
     * Sets log store data source.
     *
     * @param lockStoreDataSource the log store data source
     */
    public void setLogStoreDataSource(DataSource lockStoreDataSource) {
        this.lockStoreDataSource = lockStoreDataSource;
    }
}


text:
import { AsnConvert } from '@peculiar/asn1-schema';
import { CertificateList } from '@peculiar/asn1-x509';
import { Convert } from 'pvtsutils';

import { Download } from '../utils';

import { Extension, TExtensionValue } from './extension';
import { AsnData } from './asn_data';
import { Name, INameJSON } from './name';
import {
  certificateRawToBuffer,
  hexFormat,
  base64Format,
  getCertificateThumbprint,
} from './utils';

interface ISignature {
  algorithm: string;
  value: BufferSource;
}

export class CRL extends AsnData<CertificateList> {
  public readonly issuer: INameJSON[];

  public readonly version: number;

  public readonly lastUpdate: Date;

  public readonly nextUpdate: Date;

  public extensions: Extension<TExtensionValue>[];

  public thumbprints: Record<string, string> = {};

  public type: string = 'X.509 Certificate Revocation List';

  constructor(raw: string) {
    super(certificateRawToBuffer(raw), CertificateList);

    const { tbsCertList } = this.asn;

    this.issuer = new Name(tbsCertList.issuer).toJSON();
    this.version = tbsCertList.version + 1;
    this.lastUpdate = tbsCertList.thisUpdate.getTime();
    this.nextUpdate = tbsCertList.nextUpdate.getTime();
  }

  public async getThumbprint(
    algorithm: globalThis.AlgorithmIdentifier = 'SHA-1',
  ): Promise<void> {
    try {
      const thumbprint = await getCertificateThumbprint(algorithm, this.raw);
      if (thumbprint) {
        this.thumbprints[algorithm['name'] || algorithm] = Convert.ToHex(thumbprint);
      }
    } catch (error) {
      console.error('Error thumbprint get:', error);
    }
  }

  public get signature(): ISignature {
    const { signature, signatureAlgorithm } = this.asn;

    return {
      value: signature,
      algorithm: signatureAlgorithm.algorithm,
    };
  }

  public get commonName(): string {
    if (!this.issuer) {
      return '';
    }

    for (let i = 0; i < this.issuer.length; i += 1) {
      const name = this.issuer[i];

      if (name.shortName === 'CN' || name.shortName === 'E' || name.shortName === 'O') {
        return name.value;
      }
    }

    return '';
  }

  public parseExtensions() {
    const { tbsCertList } = this.asn;

    if (tbsCertList.crlExtensions) {
      this.extensions = tbsCertList.crlExtensions
        .map((e) => new Extension(AsnConvert.serialize(e)));
    }
  }

  public exportAsBase64() {
    return Convert.ToBase64(this.raw);
  }

  public exportAsHexFormatted() {
    return hexFormat(Convert.ToHex(this.raw));
  }

  public exportAsPemFormatted() {
    return `-----BEGIN X509 CRL-----\n${base64Format(this.exportAsBase64())}\n-----END X509 CRL-----`;
  }

  public downloadAsPEM(name?: string) {
    Download.crl.asPEM(
      this.exportAsPemFormatted(),
      name || this.commonName,
    );
  }

  public downloadAsDER(name?: string) {
    Download.crl.asDER(
      this.exportAsHexFormatted(),
      name || this.commonName,
    );
  }
}


text:
module Deals
  class Remove
    attr_reader :deal, :repository

    def initialize(user, contact_id, repository = DealRepository.new)
      @repository = repository
      @deal = repository.find_in_user_scope(user.id, contact_id)

    end

    def execute
      repository.destroy!(deal)
    end
  end
end


text:
<?php
class LoadWorkflowTest extends CDbTestCase {

	/**
	 *
	 * @see test/CDbTestCase::setUp()
	 */
	protected function setUp()
	{
		parent::setUp();
	}
	public function testInit_01() {

		$c = Yii::createComponent(array(
			'class'=>'application.extensions.simpleWorkflow.SWPhpWorkflowSource'
		));
		$c->init();
		$this->assertEquals($c->basePath,'application.models.workflows');
		$this->assertEquals($c->definitionType,'array');
		$this->assertEquals($c->workflowNamePrefix,'sw');
		$this->assertTrue( is_array($c->preload));
		$this->assertTrue( count($c->preload) == 0);

	}
	public function testLoad_01() {

		$c = Yii::createComponent(array(
		'class'=>'application.extensions.simpleWorkflow.SWPhpWorkflowSource'
		));
		$c->init();
		$this->assertFalse($c->isWorkflowLoaded('workflow1'));

		try{
			$c->loadWorkflow('workflow1');
			$this->fail();
		}catch(SWException $e){
			$this->assertEquals($e->getCode(),SWException::SW_ERR_WORKFLOW_NOT_FOUND);
		}
	}
	public function testLoad_02() {

		$c = Yii::createComponent(array(
			'class'=>'application.extensions.simpleWorkflow.SWPhpWorkflowSource',
			'basePath' => 'application.tests.unit.phpworkflowsource.workflows'
		));
		$c->init();

		$this->assertFalse($c->isWorkflowLoaded('SWWorkflowAsArray'));
		$this->assertTrue($c->loadWorkflow('SWWorkflowAsArray'));
		$this->assertTrue($c->isWorkflowLoaded('SWWorkflowAsArray'));
		//echo CVarDumper::dumpAsString($c);
	}
	public function testLoad_03() {

		$c = Yii::createComponent(array(
			'class'=>'application.extensions.simpleWorkflow.SWPhpWorkflowSource',
			'basePath' => 'application.tests.unit.phpworkflowsource.workflows',
			'preload' => array('SWWorkflowAsArray')
		));
		$c->init();

		$this->assertTrue($c->isWorkflowLoaded('SWWorkflowAsArray'));
	}
	public function testLoad_04() {

		$c = Yii::createComponent(array(
			'class'=>'application.extensions.simpleWorkflow.SWPhpWorkflowSource',
			'basePath' => 'application.tests.unit.phpworkflowsource.workflows',
			'definitionType' => 'class'
		));
		$c->init();

		$this->assertFalse($c->isWorkflowLoaded('SWWorkflowAsClass'));
		$this->assertTrue($c->loadWorkflow('SWWorkflowAsClass'));
		$this->assertTrue($c->isWorkflowLoaded('SWWorkflowAsClass'));
	}
	public function testLoad_05() {

		$c = Yii::createComponent(array(
			'class'=>'application.extensions.simpleWorkflow.SWPhpWorkflowSource',
			'basePath' => 'application.tests.unit.phpworkflowsource.workflows',
			'definitionType' => 'class'
		));
		$c->init();
		$this->assertFalse($c->isWorkflowLoaded('SWWorkflowAsClass'));

		try{
			$c->loadWorkflow('NotFound');
			$this->fail();
		}catch(Exception $e){
		}
	}
	public function testLoad_06() {

		$c = Yii::createComponent(array(
			'class'=>'application.extensions.simpleWorkflow.SWPhpWorkflowSource',
			'basePath' => 'application.tests.unit.phpworkflowsource.workflows',
			'definitionType' => 'class'
		));
		$c->init();

		$this->assertFalse($c->isWorkflowLoaded('SWWorkflow2'));
		$this->assertTrue($c->loadWorkflow('SWWorkflow2'));
		$this->assertTrue($c->isWorkflowLoaded('SWWorkflow2'));
	}
}


text:
package com.learn.core.domain;

import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;

/**
 * Created by Administrator on 2016/12/23 0023.
 */
@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseDomain implements Serializable {

    @Id
    @Column(name = "id", length = 32)
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;

    @CreatedBy
    private String createName;

    @CreatedDate
    private Date createTime;

    @LastModifiedBy
    private String updateName;

    @LastModifiedDate
    private Date updateTime;

    private Integer isDelete;

    @Version
    private Integer version;

}


text:
require 'spec_helper'

require 'quick_mem'

module QuickMem
  describe QuickMemory do
    let(:version) { '0.0.5' }
    let(:time_now) { double('time') }
    let(:timestamp) { '30/03/2015 23:28:47' }

    before do
      allow(Time).to receive(:now) { time_now }
      allow(time_now).to receive(:strftime) { timestamp }
    end

    describe '#version' do
      subject { QuickMemory.version }

      it 'outputs the correct version number' do
        expect(subject).to eq version
      end
    end

    describe '#show_stats' do
      subject { QuickMemory.show_stats }

      before do
        allow(QuickMem::MemoryStats).to receive(:show) do
          { total_gc_count: 20 }
        end
      end

      it 'returns a hash' do
        expect(subject).to be_a Hash
      end

      it 'is not empty' do
        expect(subject).not_to be_empty
      end

      it 'contains statistics about the current memory usage' do
        expect(subject[:total_gc_count]).to eql(20)
      end

      it 'contains the version' do
        expect(subject[:version]).to eq version
      end

      it 'contains the timestamp' do
        expect(subject[:timestamp]).to eq timestamp
      end
    end

    describe '#show_summary' do
      subject { QuickMemory.show_summary }
      let(:summary) { double('summary') }

      before do
        allow(QuickMem::Summary).to receive(:new) { summary }
        allow(summary).to receive(:show) { { heap_used_pct: '50.55' } }
      end

      it 'returns a hash' do
        expect(subject).to be_a Hash
      end

      it 'is not empty' do
        expect(subject).not_to be_empty
      end

      it 'contains a summary about the current memory usage' do
        expect(subject[:heap_used_pct]).to eql('50.55')
      end

      it 'contains the version' do
        expect(subject[:version]).to eq version
      end

      it 'contains the timestamp' do
        expect(subject[:timestamp]).to eq timestamp
      end
    end

    describe '#view_objects_by_size' do
      subject { QuickMemory.view_objects_by_size }

      before do
        allow(QuickMem::Dumps).to receive(:top_allocated_objects) do
          { Thread: 1049960, String: 2688465, Class: 976088 }
        end
      end

      it 'returns a hash' do
        expect(subject).to be_a Hash
      end

      it 'is not empty' do
        expect(subject).not_to be_empty
      end

      it 'contains a map of classes to total size of all instances' do
        expect(subject[:objects_by_size]).to eql(String: 2688465, Thread: 1049960, Class: 976088)
      end

      it 'contains the version' do
        expect(subject[:version]).to eq version
      end

      it 'contains the timestamp' do
        expect(subject[:timestamp]).to eq timestamp
      end
    end

    describe '#view_objects_by_count' do
      subject { QuickMemory.view_objects_by_count }

      before do
        allow(QuickMem::Dumps).to receive(:count_top_allocated_objects) do
          { Thread: 104, String: 268, Class: 97 }
        end
      end

      it 'returns a hash' do
        expect(subject).to be_a Hash
      end

      it 'is not empty' do
        expect(subject).not_to be_empty
      end

      it 'contains a map of classes to instance count' do
        expect(subject[:objects_by_count]).to eql(String: 268, Thread: 104, Class: 97)
      end

      it 'contains the version' do
        expect(subject[:version]).to eq version
      end

      it 'contains the timestamp' do
        expect(subject[:timestamp]).to eq timestamp
      end
    end
  end
end


text:
package xsdgen

import (
	"io/ioutil"
	"os"
	"regexp"
	"testing"
)

type testLogger testing.T

func grep(pattern, data string) bool {
	matched, err := regexp.MatchString(pattern, data)
	if err != nil {
		panic(err)
	}
	return matched
}

func (t *testLogger) Printf(format string, v ...interface{}) {
	t.Logf(format, v...)
}

func TestLibrarySchema(t *testing.T) {
	testGen(t, "http://dyomedea.com/ns/library", "testdata/library.xsd")
}
func TestPurchasOrderSchema(t *testing.T) {
	testGen(t, "http://www.example.com/PO1", "testdata/po1.xsd")
}
func TestUSTreasureSDN(t *testing.T) {
	testGen(t, "http://tempuri.org/sdnList.xsd", "testdata/sdn.xsd")
}
func TestSoap(t *testing.T) {
	testGen(t, "http://schemas.xmlsoap.org/soap/encoding/", "testdata/soap11.xsd")
}
func TestSimpleStruct(t *testing.T) {
	testGen(t, "http://example.org/ns", "testdata/simple-struct.xsd")
}
func testGen(t *testing.T, ns string, files ...string) string {
	file, err := ioutil.TempFile("", "xsdgen")
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(file.Name())

	var cfg Config
	cfg.Option(DefaultOptions...)
	cfg.Option(LogOutput((*testLogger)(t)))

	args := []string{"-v", "-o", file.Name(), "-ns", ns}
	err = cfg.GenCLI(append(args, files...)...)
	if err != nil {
		t.Error(err)
	}
	data, err := ioutil.ReadFile(file.Name())
	if err != nil {
		t.Fatal(err)
	}
	return string(data)
}

func TestMixedType(t *testing.T) {
	data := testGen(t, "http://example.org", "testdata/mixed-complex.xsd")
	if !grep(`PositiveNumber[^}]*,chardata`, data) {
		t.Errorf("type decl for PositiveNumber did not contain chardata, got \n%s", data)
	} else {
		t.Logf("got \n%s", data)
	}
}

func TestBase64Binary(t *testing.T) {
	t.Logf("%s\n", testGen(t, "http://example.org/", "testdata/base64.xsd"))
}

func TestSimpleUnion(t *testing.T) {
	t.Logf("%s\n", testGen(t, "http://example.org/", "testdata/simple-union.xsd"))
}


text:
import functools

from veros import runtime_settings as rs, runtime_state as rst, logger

def memoize(func):
    func.cache = {}

    @functools.wraps(func)
    def inner(*args):
        if args not in func.cache:
            func.cache[args] = func(*args)

        return func.cache[args]

    return inner

def _get_solver_class():
    ls = rs.linear_solver

    def _get_best_solver():
        if rst.proc_num > 1:
            try:
                from veros.core.streamfunction.solvers.petsc_ import PETScSolver
            except ImportError:
                logger.warning("PETSc linear solver not available, falling back to SciPy")
            else:
                return PETScSolver

        if rs.backend == "jax" and rs.device == "gpu" and rs.float_type == "float64":
            from veros.core.streamfunction.solvers.scipy_jax import JAXSciPySolver

            return JAXSciPySolver

        from veros.core.streamfunction.solvers.scipy import SciPySolver

        return SciPySolver

    if ls == "best":
        return _get_best_solver()
    elif ls == "petsc":
        from veros.core.streamfunction.solvers.petsc_ import PETScSolver

        return PETScSolver
    elif ls == "scipy":
        from veros.core.streamfunction.solvers.scipy import SciPySolver

        return SciPySolver
    elif ls == "scipy_jax":
        from veros.core.streamfunction.solvers.scipy_jax import JAXSciPySolver

        return JAXSciPySolver

    raise ValueError(f"unrecognized linear solver {ls}")

@memoize
def get_linear_solver(state):
    logger.debug("Initializing linear solver")
    SolverClass = _get_solver_class()
    return SolverClass(state)


text:
"""
This is the basis of the typeclass system.

The idea is have the object as a normal class with the
database-connection tied to itself through a property.

The instances of all the different object types are all tied to their
own database object stored in the 'dbobj' property.  All attribute
get/set operations are channeled transparently to the database object
as desired. You should normally never have to worry about the database
abstraction, just do everything on the TypeClass object.

That an object is controlled by a player/user is just defined by its
'user' property being set.  This means a user may switch which object
they control by simply linking to a new object's user property.
"""

import datetime
from django.conf import settings
from src.typeclasses.typeclass import TypeClass
from src.commands import cmdset, command
from src.comms.models import Channel
from src.utils import logger

__all__ = ("Object", "Character", "Room", "Exit")

_GA = object.__getattribute__
_SA = object.__setattr__
_DA = object.__delattr__

_CONNECT_CHANNEL = None

#
# Base class to inherit from.
#

class Object(TypeClass):
    """
    This is the base class for all in-game objects.  Inherit from this
    to create different types of objects in the game.
    """
    # __init__ is only defined here in order to present docstring to API.
    def __init__(self, dbobj):
        """
        This is the root typeclass object representing all entities
        that has and actual presence in-game. Objects generally has a
        location, can be manipulated and looked at. Most game entities
        you define should inherit from Object at some distance.
        Important subclasses of Object are that Evennia defines by
        default for you are Characters, Exits and Rooms.

        Note that all Objects and its subclasses *must* always be
        created using the ev.create_object() function. This is so the
        typeclass system can be correctly initiated behind the scenes.

        Object Typeclass API:

        * Available properties (only available on *initiated* typeclass objects)

         key (string) - name of object
         name (string)- same as key
         aliases (list of strings) - aliases to the object. Will be saved to database as AliasDB entries but returned as strings.
         dbref (int, read-only) - unique #id-number. Also "id" can be used.
         dbobj (Object, read-only) - link to database model. dbobj.typeclass points back to this class
         typeclass (Object, read-only) - this links back to this class as an identified only. Use self.swap_typeclass() to switch.
         date_created (string) - time stamp of object creation
         permissions (list of strings) - list of permission strings

         player (Player) - controlling player (will also return offline player)
         location (Object) - current location. Is None if this is a room
         home (Object) - safety start-location
         sessions (list of Sessions, read-only) - returns all sessions connected to this object
         has_player (bool, read-only)- will only return *connected* players
         contents (list of Objects, read-only) - returns all objects inside this object (including exits)
         exits (list of Objects, read-only) - returns all exits from this object, if any
         destination (Object) - only set if this object is an exit.
         is_superuser (bool, read-only) - True/False if this user is a superuser

        * Handlers available

         locks - lock-handler: use locks.add() to add new lock strings
         db - attribute-handler: store/retrieve database attributes on this self.db.myattr=val, val=self.db.myattr
         ndb - non-persistent attribute handler: same as db but does not create a database entry when storing data
         scripts - script-handler. Add new scripts to object with scripts.add()
         cmdset - cmdset-handler. Use cmdset.add() to add new cmdsets to object
         nicks - nick-handler. New nicks with nicks.add().

        * Helper methods (see src.objects.objects.py for full headers)

         search(ostring, global_search=False, global_dbref=False, attribute_name=None,
                use_nicks=False, location=None, ignore_errors=False, player=False)
         execute_cmd(raw_string)
         msg(message, from_obj=None, data=None)
         msg_contents(message, exclude=None, from_obj=None, data=None)
         move_to(destination, quiet=False, emit_to_obj=None, use_destination=True, to_none=False)
         copy(new_key=None)
         delete()
         is_typeclass(typeclass, exact=False)
         swap_typeclass(new_typeclass, clean_attributes=False, no_default=True)
         access(accessing_obj, access_type='read', default=False)
         check_permstring(permstring)

        * Hook methods

         basetype_setup()     - only called once, used for behind-the-scenes setup. Normally not modified.
         basetype_posthook_setup() - customization in basetype, after the object has been created; Normally not modified.

         at_object_creation() - only called once, when object is first created. Object customizations go here.
         at_object_delete() - called just before deleting an object. If returning False, deletion is aborted. Note that all objects
                              inside a deleted object are automatically moved to their <home>, they don't need to be removed here.

         at_init()            - called whenever typeclass is cached from memory, at least once every server restart/reload
         at_cmdset_get()      - this is called just before the command handler requests a cmdset from this object
         at_first_login()     - (player-controlled objects only) called once, the very first time user logs in.
         at_pre_login()       - (player-controlled objects only) called every time the user connects, after they have identified, before other setup
         at_post_login()      - (player-controlled objects only) called at the end of login, just before setting the player loose in the world.
         at_disconnect()      - (player-controlled objects only) called just before the user disconnects (or goes linkless)
         at_server_reload()   - called before server is reloaded
         at_server_shutdown() - called just before server is fully shut down

         at_before_move(destination)             - called just before moving object to the destination. If returns False, move is cancelled.
         announce_move_from(destination)         - called in old location, just before move, if obj.move_to() has quiet=False
         announce_move_to(source_location)       - called in new location, just after move, if obj.move_to() has quiet=False
         at_after_move(source_location)          - always called after a move has been successfully performed.
         at_object_leave(obj, target_location)   - called when an object leaves this object in any fashion
         at_object_receive(obj, source_location) - called when this object receives another object

         at_before_traverse(traversing_object)                 - (exit-objects only) called just before an object traverses this object
         at_after_traverse(traversing_object, source_location) - (exit-objects only) called just after a traversal has happened.
         at_failed_traverse(traversing_object)      - (exit-objects only) called if traversal fails and property err_traverse is not defined.

         at_msg_receive(self, msg, from_obj=None, data=None) - called when a message (via self.msg()) is sent to this obj.
                                                               If returns false, aborts send.
         at_msg_send(self, msg, to_obj=None, data=None) - called when this objects sends a message to someone via self.msg().

         return_appearance(looker) - describes this object. Used by "look" command by default
         at_desc(looker=None)      - called by 'look' whenever the appearance is requested.
         at_get(getter)            - called after object has been picked up. Does not stop pickup.
         at_drop(dropper)          - called when this object has been dropped.
         at_say(speaker, message)  - by default, called if an object inside this object speaks

         """
        super(Object, self).__init__(dbobj)

    ## methods inherited from the database object (overload them here)

    def search(self, ostring,
               global_search=False,
               global_dbref=False,
               attribute_name=None,
               use_nicks=False,
               location=None,
               ignore_errors=False,
               player=False):
        """
        Perform a standard object search in the database, handling
        multiple results and lack thereof gracefully.

        ostring: (str) The string to match object names against.
                       Obs - To find a player, append * to the
                       start of ostring.
        global_search(bool): Search all objects, not just the current
                       location/inventory
        attribute_name (string) Which attribute to match
                        (if None, uses default 'name')
        use_nicks (bool) : Use nickname replace (off by default)
        location (Object): If None, use caller's current location
        ignore_errors (bool): Don't display any error messages even
                        if there are none/multiple matches -
                        just return the result as a list.
        player (Objectt):  Don't search for an Object but a Player.
                           This will also find players that don't
                           currently have a character.

        Returns - a unique Object/Player match or None. All error
                  messages are handled by system-commands and the parser-handlers
                  specified in settings.

        Use *<string> to search for objects controlled by a specific
        player. Note that the object controlled by the player will be
        returned, not the player object itself. This also means that
        this will not find Players without a character. Use the keyword
        player=True to find player objects.

        Note - for multiple matches, the engine accepts a number
        linked to the key in order to separate the matches from
        each other without showing the dbref explicitly. Default
        syntax for this is 'N-searchword'. So for example, if there
        are three objects in the room all named 'ball', you could
        address the individual ball as '1-ball', '2-ball', '3-ball'
        etc.
        """
        return self.dbobj.search(ostring,
                                 global_search=global_search,
                                 global_dbref=global_dbref,
                                 attribute_name=attribute_name,
                                 use_nicks=use_nicks,
                                 location=location,
                                 ignore_errors=ignore_errors,
                                 player=player)

    def execute_cmd(self, raw_string):
        """
        Do something as this object. This command transparently
        lets its typeclass execute the command. Evennia also calls
        this method whenever the player sends a command on the command line.

        Argument:
        raw_string (string) - raw command input

        Returns Deferred - this is an asynchronous Twisted object that will
            not fire until the command has actually finished executing. To overload
            this one needs to attach callback functions to it, with addCallback(function).
            This function will be called with an eventual return value from the command
            execution.

            This return is not used at all by Evennia by default, but might be useful
            for coders intending to implement some sort of nested command structure.
        """
        return self.dbobj.execute_cmd(raw_string)

    def msg(self, message, from_obj=None, data=None):
        """
        Emits something to any sessions attached to the object.

        message (str): The message to send
        from_obj (obj): object that is sending.
        data (object): an optional data object that may or may not
                       be used by the protocol.
        """
        self.dbobj.msg(message, from_obj=from_obj, data=data)

    def msg_contents(self, message, exclude=None, from_obj=None, data=None):
        """
        Emits something to all objects inside an object.

        exclude is a list of objects not to send to. See self.msg() for more info.
        """
        self.dbobj.msg_contents(message, exclude=exclude, from_obj=from_obj, data=data)

    def move_to(self, destination, quiet=False,
                emit_to_obj=None, use_destination=True, to_none=False):
        """
        Moves this object to a new location. Note that if <destination> is an
        exit object (i.e. it has "destination"!=None), the move_to will
        happen to this destination and -not- into the exit object itself, unless
        use_destination=False. Note that no lock checks are done by this function,
        such things are assumed to have been handled before calling move_to.

        destination: (Object) Reference to the object to move to. This
                     can also be an exit object, in which case the destination
                     property is used as destination.
        quiet:  (bool)    If true, don't emit left/arrived messages.
        emit_to_obj: (Object) object to receive error messages
        use_destination (bool): Default is for objects to use the "destination" property
                              of destinations as the target to move to. Turning off this
                              keyword allows objects to move "inside" exit objects.
        to_none - allow destination to be None. Note that no hooks are run when moving
                      to a None location. If you want to run hooks, run them manually.
        Returns True/False depending on if there were problems with the move. This method
                may also return various error messages to the emit_to_obj.

        """
        return self.dbobj.move_to(destination, quiet=quiet,
                                  emit_to_obj=emit_to_obj, use_destination=use_destination)

    def copy(self, new_key=None):
        """
        Makes an identical copy of this object. If you want to customize the copy by
        changing some settings, use ObjectDB.object.copy_object() directly.

        new_key (string) - new key/name of copied object. If new_key is not specified, the copy will be named
                           <old_key>_copy by default.
        Returns: Object (copy of this one)
        """
        return self.dbobj.copy(new_key=new_key)

    def delete(self):
        """
        Deletes this object.
        Before deletion, this method makes sure to move all contained
        objects to their respective home locations, as well as clean
        up all exits to/from the object.

        Returns: boolean True if deletion succeded, False if there
                 were errors during deletion or deletion otherwise
                 failed.
        """
        return self.dbobj.delete()

    # methods inherited from the typeclass system

    def is_typeclass(self, typeclass, exact=False):
        """
        Returns true if this object has this type
          OR has a typeclass which is an subclass of
          the given typeclass.

        typeclass - can be a class object or the
                python path to such an object to match against.

        exact - returns true only if the object's
               type is exactly this typeclass, ignoring
               parents.

        Returns: Boolean
        """
        return self.dbobj.is_typeclass(typeclass, exact=exact)

    def swap_typeclass(self, new_typeclass, clean_attributes=False, no_default=True):
        """
        This performs an in-situ swap of the typeclass. This means
        that in-game, this object will suddenly be something else.
        Player will not be affected. To 'move' a player to a different
        object entirely (while retaining this object's type), use
        self.player.swap_object().

        Note that this might be an error prone operation if the
        old/new typeclass was heavily customized - your code
        might expect one and not the other, so be careful to
        bug test your code if using this feature! Often its easiest
        to create a new object and just swap the player over to
        that one instead.

        Arguments:
        new_typeclass (path/classobj) - type to switch to
        clean_attributes (bool/list) - will delete all attributes
                           stored on this object (but not any
                           of the database fields such as name or
                           location). You can't get attributes back,
                           but this is often the safest bet to make
                           sure nothing in the new typeclass clashes
                           with the old one. If you supply a list,
                           only those named attributes will be cleared.
        no_default - if this is active, the swapper will not allow for
                     swapping to a default typeclass in case the given
                     one fails for some reason. Instead the old one
                     will be preserved.
        Returns:
          boolean True/False depending on if the swap worked or not.

        """
        return self.dbobj.swap_typeclass(new_typeclass, clean_attributes=clean_attributes, no_default=no_default)

    def access(self, accessing_obj, access_type='read', default=False):
        """
        Determines if another object has permission to access this object in whatever way.

          accessing_obj (Object)- object trying to access this one
          access_type (string) - type of access sought
          default (bool) - what to return if no lock of access_type was found

        This function will call at_access_success or at_access_failure depending on the
        outcome of the access check.

        """
        if self.dbobj.access(accessing_obj, access_type=access_type, default=default):
            self.at_access_success(accessing_obj, access_type)
            return True
        else:
            self.at_access_failure(accessing_obj, access_type)
            return False

    def check_permstring(self, permstring):
        """
        This explicitly checks the given string against this object's
        'permissions' property without involving any locks.

        permstring (string) - permission string that need to match a permission on the object.
                              (example: 'Builders')
        """
        return self.dbobj.check_permstring(permstring)

    def __eq__(self, other):
        """
        Checks for equality against an id string or another object or user.

        This has be located at this level, having it in the
        parent doesn't work.
        """
        try:
                return _GA(_GA(self, "dbobj"),"dbid") == _GA(_GA(other,"dbobj"),"dbid")
        except AttributeError:
           # compare players instead
            try:
                return _GA(_GA(_GA(self, "dbobj"),"player"),"uid") == _GA(_GA(other, "player"),"uid")
            except AttributeError:
                return False

    ## hooks called by the game engine

    def basetype_setup(self):
        """
        This sets up the default properties of an Object,
        just before the more general at_object_creation.

        You normally don't need to change this unless you change some fundamental
        things like names of permission groups.
        """
        # the default security setup fallback for a generic
        # object. Overload in child for a custom setup. Also creation
        # commands may set this (create an item and you should be its
        # controller, for example)

        dbref = self.dbobj.dbref
        self.locks.add(";".join(["control:perm(Immortals)",  # edit locks/permissions, delete
                                 "examine:perm(Builders)",   # examine properties
                                 "view:all()",               # look at object (visibility)
                                 "edit:perm(Wizards)",       # edit properties/attributes
                                 "delete:perm(Wizards)",     # delete object
                                 "get:all()",                # pick up object
                                 "call:true()",              # allow to call commands on this object
                                 "puppet:id(%s) or perm(Immortals) or pperm(Immortals)" % dbref])) # restricts puppeting of this object

    def basetype_posthook_setup(self):
        """
        Called once, after basetype_setup and at_object_creation. This should generally not be overloaded unless
        you are redefining how a room/exit/object works. It allows for basetype-like setup
        after the object is created. An example of this is EXITs, who need to know keys, aliases, locks
        etc to set up their exit-cmdsets.
        """
        pass

    def at_object_creation(self):
        """
        Called once, when this object is first created.
        """
        pass

    def at_object_delete(self):
        """
        Called just before the database object is
        permanently delete()d from the database. If
        this method returns False, deletion is aborted.
        """
        return True

    def at_init(self):
        """
        This is always called whenever this object is initiated --
        that is, whenever it its typeclass is cached from memory. This
        happens on-demand first time the object is used or activated
        in some way after being created but also after each server
        restart or reload.
        """
        pass

    def at_cmdset_get(self):
        """
        Called just before cmdsets on this object are requested by the
        command handler. If changes need to be done on the fly to the cmdset
        before passing them on to the cmdhandler, this is the place to do it.
        This is called also if the object currently have no cmdsets.
        """
        pass

    def at_first_login(self):
        """
        Only called once, the very first
        time the user logs in.
        """
        pass
    def at_pre_login(self):
        """
        Called every time the user logs in,
        before they are actually logged in.
        """
        pass
    def at_post_login(self):
        """
        Called at the end of the login
        process, just before letting
        them loose.
        """
        pass

    def at_disconnect(self):
        """
        Called just before user
        is disconnected.
        """
        pass

    def at_server_reload(self):
        """
        This hook is called whenever the server is shutting down for restart/reboot.
        If you want to, for example, save non-persistent properties across a restart,
        this is the place to do it.
        """
        pass

    def at_server_shutdown(self):
        """
        This hook is called whenever the server is shutting down fully (i.e. not for
        a restart).
        """
        pass

    def at_access_success(self, accessing_obj, access_type):
        """
        This hook is called whenever accessing_obj succeed a lock check of type access_type
        on this object, for whatever reason. The return value of this hook is not used,
        the lock will still pass regardless of what this hook does (use lockstring/funcs to tweak
        the lock result).
        """
        pass

    def at_access_failure(self, accessing_obj, access_type):
        """
        This hook is called whenever accessing_obj fails a lock check of type access_type
        on this object, for whatever reason. The return value of this hook is not used, the
        lock will still fail regardless of what this hook does (use lockstring/funcs to tweak the
        lock result).
        """
        pass

    # hooks called when moving the object

    def at_before_move(self, destination):
        """
        Called just before starting to move
        this object to destination.

        destination - the object we are moving to

        If this method returns False/None, the move
        is cancelled before it is even started.
        """
        #return has_perm(self, destination, "can_move")
        return True

    def announce_move_from(self, destination):
        """
        Called if the move is to be announced. This is
        called while we are still standing in the old
        location.

        destination - the place we are going to.
        """
        if not self.location:
            return
        name = self.name
        loc_name = ""
        loc_name = self.location.name
        dest_name = destination.name
        string = "%s is leaving %s, heading for %s."
        self.location.msg_contents(string % (name, loc_name, dest_name), exclude=self)

    def announce_move_to(self, source_location):
        """
        Called after the move if the move was not quiet. At this
        point we are standing in the new location.

        source_location - the place we came from
        """

        name = self.name
        if not source_location and self.location.has_player:
            # This was created from nowhere and added to a player's
            # inventory; it's probably the result of a create command.
            string = "You now have %s in your possession." % name
            self.location.msg(string)
            return

        src_name = "nowhere"
        loc_name = self.location.name
        if source_location:
            src_name = source_location.name
        string = "%s arrives to %s from %s."
        self.location.msg_contents(string % (name, loc_name, src_name), exclude=self)

    def at_after_move(self, source_location):
        """
        Called after move has completed, regardless of quiet mode or not.
        Allows changes to the object due to the location it is now in.

        source_location - where we came from
        """
        pass

    def at_object_leave(self, moved_obj, target_location):
        """
        Called just before an object leaves from inside this object

        moved_obj - the object leaving
        target_location - where the object is going.
        """
        pass

    def at_object_receive(self, moved_obj, source_location):
        """
        Called after an object has been moved into this object.

        moved_obj - the object moved into this one
        source_location - where moved_object came from.
        """
        pass

    def at_before_traverse(self, traversing_object):
        """
        Called just before an object uses this object to
        traverse to another object (i.e. this object is a type of Exit)

        The target location should normally be available as self.destination.
        """
        pass

    def at_traverse(self, traversing_object, target_location):
        """
        This hook is responsible for handling the actual traversal, normally
        by calling traversing_object.move_to(target_location). It is normally
        only implemented by Exit objects. If it returns False (usually because move_to
        returned False), at_after_traverse below should not be called and
        instead at_failed_traverse should be called.
        """
        pass

    def at_after_traverse(self, traversing_object, source_location):
        """
        Called just after an object successfully used this object to
        traverse to another object (i.e. this object is a type of Exit)

        The target location should normally be available as self.destination.
        """
        pass

    def at_failed_traverse(self, traversing_object):
        """
        This is called if an object fails to traverse this object for some
        reason. It will not be called if the attribute err_traverse is defined,
        that attribute will then be echoed back instead.
        """
        pass

    def at_msg_receive(self, msg, from_obj=None, data=None):
        """
        This hook is called whenever someone
        sends a message to this object.

        Note that from_obj may be None if the sender did
        not include itself as an argument to the obj.msg()
        call - so you have to check for this. .

        Consider this a pre-processing method before
        msg is passed on to the user sesssion. If this
        method returns False, the msg will not be
        passed on.
        Input:
            msg = the message received
            from_obj = the one sending the message
        Output:
            boolean True/False
        """
        return True

    def at_msg_send(self, msg, to_obj=None, data=None):
        """
        This is a hook that is called when /this/ object
        sends a message to another object with obj.msg()
        while also specifying that it is the one sending.

        Note that this method is executed on the object
        passed along with the msg() function (i.e. using
        obj.msg(msg, caller) will then launch caller.at_msg())
        and if no object was passed, it will never be called.
        """
        pass

    # hooks called by the default cmdset.

    def return_appearance(self, pobject):
        """
        This is a convenient hook for a 'look'
        command to call.
        """
        if not pobject:
            return
        # get and identify all objects
        visible = (con for con in self.contents if con != pobject and con.access(pobject, "view"))
        exits, users, things = [], [], []
        for con in visible:
            key = con.key
            if con.destination:
                exits.append(key)
            elif con.has_player:
                users.append("{c%s{n" % key)
            else:
                things.append(key)
        # get description, build string
        string = "{c%s{n" % self.key
        desc = self.db.desc
        if desc:
            string += "\n %s" % desc
        if exits:
            string += "\n{wExits:{n " + ", ".join(exits)
        if users or things:
            string += "\n{wYou see:{n " + ", ".join(users + things)
        return string

    def at_desc(self, looker=None):
        """
        This is called whenever someone looks
        at this object. Looker is the looking
        object.
        """
        pass

    def at_get(self, getter):
        """
        Called when this object has been picked up. Obs-
        this method cannot stop the pickup - use permissions
        for that!

        getter - the object getting this object.
        """
        pass

    def at_drop(self, dropper):
        """
        Called when this object has been dropped.

        dropper - the object which just dropped this object.
        """
        pass
    def at_say(self, speaker, message):
        """
        Called on this object if an object inside this object speaks.
        The string returned from this method is the final form
        of the speech. Obs - you don't have to add things like
        'you say: ' or similar, that is handled by the say command.

        speaker - the object speaking
        message - the words spoken.
        """
        return message

#
# Base Player object
#

class Character(Object):
    """
    This is just like the Object except it implements its own
    version of the at_object_creation to set up the script
    that adds the default cmdset to the object.
    """

    def basetype_setup(self):
        """
        Setup character-specific security

        You should normally not need to overload this, but if you do, make
        sure to reproduce at least the two last commands in this method (unless
        you want to fundamentally change how a Character object works).

        """
        super(Character, self).basetype_setup()
        self.locks.add(";".join(["get:false()",  # noone can pick up the character
                                 "call:false()"])) # no commands can be called on character from outside
        # add the default cmdset
        self.cmdset.add_default(settings.CMDSET_DEFAULT, permanent=True)

    def at_object_creation(self):
        """
        All this does (for now) is to add the default cmdset. Since
        the script is permanently stored to this object (the permanent
        keyword creates a script to do this), we should never need to
        do this again for as long as this object exists.
        """
        pass

    def at_after_move(self, source_location):
        "Default is to look around after a move."
        self.execute_cmd('look')

    def at_disconnect(self):
        """
        We stove away the character when logging off, otherwise the character object will
        remain in the room also after the player logged off ("headless", so to say).
        """
        global _CONNECT_CHANNEL
        if not _CONNECT_CHANNEL:
            try:
                _CONNECT_CHANNEL = Channel.objects.filter(db_key=settings.CHANNEL_CONNECTINFO[0])[0]
            except Exception, e:
                logger.log_trace()

        if self.location: # have to check, in case of multiple connections closing
            self.location.msg_contents("%s has left the game." % self.name, exclude=[self])
            self.db.prelogout_location = self.location
            self.location = None
        if _CONNECT_CHANNEL:
            now = datetime.datetime.now()
            now = "%02i-%02i-%02i(%02i:%02i)" % (now.year, now.month, now.day, now.hour, now.minute)
            _CONNECT_CHANNEL.tempmsg("[%s, %s]: {R%s disconnected{n" % (_CONNECT_CHANNEL.key, now, self.key))

    def at_post_login(self):
        """
        This recovers the character again after having been "stoved away" at disconnect.
        """
        global _CONNECT_CHANNEL
        if not _CONNECT_CHANNEL:
            try:
                _CONNECT_CHANNEL = Channel.objects.filter(db_key=settings.CHANNEL_CONNECTINFO[0])[0]
            except Exception, e:
                logger.log_trace()
        if self.db.prelogout_location:
            # try to recover
            self.location = self.db.prelogout_location
        if self.location == None:
            # make sure location is never None (home should always exist)
            self.location = self.home
        # save location again to be sure
        self.db.prelogout_location = self.location

        self.location.msg_contents("%s has entered the game." % self.name, exclude=[self])
        self.location.at_object_receive(self, self.location)
        # call look
        self.execute_cmd("look")
        # send to connect channel, if available
        if _CONNECT_CHANNEL:
            now = datetime.datetime.now()
            now = "%02i-%02i-%02i(%02i:%02i)" % (now.year, now.month, now.day, now.hour, now.minute)
            _CONNECT_CHANNEL.tempmsg("[%s, %s]: {G%s connected{n" % (_CONNECT_CHANNEL.key, now, self.key))

#
# Base Room object
#

class Room(Object):
    """
    This is the base room object. It's basically
    like any Object except its location is None.
    """
    def basetype_setup(self):
        """
        Simple setup, shown as an example
        (since default is None anyway)

        """

        super(Room, self).basetype_setup()
        self.locks.add(";".join(["get:false()",
                                 "puppet:false()"])) # would be weird to puppet a room ...
        self.location = None

#
# Exits
#

class Exit(Object):
    """
    This is the base exit object - it connects a location to
    another. This is done by the exit assigning a "command" on itself
    with the same name as the exit object (to do this we need to
    remember to re-create the command when the object is cached since it must be
    created dynamically depending on what the exit is called). This
    command (which has a high priority) will thus allow us to traverse exits
    simply by giving the exit-object's name on its own.

    """

    # Helper classes and methods to implement the Exit. These need not
    # be overloaded unless one want to change the foundation for how
    # Exits work. See the end of the class for hook methods to overload.

    def create_exit_cmdset(self, exidbobj):
        """
        Helper function for creating an exit command set + command.

        The command of this cmdset has the same name as the Exit object
        and allows the exit to react when the player enter the exit's name,
        triggering the movement between rooms.

        Note that exitdbobj is an ObjectDB instance. This is necessary
        for handling reloads and avoid tracebacks if this is called while
        the typeclass system is rebooting.
        """
        class ExitCommand(command.Command):
            """
            This is a command that simply cause the caller
            to traverse the object it is attached to.
            """
            locks = "cmd:all()" # should always be set to this.
            obj = None
            arg_regex=r"\s.*?|$"
            is_exit = True      # this helps cmdhandler disable exits in cmdsets with no_exits=True.

            def func(self):
                "Default exit traverse if no syscommand is defined."

                if self.obj.access(self.caller, 'traverse'):
                    # we may traverse the exit.
                    self.obj.at_traverse(self.caller, self.obj.destination)
                else:
                    # exit is locked
                    if self.obj.db.err_traverse:
                        # if exit has a better error message, let's use it.
                        self.caller.msg(self.obj.db.err_traverse)
                    else:
                        # No shorthand error message. Call hook.
                        self.obj.at_failed_traverse(self.caller)

        # create an exit command.
        cmd = ExitCommand()
        cmd.key = exidbobj.db_key.strip().lower()
        cmd.obj = exidbobj
        cmd.aliases = exidbobj.aliases
        cmd.locks = str(exidbobj.locks)
        cmd.destination = exidbobj.db_destination
        cmd.auto_help = False
        # create a cmdset
        exit_cmdset = cmdset.CmdSet(None)
        exit_cmdset.key = '_exitset'
        exit_cmdset.priority = 9
        exit_cmdset.duplicates = True
        # add command to cmdset
        exit_cmdset.add(cmd)
        return exit_cmdset

    # Command hooks
    def basetype_setup(self):
        """
        Setup exit-security

        You should normally not need to overload this - if you do make sure you
        include all the functionality in this method.
        """
        super(Exit, self).basetype_setup()

        # setting default locks (overload these in at_object_creation()
        self.locks.add(";".join(["puppet:false()", # would be weird to puppet an exit ...
                                 "traverse:all()", # who can pass through exit by default
                                 "get:false()"]))   # noone can pick up the exit

        # an exit should have a destination (this is replaced at creation time)
        if self.dbobj.location:
            self.destination = self.dbobj.location

    def at_cmdset_get(self):
        """
        Called when the cmdset is requested from this object, just before the cmdset is
        actually extracted. If no Exit-cmdset is cached, create it now.
        """

        if self.ndb.exit_reset or not self.cmdset.has_cmdset("_exitset", must_be_default=True):
            # we are resetting, or no exit-cmdset was set. Create one dynamically.
            self.cmdset.add_default(self.create_exit_cmdset(self.dbobj), permanent=False)
            self.ndb.exit_reset = False

    # this and other hooks are what usually can be modified safely.

    def at_object_creation(self):
        "Called once, when object is first created (after basetype_setup)."
        pass

    def at_traverse(self, traversing_object, target_location):
        """
        This implements the actual traversal. The traverse lock has already been
        checked (in the Exit command) at this point.
        """
        source_location = traversing_object.location
        if traversing_object.move_to(target_location):
            self.at_after_traverse(traversing_object, source_location)
        else:
            if self.db.err_traverse:
                # if exit has a better error message, let's use it.
                self.caller.msg(self.db.err_traverse)
            else:
                # No shorthand error message. Call hook.
                self.at_failed_traverse(traversing_object)

    def at_after_traverse(self, traversing_object, source_location):
        """
        Called after a successful traverse.
        """
        pass

    def at_failed_traverse(self, traversing_object):
        """
        This is called if an object fails to traverse this object for some
        reason. It will not be called if the attribute "err_traverse" is defined,
        that attribute will then be echoed back instead as a convenient shortcut.

        (See also hooks at_before_traverse and at_after_traverse).
        """
        traversing_object.msg("You cannot go there.")


text:
import React from 'react';
import Header from '../containers/Header';
import Footer from './Footer';
import Sidebar from '../containers/Sidebar';
import config from 'react-global-configuration';

class Layout extends React.Component {

	constructor(){
		super();
	}

    render() {

	let body = (

						<Sidebar/>

                    {this.props.children}

			);

	let login = (

Sign In

		);

        return (

							{this.props.loggedIn ? body : login}

        );
    }
}

export default Layout;


text:
package consumer.sts;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.10-b140803.1500
 * Generated source version: 2.2
 *
 */
@WebService(name = "IWSTrust13Sync", targetNamespace = "http://schemas.microsoft.com/ws/2008/06/identity/securitytokenservice")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
@XmlSeeAlso({
    ObjectFactory.class
})
public interface IWSTrust13Sync {

    /**
     *
     * @param message
     * @return
     *     returns consumer.sts.RequestSecurityTokenResponseCollectionType
     */
    @WebMethod(operationName = "Trust13Issue", action = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue")
    @WebResult(name = "RequestSecurityTokenResponseCollection", targetNamespace = "http://docs.oasis-open.org/ws-sx/ws-trust/200512", partName = "Trust13IssueResult")
    public RequestSecurityTokenResponseCollectionType trust13Issue(
        @WebParam(name = "RequestSecurityToken", targetNamespace = "http://docs.oasis-open.org/ws-sx/ws-trust/200512", partName = "message")
        RequestSecurityTokenType message);

}


text:
using System;
using System.Collections;
using System.Globalization;

namespace MindTouch.Deki.Script.Runtime.Library {
    public static partial class DekiScriptLibrary {

        //--- Constants ---
        private static readonly Random RANDOM = new Random();

        //--- Class Methods ---
        [DekiScriptFunction("num.format", "Show number in custom format.", IsIdempotent = true)]
        public static string NumberFormat(
            [DekiScriptParam("number")] double number,
            [DekiScriptParam("number format string (http://msdn2.microsoft.com/en-us/library/0c899ak8(VS.80).aspx)")] string format
        ) {
            CultureInfo culture = GetCulture();
            return number.ToString(format, culture);
        }

        [DekiScriptFunction("num.round", "Round to nearest number with given precision.", IsIdempotent = true)]
        public static double NumberRound(
            [DekiScriptParam("number")] double number,
            [DekiScriptParam("digits to keep after decimal point (default: 0)", true)] int? digits
        ) {
            int d = digits ?? 0;
            if(d >= 0) {
                return Math.Round(number, d);
            }
            double ten = Math.Pow(10, -d);
            return Math.Round(number / ten, 0) * ten;
        }

        [DekiScriptFunction("num.abs", "Get absolute value of number.")]
        public static double NumberAbs(
            [DekiScriptParam("number")] double number
        ) {
            return Math.Abs(number);
        }

        [DekiScriptFunction("num.acos", "Get the angle whose cosine is the specified number.")]
        public static double NumberAcos(
            [DekiScriptParam("number")] double number
        ) {
            return Math.Acos(number);
        }

        [DekiScriptFunction("num.asin", "Get the angle whose sine is the specified number.")]
        public static double NumberAsin(
            [DekiScriptParam("number")] double number
        ) {
            return Math.Asin(number);
        }

        [DekiScriptFunction("num.atan", "Get the angle whose tangent is the specified number.")]
        public static double NumberAtan(
            [DekiScriptParam("number")] double number
        ) {
            return Math.Atan(number);
        }

        [DekiScriptFunction("num.atan2", "Get the angle whose tangent is the quotient of two specified numbers.")]
        public static double NumberAtan2(
            [DekiScriptParam("number")] double x,
            [DekiScriptParam("number")] double y
        ) {
            return Math.Atan2(x, y);
        }

        [DekiScriptFunction("num.ceiling", "Get the smallest integer greater or equal to the specified number.")]
        public static double NumberCeiling(
            [DekiScriptParam("number")] double number
        ) {
            return Math.Ceiling(number);
        }

        [DekiScriptFunction("num.cos", "Get the cosine of the specified angle.")]
        public static double NumberCos(
            [DekiScriptParam("angle")] double angle
        ) {
            return Math.Cos(angle);
        }

        [DekiScriptFunction("num.cosh", "Get the hyperbolic cosine of the specified angle.")]
        public static double NumberCosh(
            [DekiScriptParam("angle")] double angle
        ) {
            return Math.Cosh(angle);
        }

        [DekiScriptFunction("num.exp", "Get e raised to the specified number.", IsIdempotent = true)]
        public static double NumberExp(
            [DekiScriptParam("number")] double number
        ) {
            return Math.Exp(number);
        }

        [DekiScriptFunction("num.floor", "Get the largest integer less or equal to the specified number.", IsIdempotent = true)]
        public static double NumberFloor(
            [DekiScriptParam("number")] double number
        ) {
            return Math.Floor(number);
        }

        [DekiScriptFunction("num.log", "Get the logarithm of the specified number in the specified base.", IsIdempotent = true)]
        public static double NumberLog(
            [DekiScriptParam("number")] double number,
            [DekiScriptParam("base (default: e)", true)] double? @base
        ) {
            return @base.HasValue ? Math.Log(number, @base.Value) : Math.Log(number);
        }

        [DekiScriptFunction("num.max", "Get the larger of two numbers.", IsIdempotent = true)]
        public static double NumberMax(
            [DekiScriptParam("first number")] double first,
            [DekiScriptParam("second number")] double second
        ) {
            return Math.Max(first, second);
        }

        [DekiScriptFunction("num.min", "Get the smaller of two numbers.", IsIdempotent = true)]
        public static double NumberMin(
            [DekiScriptParam("first number")] double first,
            [DekiScriptParam("second number")] double second
        ) {
            return Math.Min(first, second);
        }

        [DekiScriptFunction("num.pow", "Get the specified number raised to the specified power.", IsIdempotent = true)]
        public static double NumberPow(
            [DekiScriptParam("base number")] double @base,
            [DekiScriptParam("exponent number")] double exponent
        ) {
            return Math.Pow(@base, exponent);
        }

        [DekiScriptFunction("num.sign", "Get a value indicating the sign of the number.", IsIdempotent = true)]
        public static int NumberSign(
            [DekiScriptParam("number")] double number
        ) {
            return Math.Sign(number);
        }

        [DekiScriptFunction("num.sin", "Get the sine of the specified angle.", IsIdempotent = true)]
        public static double NumberSin(
            [DekiScriptParam("angle")] double angle
        ) {
            return Math.Sin(angle);
        }

        [DekiScriptFunction("num.sinh", "Get the hyperbolic sine of the specified angle.", IsIdempotent = true)]
        public static double NumberSinh(
            [DekiScriptParam("angle")] double angle
        ) {
            return Math.Sinh(angle);
        }

        [DekiScriptFunction("num.sqrt", "Get the square root of the specified number.", IsIdempotent = true)]
        public static double NumberSqrt(
            [DekiScriptParam("number")] double number
        ) {
            return Math.Sqrt(number);
        }

        [DekiScriptFunction("num.tan", "Get the tangent of the specified angle.", IsIdempotent = true)]
        public static double NumberTan(
            [DekiScriptParam("angle")] double angle
        ) {
            return Math.Tan(angle);
        }

        [DekiScriptFunction("num.tanh", "Get the hyperbolic tangent of the specified angle.", IsIdempotent = true)]
        public static double NumberTanh(
            [DekiScriptParam("angle")] double angle
        ) {
            return Math.Tanh(angle);
        }

        [DekiScriptFunction("num.int", "Get the integral part of the specified number.", IsIdempotent = true)]
        public static double NumberInt(
            [DekiScriptParam("number")] double number
        ) {
            return Math.Truncate(number);
        }

        [DekiScriptFunction("num.isnan", "Check if number is not-a-number (NaN).", IsIdempotent = true)]
        public static bool NumberIsNan(
            [DekiScriptParam("number")] double number
        ) {
            return double.IsNaN(number);
        }

        [DekiScriptFunction("num.isinfinity", "Check if number is infinite.", IsIdempotent = true)]
        public static bool NumberIsInfinity(
            [DekiScriptParam("number")] double number
        ) {
            return double.IsInfinity(number);
        }

        [DekiScriptFunction("num.isnegativeinfinity", "Check if number is negative infinity.", IsIdempotent = true)]
        public static bool NumberIsNegativeInfinity(
            [DekiScriptParam("number")] double number
        ) {
            return double.IsNegativeInfinity(number);
        }

        [DekiScriptFunction("num.ispositiveinfinity", "Check if number is positive infinity.", IsIdempotent = true)]
        public static bool NumberIsPositiveInfinity(
            [DekiScriptParam("number")] double number
        ) {
            return double.IsPositiveInfinity(number);
        }

        [DekiScriptFunction("num.cast", "Cast value to a number or nil if not possible.", IsIdempotent = true)]
        public static double? NumberCast(
            [DekiScriptParam("value to cast")] object value
        ) {
            try {
                return SysUtil.ChangeType<double>(value);
            } catch {
                return null;
            }
        }

        [DekiScriptFunction("num.series", "Create a series of numbers.", IsIdempotent = true)]
        public static ArrayList NumberSeries(
            [DekiScriptParam("starting value")] double start,
            [DekiScriptParam("ending value")] double end,
            [DekiScriptParam("step value (default: 1 or -1)", true)] double? step
        ) {

            // check if step is zero
            double increment = step ?? (((end - start) >= 0.0) ? 1.0 : -1.0);
            if(increment == 0) {
                return new ArrayList();
            }

            // check if count is going in the wrong direction or if result is too large
            int count;
            try {
                double total = (end - start) / increment;
                if(total < 0) {
                    return new ArrayList();
                }
                count = (int)Math.Min(total, 1000);
            } catch {

                // arithmetic overflow
                return new ArrayList();
            }

            // populate series
            ArrayList result = new ArrayList(count);
            for(int i = 0; i <= count; ++i) {
                result.Add(start + i * increment);
            }
            return result;
        }

        [DekiScriptFunction("num.random", "Return a random number between 0 and 1.")]
        public static double NumberRandom() {
            return RANDOM.NextDouble();
        }
    }
}


text:
require 'spec_integration_helper'

feature 'Common use cases > Shortcuts' do
  let(:cat_owner)     { test_app_page.cat_owner }
  let(:test_app_page) { HomePage.new }

  let(:applier) do
    SPV::Applier.new(test_app_page) do
      fixtures ['ned_stark']
      waiter   &:wait_for_cat_owner
    end
  end

  let(:applier_with_event) do
    applier.shift_event {
      test_app_page.link_with_one_request.click
    }
  end

  before do
    test_app_page.load

    applier_with_event.apply_vcr do
      shortcut_path 'c', 'custom'

      fixtures [':c/bran_stark']
    end
  end

  it 'applies a stored fixture in the directory defined in the shortcut path' do
    expect(cat_owner).to have_content('Bran Stark')
  end
end