text:
<?php

namespace OpenSkill\Datatable\Providers;

use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use OpenSkill\Datatable\Columns\ColumnConfiguration;
use OpenSkill\Datatable\Columns\ColumnOrder;
use OpenSkill\Datatable\Columns\ColumnSearch;
use OpenSkill\Datatable\Columns\Searchable\DefaultSearchable;
use OpenSkill\Datatable\Data\ResponseData;
use OpenSkill\Datatable\DatatableException;
use OpenSkill\Datatable\Queries\QueryConfiguration;

/**
 * Class CollectionProvider
 * @package OpenSkill\Datatable\Providers
 *
 * Provider that is able to provide data based on a initial passed collection.
 */
class QueryBuilderProvider implements Provider
{
    /**
     * @var QueryBuilder The original query, as passed to us.
     */
    private $originalQuery;

    /**
     * @var QueryBuilder The query, before limits are applied
     */
    private $queryBeforeLimits;

    /**
     * @var QueryBuilder The underlying query
     */
    private $query;

    /**
     * @var QueryConfiguration
     */
    private $queryConfiguration;

    /**
     * @var array an array that will hold the search functions for each column
     */
    private $columnConfiguration = [];

    /**
     * CollectionProvider constructor.
     * @param QueryBuilder $query The query to base the built query on
     */
    public function __construct(QueryBuilder $query)
    {
        $this->originalQuery = $query;
        $this->query = clone $query;
    }

    /**
     * Here the DTQueryConfiguration is passed to prepare the provider for the processing of the request.
     * This will only be called when the DTProvider needs to handle the request.
     * It will never be called when the DTProvider does not need to handle the request.
     *
     * @param QueryConfiguration $queryConfiguration
     * @param ColumnConfiguration[] $columnConfiguration
     * @return mixed
     */
    public function prepareForProcessing(QueryConfiguration $queryConfiguration, array $columnConfiguration)
    {
        $this->queryConfiguration = $queryConfiguration;
        $this->columnConfiguration = $columnConfiguration;

        // compile the query first
        $this->compileQuery();

        // sort
        $this->sortQuery();
    }

    /**
     * This method should process all configurations and prepare the underlying data for the view. It will arrange the
     * data and provide the results in a DTData object.
     * It will be called after {@link #prepareForProcessing} has been called and needs to return the processed data in
     * a DTData object so the Composer can further handle the data.
     *
     * @return ResponseData The processed data
     *
     */
    public function process()
    {
        // check if the query configuration is set
        if (is_null($this->queryConfiguration) || empty($this->columnConfiguration)) {
            throw new \InvalidArgumentException("Provider was not configured. Did you call prepareForProcessing first?");
        }

        // limit
        $this->queryBeforeLimits = clone $this->query;
        $this->limitQuery();

        // # of items in filtered & ordered data set
        $dataCount = $this->queryBeforeLimits->count();

        // the data for the response
        $columns = $this->compileColumnNames();
        $response = new Collection($this->query->get($columns));

        // slice the result into the right size
        return new ResponseData(
            $response,
            $this->getTotalNumberOfRows(),
            $dataCount
        );
    }

    /**
     * Get the total number of rows for the original query.
     * @return int
     */
    private function getTotalNumberOfRows()
    {
        return $this->originalQuery->count();
    }

    /**
     * Will compile the collection into the final collection where operations like search and order can be applied.
     *
     * @return QueryBuilder
     * @throws DatatableException
     */
    private function compileQuery()
    {
        if ($this->queryConfiguration->isGlobalSearch()) {
            $this->compileGlobalQuery();
        } elseif ($this->queryConfiguration->isColumnSearch()) {
            $this->compileColumnQuery();
        }
    }

    /**
     * When a global (single) search has been done against data in the datatable.
     *
     * @return QueryBuilder
     * @throws DatatableException
     */
    private function compileGlobalQuery()
    {
        foreach ($this->columnConfiguration as $i => $col) {
            $this->createQueryForColumn($col, $this->queryConfiguration->searchValue());
        }
    }

    /**
     * When a global query is being performed (ie, a query against a single column)
     *
     * @return QueryBuilder
     * @throws DatatableException
     */
    private function compileColumnQuery()
    {
        $searchColumns = $this->queryConfiguration->searchColumns();

        foreach ($searchColumns as $i => $col) {
            $column = $this->getColumnFromName($col->columnName());

            if (!isset($column))
                continue;

            $this->createQueryForColumn($column, $col->searchValue());
        }
    }

    /**
     * Create the query w/ QueryBuilder
     * @param ColumnConfiguration $column
     * @param $searchValue
     * @return QueryBuilder
     * @throws DatatableException
     */
    private function createQueryForColumn(ColumnConfiguration $column, $searchValue)
    {
        $searchType = $column->getSearch();

        if ($searchType == DefaultSearchable::NONE()) {
            // Don't do anything, this is not a searchable field
            return $this->query;
        } elseif ($searchType == DefaultSearchable::NORMAL()) {
            $this->query->orWhere($column->getName(), 'LIKE', '%' . $searchValue . '%');
        } elseif ($searchType == DefaultSearchable::REGEX()) {
            $this->query->orWhere($column->getName(), 'REGEXP', $searchValue);
        } else {
            throw new DatatableException('An unsupported DefaultSearchable was provided.');
        }

        return $this->query;
    }

    /**
     * Get the requested column configuration from the name of a column
     * @param string $name
     * @return ColumnConfiguration
     * @throws DatatableException when a column is not found
     */
    private function getColumnFromName($name)
    {
        foreach ($this->columnConfiguration as $i => $col) {
            if ($col->getName() == $name) {
                return $col;
            }
        }

        // This exception should never happen. If it does, something is
        // wrong w/ the relationship between searchable columns and the
        // configuration.
        throw new DatatableException("A requested column was not found in the columnConfiguration.");
    }

    /**
     * Get a list of all the column names for the SELECT query.
     */
    private function compileColumnNames()
    {
        $columns = [];
        foreach($this->columnConfiguration as $column) {
            $columns[] = $column->getName();
        }

        return $columns;
    }

    /**
     * Will sort the query based on the given datatable query configuration.
     */
    private function sortQuery()
    {
        if ($this->queryConfiguration->hasOrderColumn()) {
            $orderColumns = $this->queryConfiguration->orderColumns();

            foreach($orderColumns as $order) {
                $this->query->orderBy($order->columnName(), $order->isDescending() ? 'desc' : 'asc');
            }
        }
    }

    /**
     * Will limit a query based on the start and length given
     */
    private function limitQuery()
    {
        $this->query->skip($this->queryConfiguration->start());
        $this->query->limit($this->queryConfiguration->length());
    }
}


text:
import React, { Component } from 'react'
import { Card, CardActions, CardHeader, CardText, CardTitle } from 'material-ui/Card'
import FlatButton from 'material-ui/FlatButton'
import { List } from 'material-ui/List'
import Dialog from 'material-ui/Dialog'
import ChatIcon from 'material-ui/svg-icons/communication/chat-bubble-outline'
import CommentIcon from 'material-ui/svg-icons/communication/comment'
import Badge from 'material-ui/Badge'
import './PushableCardHeader.css'

import Linkify from 'react-linkify'
import Timestamp from 'react-timestamp'

import firebase from 'firebase'

import CommentRef from './CommentRef'
import CommentForm from './CommentForm'

import LocalizedStrings from 'react-localization'

let strings = new LocalizedStrings({
 en:{
   comment:"comment",
   writeComment:"write comment",
   cansel:"Cansel",
 },
 ja: {
   comment:"コメント",
   writeComment:"コメント投稿",
   cansel:"キャンセル",
 }
});

class PostRef4Mypage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open:false,
      postOpen:false,
    };
  }

  handleClose = () => {
    this.setState({open: false,postOpen:false});
  }

  onCommentFncOpen = () => {
    this.setState({open:true})
  }

  handleCommentSubmit = (val) =>{
    this.writeNewComment(val)
  }

  handlePostOpen = () => {
    this.setState({postOpen:true})
  }

  writeNewComment(val){
    const self = this
    const postId = this.props.post.postId
    var newCommentKey = firebase.database().ref('/comments/').push().key
    var commentData = {
      author: self.props.author,
      uid: self.props.uid,
      body: val,
      commentId: newCommentKey,
      profile_image:self.props.profile_image,
    }

    firebase.database().ref('posts/' + postId + '/postComment').once("value").then(function(snapshot) {
      const commentCount = snapshot.val()
      var updates = {}
      updates['posts/' + postId + '/postComment/comments/' + newCommentKey]= true
      updates['posts/' + postId + '/postComment/commentCount']= commentCount.commentCount+1
      updates['comments/' + newCommentKey]= commentData
      return  firebase.database().ref().update(updates)
    })
    this.setState({open:false})
  }

  render(){
    const actions = [<FlatButton  label={strings.cansel}
                                  primary={true}
                                  onClick={this.handleClose} />,  ]

    return(
      <Card  style={{
              width:'500px',
              display: 'inline-block',
              margin:'auto',
              marginRight:'10px',
              verticalAlign: 'top'
            }} >
        <CardTitle  title={  <Badge
                              badgeContent={this.props.post.postStar.starCount}
                              primary={true}
                              badgeStyle={{fontSize:5,top:12,right:12}} >
                              {this.props.post.title}
                            </Badge>  }
                    subtitle={
                      <Timestamp time={this.props.post.timestamp/1000} format='full' includeDay/>
                    }
                    titleStyle={{
                      paddingTop:'0',
                      marginTop:'-20'
                    }}/>

          <CardText onClick={this.handlePostOpen} className="CardText">
            <Linkify>{this.props.post.body}</Linkify>

          </CardText>
          <CardActions>
            <FlatButton
              secondary
              label={strings.comment}
              labelPosition="before"
              icon={<CommentIcon/>}
              onClick={this.onCommentFncOpen} />
          </CardActions>

          <CardHeader showExpandableButton
                      title={
                        <Badge  badgeContent={this.props.post.postComment.commentCount}
                                primary={true}
                                badgeStyle={{fontSize:1,top: 12, right: 12}} >
                          <ChatIcon />
                        </Badge> }
                      style={{
                          paddingTop:'0',
                          marginTop:'-10',
                          marginBottom:'-25'
                      }}/>
          <List expandable>
            <CommentRef postId={this.props.post.postId} uid={this.props.post.uid}/>
          </List>
        <Dialog title={strings.writeComment}
                actions={actions}
                modal={false}
                open={this.state.open}
                onRequestClose={this.handleClose}
                autoScrollBodyContent={true} >
          <CommentForm onSubmit={this.handleCommentSubmit.bind(this)}/>
        </Dialog>

        <Dialog title={this.props.post.title}
                actions={actions}
                modal={false}
                open={this.state.postOpen}
                onRequestClose={this.handleClose}
                autoScrollBodyContent={true} >

            <Linkify>  {this.props.post.body} </Linkify>

        </Dialog>
      </Card>
    )
  }
}
export default PostRef4Mypage

redpajama_set_name: RedPajamaGithub


text:
/**
 * @cond (NODOX)
 * @defgroup app_mailbox_internal Auxiliary internal types declarations
 * @{
 * @ingroup app_mailbox
 * @internal
 *
 * @brief Module for internal usage inside the library only
 *
 * Some definitions must be included in the header file because
 * of the way the library is set up. In this way, the are accessible to the user.
 * However, any functions and variables defined here may change at any time
 * without a warning, so you should not access them directly.
 */

#ifndef APP_MAILBOX_LOCAL_H__
#define APP_MAILBOX_LOCAL_H__

#ifdef __cplusplus
extern "C" {
#endif

 /**
 * @brief Mailbox handle used for managing a mailbox queue.
 */
typedef struct
{
    uint8_t                      r_idx;    /**< Read index for the mailbox queue. */
    uint8_t                      w_idx;    /**< Write index for the mailbox queue. */
    uint8_t                      len;      /**< Number of elements currently in the mailbox queue. */
    app_mailbox_overflow_mode_t  mode;     /**< Mode of overflow handling. */
} app_mailbox_cb_t;

#ifdef __cplusplus
}
#endif

#endif // APP_MAILBOX_LOCAL_H__

/** @}
 * @endcond
 */


text:
package tools;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Interface de normalisation des mots
 * @author xtannier
 *
 */
public interface Normalizer {
	/**
	 * Renvoie la liste d'unités lexicales contenus dans le fichier
	 * spécifié, en appliquant une normalisation. Equivaut à {@code normalize(file, false)}.
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public ArrayList<String> normalize(File file) throws IOException;

	/**
	 * Renvoie la liste d'unités lexicales contenus dans le texte
	 * spécifié, en appliquant une normalisation. Equivaut à {@code normalize(text, false)}.
	 * @param text
	 * @return
	 */
	public ArrayList<String> normalize(String text);

	/**
	 * Renvoie la liste d'unités lexicales contenus dans le fichier
	 * spécifié, en appliquant une normalisation. Equivaut à {@code normalize(text, false)}.
	 * avec suppression ou pas de mots vides
	 * @param fileName
	 * @param removeStopWords
	 * @return
	 * @throws IOException
	 */
	public ArrayList<String> normalize(String fileName, boolean removeStopWords)
			throws IOException;
}


text:
require 'thor'

module Nrcmd
  class Apps::Hosts < Thor
    namespace 'apps hosts'

    Nrcmd.autoload :Metrics,      'nrcmd/apps/hosts/metrics'
    register(Metrics, 'metrics', 'metrics <sub-command>', 'sub-commands for Application Hosts Metrics services')

    URL = 'https://api.newrelic.com/v2'

    desc "list <app_id>", "list your hosts associated with the given app_id."
    long_desc <<-LONGDESC
    This API endpoint returns a paginated list of hosts associated with the given application.
    Application hosts can be filtered by hostname, or the list of application host IDs.

    with --filter, -f option, filtering applications by `hostname`, `ids`.

    https://rpm.newrelic.com/api/explore/application_hosts/list
    LONGDESC
    option :filter, :type => :string, :aliases => '-f', :default => ""
    def list(app_id)
      uri = URL + "/applications/#{app_id}/hosts.json"
      filter_param = ""
      options["filter"].gsub(" ", "").split(',').each do |filter|
        fkv = filter.split('=')
        filter_param << "filter[#{fkv[0]}]=#{fkv[1]}&"
      end
      res = Nrcmd::Http.get(uri, {}, filter_param)
      result = JSON.parse(res.body)
      print JSON[ result["application_hosts"] ]
    end

    desc "show <app_id> <host_id>", "show a single application host, identified by its ID."
    long_desc <<-LONGDESC
    https://rpm.newrelic.com/api/explore/application_hosts/show
    LONGDESC
    def show(app_id, host_id)
      uri = URL + "/applications/#{app_id}/hosts/#{host_id}.json"
      res = Nrcmd::Http.get(uri)
      result = JSON.parse(res.body)
      print JSON[ result["application_host"]]
    end
    def self.banner(task, namespace = false, subcommand = true)
      super
    end
  end
end


text:
#ifndef POLYGRAPH__KERBEROS_XACT_H
#define POLYGRAPH__KERBEROS_XACT_H

#include "xstd/FileScanner.h"
#include "xstd/Kerberos.h"
#include "xstd/NetAddr.h"
#include "xstd/Socket.h"
#include "runtime/IOBuf.h"

class Client;

namespace Kerberos {

class Mgr;

class Xact: public FileScanUser {
	public:
		Xact();
		virtual ~Xact();

		virtual const ::String &description() const = 0;
		virtual void reset();
		void exec(const NetAddr &aKdcAddr);

		bool needRetry() const { return doRetry; }
		//bool done() const { return theState == stDone; }
		int tryCount() const { return theTryCount; }

		virtual void noteReadReady(int fd);
		virtual void noteWriteReady(int fd);
		virtual void noteTimeout(int fd, Time tout);
		const NetAddr &kdcAddr() const { return theKdcAddr; }

		int sessionId; // Mgr tag to ignore late transactions

	protected:
		const Client &client() const;
		const Mgr &owner() const { Must(theOwner); return *theOwner; }
		Mgr &owner() { Must(theOwner); return *theOwner; }

		bool configure(Mgr &anOwner);
		virtual void finish(const bool isSuccessful = false);
		void finishAndRetry() { doRetry = true; finish(); }
		int logCat() const;
		void reportError(const char *action, const ErrorCode krbError = 0) const;
		void reportError(const ::Error polyErr, const char *action, const ErrorCode krbError = 0) const;
		virtual ErrorCode step(Data &in, Data &out) = 0;

		// Polygraph error used by kids when detailing lower level errors
		virtual ::Error polyError() const = 0;

		bool usingTcp; // whether we are or should be using a TCP connection

	private:
		bool openSocket();
		bool reOpenSocket(ErrorCode e);
		void closeSocket();
		void startIO(const IODir dir);
		void doStep();
		void reportErrorAndFinish(const char *action, const ::Error sysError);
		void reportErrorAndFinish(const ::Error polyError);
		void reportErrorAndFinish(const char *action, const ErrorCode krbError);
		void outAppend(IOBuf* &out ,const char* buf, Size sz);

	private:
		Mgr *theOwner;
		CCache *theCCache;
		NetAddr theKdcAddr;
		Socket theSock;
		FileScanReserv theReserv;
		IOBuf *theIn;
		IOBuf *theOut;
		IOBuf *theLastRequest;
		int theTryCount;
		bool doRetry;
		bool usingPconn; // sent a request on a previously used TCP connection
};

}; // namespace Kerberos

#endif


text:
class Velero < Formula
  desc "Disaster recovery for Kubernetes resources and persistent volumes"
  homepage "https://github.com/heptio/velero"
  url "https://github.com/heptio/velero/archive/v1.1.0.tar.gz"
  sha256 "9313f059c9c973052fba4b307e652b1067b8542302277af1f610415e79cb32c0"

  bottle do
    cellar :any_skip_relocation
    sha256 "e4684ab704c35f8ee7f9843f2f106f693f87d7671864f9a20859c392b844adc7" => :catalina
    sha256 "713560c7ada1422f49cf04e4146e3afa483e5f00b50a67fcc4c7180e7018c394" => :mojave
    sha256 "74e077b085c10713f22c09fdc592ef6dce9e13a6a87a3d83b02ca9f66f1557c1" => :high_sierra
    sha256 "36bce9094dac8e3dd1ed7d108dea0237f90f101ff158ae7279a53907258e5ed0" => :sierra
  end

  depends_on "go" => :build

  def install
    ENV["GOPATH"] = buildpath
    dir = buildpath/"src/github.com/heptio/velero"
    dir.install buildpath.children - [buildpath/".brew_home"]

    cd dir do
      system "go", "build", "-o", bin/"velero", "-installsuffix", "static",
                   "-ldflags",
                   "-X github.com/heptio/velero/pkg/buildinfo.Version=v#{version}",
                   "./cmd/velero"

      # Install bash completion
      output = Utils.popen_read("#{bin}/velero completion bash")
      (bash_completion/"velero").write output

      # Install zsh completion
      output = Utils.popen_read("#{bin}/velero completion zsh")
      (zsh_completion/"_velero").write output

      prefix.install_metafiles
    end
  end

  test do
    output = shell_output("#{bin}/velero 2>&1")
    assert_match "Velero is a tool for managing disaster recovery", output
    assert_match "Version: v#{version}", shell_output("#{bin}/velero version --client-only 2>&1")
    system bin/"velero", "client", "config", "set", "TEST=value"
    assert_match "value", shell_output("#{bin}/velero client config get 2>&1")
  end
end


text:
$:.unshift File.dirname(__FILE__)+"/../lib"

require 'test/unit'
require 'rgen/ecore/ecore'
require 'rgen/model_builder/builder_context'

class BuilderContextTest < Test::Unit::TestCase

  module BuilderExtension1
    module PackageA
      def inPackAExt
        3
      end
      module PackageB
        def inPackBExt
          5
        end
      end
    end
  end

  class BuilderContext
    def inBuilderContext
      7
    end
  end

  def test_extensionContainerFactory
    aboveRoot = RGen::ECore::EPackage.new(:name => "AboveRoot")
    root = RGen::ECore::EPackage.new(:name => "Root", :eSuperPackage => aboveRoot)
    packageA = RGen::ECore::EPackage.new(:name => "PackageA", :eSuperPackage => root)
    packageB = RGen::ECore::EPackage.new(:name => "PackageB", :eSuperPackage => packageA)
    packageC = RGen::ECore::EPackage.new(:name => "PackageBC", :eSuperPackage => packageA)

    factory = RGen::ModelBuilder::BuilderContext::ExtensionContainerFactory.new(root, BuilderExtension1, BuilderContext.new)

    assert_equal BuilderExtension1::PackageA, factory.moduleForPackage(packageA)

    packAExt = factory.extensionContainer(packageA)
    assert packAExt.respond_to?(:inPackAExt)
    assert !packAExt.respond_to?(:inPackBExt)
    assert_equal 3, packAExt.inPackAExt
    assert_equal 7, packAExt.inBuilderContext

    assert_equal BuilderExtension1::PackageA::PackageB, factory.moduleForPackage(packageB)

    packBExt = factory.extensionContainer(packageB)
    assert !packBExt.respond_to?(:inPackAExt)
    assert packBExt.respond_to?(:inPackBExt)
    assert_equal 5, packBExt.inPackBExt
    assert_equal 7, packBExt.inBuilderContext

    assert_raise RuntimeError do
      # aboveRoot is not contained within root
      assert_nil factory.moduleForPackage(aboveRoot)
    end
    assert_nil factory.moduleForPackage(packageC)
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<gradient xmlns:android="http://schemas.android.com/apk/res/android"
          android:endColor="#00263238"
          android:endX="108"
          android:endY="108"
          android:startColor="#33263238"
          android:startX="54"
          android:startY="54"
          android:type="linear"/>


text:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;

namespace SharpLib.Texter.Rendering
{
    internal sealed class TextLayer : Layer
    {
        #region Поля

        private readonly List<VisualLineDrawingVisual> visuals = new List<VisualLineDrawingVisual>();

        internal int index;

        #endregion

        #region Свойства

        protected override int VisualChildrenCount
        {
            get { return visuals.Count; }
        }

        #endregion

        #region Конструктор

        public TextLayer(TextView textView)
            : base(textView, KnownLayer.Text)
        {
        }

        #endregion

        #region Методы

        internal void SetVisualLines(ICollection<VisualLine> visualLines)
        {
            foreach (VisualLineDrawingVisual v in visuals)
            {
                if (v.VisualLine.IsDisposed)
                {
                    RemoveVisualChild(v);
                }
            }
            visuals.Clear();
            foreach (VisualLine newLine in visualLines)
            {
                var v = newLine.Render();
                if (!v.IsAdded)
                {
                    AddVisualChild(v);
                    v.IsAdded = true;
                }
                visuals.Add(v);
            }
            InvalidateArrange();
        }

        protected override Visual GetVisualChild(int index)
        {
            return visuals[index];
        }

        protected override void ArrangeCore(Rect finalRect)
        {
            textView.ArrangeTextLayer(visuals);
        }

        #endregion
    }
}


text:
using Microsoft.AspNetCore.Http;

namespace Bossr.Api.Services
{
    public interface IUserAccessValidator
    {
        bool IsCurrentUserAllowedToAccessUserResources(int resourceUserId);
    }

    public class UserAccessValidator : IUserAccessValidator
    {
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IUserIdentityReader userIdentityReader;

        public UserAccessValidator(IHttpContextAccessor httpContextAccessor, IUserIdentityReader userIdentityReader)
        {
            this.httpContextAccessor = httpContextAccessor;
            this.userIdentityReader = userIdentityReader;
        }

        public bool IsCurrentUserAllowedToAccessUserResources(int resourceUserId)
        {
            var currentUser = httpContextAccessor.HttpContext.User;
            var currentUserId = userIdentityReader.GetUserId(currentUser);

            return currentUserId == resourceUserId;
        }
    }
}


text:
'use strict'

const tap = require('tap')
const ActiveDirectory = require('../index')
const config = require('./config')
const serverFactory = require('./mockServer')
const settings = require('./settings').findUser

tap.beforeEach((done, t) => {
  serverFactory(function (err, server) {
    if (err) return done(err)
    const connectionConfig = config(server.port)
    t.context.ad = new ActiveDirectory(connectionConfig)
    t.context.server = server
    done()
  })
})

tap.afterEach((done, t) => {
  if (t.context.server) t.context.server.close()
  done()
})

tap.test('#findUser()', t => {
  ['userPrincipalName', 'sAMAccountName', 'dn'].forEach((userAttribute) => {
    const username = settings.username[userAttribute]
    t.test(`should return user for (${userAttribute}) ${username}`, t => {
      t.context.ad.findUser(username, function (err, user) {
        t.error(err)
        t.ok(user)
        t.end()
      })
    })
  })

  t.test('should return undefined if the username doesn\'t exist', t => {
    t.context.ad.findUser('!!!NON-EXISTENT USER!!!', function (err, user) {
      t.error(err)
      t.is(user, undefined)
      t.end()
    })
  })

  t.test('should return default user attributes when not specified', t => {
    const defaultAttributes = ActiveDirectory.defaultAttributes.user
    t.context.ad.findUser(settings.username.userPrincipalName, function (err, user) {
      t.error(err)
      t.ok(user)

      const attributes = Object.keys(user)
      t.deepEqual(attributes, defaultAttributes)

      t.end()
    })
  })

  t.end()
})

tap.test('#findUser(opts)', t => {
  t.test('should use the custom opts.filter if provided', t => {
    const opts = {
      filter: settings.opts.custom
    }
    const username = settings.username.userPrincipalName
    t.context.ad.findUser(opts, username, function (err, user) {
      t.error(err)
      t.ok(user)
      t.notEqual(user.userPrincipalName, username)
      t.end()
    })
  })

  t.test('should include groups/membership if opts.includeMembership[] = [ \'all\' ]', t => {
    const opts = {
      includeMembership: ['all']
    }
    const username = settings.username.userPrincipalName
    t.context.ad.findUser(opts, username, function (err, user) {
      t.error(err)
      t.ok(user)
      t.true(user.groups.length >= settings.groups.length)

      const cns = user.groups.map((g) => g.cn)
      settings.groups.forEach(group => t.true(cns.includes(group)))

      t.end()
    })
  })

  t.test('should include groups/membership if opts.includeMembership[] = [ \'user\' ]', t => {
    const opts = {
      includeMembership: ['user']
    }
    const username = settings.username.userPrincipalName
    t.context.ad.findUser(opts, username, function (err, user) {
      t.error(err)
      t.ok(user)
      t.true(user.groups.length >= settings.groups.length)

      const cns = user.groups.map((g) => g.cn)
      settings.groups.forEach(group => t.true(cns.includes(group)))

      t.end()
    })
  })

  t.test('should return expected groups/membership if opts.includeMembership enabled', t => {
    const opts = {
      includeMembership: ['user', 'all']
    }
    const username = settings.username.userPrincipalName
    t.context.ad.findUser(opts, username, function (err, user) {
      t.error(err)
      t.ok(user)
      t.true(user.groups.length >= settings.groups.length)

      const cns = user.groups.map((g) => g.cn)
      settings.groups.forEach(group => t.true(cns.includes(group)))

      t.end()
    })
  })

  t.test('should return only the first user if more than one result returned', t => {
    const opts = {
      filter: settings.opts.multipleFilter
    }
    t.context.ad.findUser(opts, '' /* ignored since we're setting our own filter */, function (err, user) {
      t.error(err)
      t.ok(user)
      t.false(Array.isArray(user))

      t.end()
    })
  })

  t.test('should return only requested attributes', t => {
    const opts = {
      attributes: ['cn']
    }
    const username = settings.username.userPrincipalName
    t.context.ad.findUser(opts, username, function (err, user) {
      t.error(err)
      t.ok(user)

      const keys = Object.keys(user)
      t.true(keys.length <= opts.attributes.length)
      keys.forEach(key => t.true(opts.attributes.includes(key)))

      t.end()
    })
  })

  // https://github.com/jsumners/node-activedirectory/issues/26
  t.test('should return unique users', t => {
    let count = 0
    // The bug was triggered by using a common options object. The method
    // was creating a pointer to this object and then not updating its
    // internal reference on subsequent calls (because it was already defined).
    const opts = {}
    function findUser (user, cb) {
      t.context.ad.findUser(opts, user, function (err, user) {
        count += 1
        t.error(err)
        cb(user)
      })
    }

    findUser('username', (result) => {
      t.equal(result.sAMAccountName, 'username')
      if (count === 2) t.end()
    })

    findUser('username1', (result) => {
      t.equal(result.sAMAccountName, 'username1')
      if (count === 2) t.end()
    })
  })

  t.end()
})


text:
/* eslint-disable func-names */
import { expect } from 'chai';

import EasyPost from '../../src/easypost';
import NotImplementedError from '../../src/errors/not_implemented';
import Fixture from '../helpers/fixture';
import * as setupPolly from '../helpers/setup_polly';

describe('Event Resource', function () {
  setupPolly.startPolly();

  before(function () {
    this.easypost = new EasyPost(process.env.EASYPOST_TEST_API_KEY);
  });

  beforeEach(function () {
    const { server } = this.polly;
    setupPolly.setupCassette(server);
  });

  it('retrieves an event', async function () {
    const events = await this.easypost.Event.all({
      page_size: Fixture.pageSize(),
    });

    const retrievedEvent = await this.easypost.Event.retrieve(events.events[0].id);

    expect(retrievedEvent).to.be.an.instanceOf(this.easypost.Event);
    expect(retrievedEvent.id).to.match(/^evt_/);
  });

  it('retrieves all events', async function () {
    const events = await this.easypost.Event.all({
      page_size: Fixture.pageSize(),
    });

    const eventsArray = events.events;

    expect(eventsArray.length).to.be.lessThanOrEqual(Fixture.pageSize());
    expect(events.has_more).to.exist;
    eventsArray.forEach((event) => {
      expect(event).to.be.an.instanceOf(this.easypost.Event);
    });
  });

  it('throws on save', function () {
    const event = new this.easypost.Event({ id: 1 });

    return event.save().catch((err) => {
      expect(err).to.be.an.instanceOf(NotImplementedError);
    });
  });

  it('throws on delete', function () {
    const event = new this.easypost.Event({ id: 1 });

    return event.delete().catch((err) => {
      expect(err).to.be.an.instanceOf(NotImplementedError);
    });
  });
});


text:
#ifndef __ALT_CACHE_H__
#define __ALT_CACHE_H__

#include "hwlib.h"

#ifdef __cplusplus
extern "C"
{
#endif

/*!
 * \addtogroup CACHE_MGR Cache Management API
 *
 * This module defines the cache management API for enabling and disabling L1
 * data cache, L1 instruction cache, L1 dynamic branch prediction caches, L1
 * TLB cache, and L2 cache in the SoC. As well, many it allows users to perform
 * cache maintenance operations on these caches. This includes the following
 * operations:
 *  * Invalidate: Marks the cache line as being invalid, freeing up the space
 *    to cache other data. All APIs which enable caches invalidates the memory
 *    before being enabling the cache.
 *  * Clean: If the cache line is dirty, it synchronizes the cache line data
 *    with the upper level memory system and marks that line as clean. All APIs
 *    which disable caches cleans the memory before disabling the cache.
 *  * Purge: A term used in this API as a short form for clean and invalidate.
 *    This operation cleans and invalidates a cache line in that order, as a
 *    single command to the cache controller.
 *
 * The following reference materials were used in the design of this API:
 *  * ARM® Architecture Reference Manual, ARMv7-A and ARMv7-R edition
 *  * Cortex™-A9 Technical Reference Manual
 *  * Cortex™-A9 MPCore Technical Reference Manual
 *  * CoreLink™ Level 2 Cache Controller L2C-310 Technical Reference
 *    Manual
 *
 * @{
 */

/*!
 * \addtogroup CACHE_SYS System Level Cache Management API
 *
 * This API group provides cache maintenance operations which affects multiple
 * cache levels.
 *
 * The enable and disable functions enables and disables all caches in the
 * system respectively. For caches shared by the CPU core(s), particularly the
 * L2 cache, once that cache is enabled or disabled it will not be invalidated
 * or cleaned again respectively. This allows the safe system-wide enable and
 * disable to be used in single-core and multi-core scenarios.
 *
 * For cache maintenance operations, this API implements the procedures
 * outlined in the L2C-310 Technical Reference Manual, section 3.3.10,
 * subsection "System cache maintenance considerations". This allows for a
 * convenient way to invalidate, clean, or clean and invalidate cache data from
 * the L1 to L2 to L3 while avoiding any potential race conditions in
 * mutli-core or multi-master scenarios. It assumes that the L1 and L2 cache is
 * set in "non-exclusive" mode. This means a segment of data can reside in both
 * the L1 and L2 simultaneously. This is the default mode for caches in the
 * system.
 *
 * The current implementation of the system cache APIs assumes that the MMU is
 * configured with a flat memory mapping or that every virtual address matches
 * perfectly with the physical address. This restriction may be lifted in a
 * future release of the cache API implementation.
 *
 * @{
 */

/*!
 * Enables support for a non-flat virtual memory. A flat virtual memory is
 * where every virtual address matches exactly to the physical address, making
 * the virtual to physical translation trivial. Adding support for non-flat
 * adds some overhead for the VA to PA translation and error detection.
 *
 * To enable non-flat virtual memory support, defined
 * ALT_CACHE_SUPPORT_NON_FLAT_VIRTUAL_MEMORY=1 in your Makefile when compiling
 * HWLibs.
 */
#ifndef ALT_CACHE_SUPPORT_NON_FLAT_VIRTUAL_MEMORY
#define ALT_CACHE_SUPPORT_NON_FLAT_VIRTUAL_MEMORY (0)
#endif

/*!
 * This is the system wide cache line size, given in bytes.
 */
#define ALT_CACHE_LINE_SIZE         32

/*!
 * Enables all caches and features which improve reliability and speed on all
 * cache controllers visible to the current CPU core. This includes parity
 * error detection. Cache controllers visible to multiple CPU cores, for
 * example the L2, will first be checked to be disabled before being enabled.
 * All necessary cache maintenance operations will be done automatically.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_system_enable(void);

/*!
 * Disables all cache controllers visible to the current CPU core. Cache
 * controllers visible to multiple CPU cores, for example the L2, will first
 * be checked to be enabled before being disabled. All necessary cache
 * maintenance operations will be done automatically.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_system_disable(void);

/*!
 * Invalidates the specified contents of all cache levels visible to the
 * current CPU core for the given memory segment.
 *
 * The memory segment address and length specified must align to the
 * characteristics of the cache line. This means the address and length must be
 * multiples of the cache line size. To determine the cache line size, use the
 * \b ALT_CACHE_LINE_SIZE macro.
 *
 * The following pseudocode outlines the operations carried out by this
 * function:
 *  -# L2 invalidate address(es)
 *  -# L2 cache sync
 *  -# L1 invalidate address(es)
 *  -# DSB instruction
 *
 * The current implementation of the system cache APIs assumes that the MMU is
 * configured with a flat memory mapping or that every virtual address matches
 * perfectly with the physical address. This restriction may be lifted in a
 * future release of the cache API implementation.
 *
 * \param       vaddress
 *              The virtual address of the memory segment to be invalidated.
 *
 * \param       length
 *              The length of the memory segment to be invalidated.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 * \retval      ALT_E_BAD_ARG   The memory segment is invalid.
 * \retval      ALT_E_TMO       The memory operation timed out.
 */
ALT_STATUS_CODE alt_cache_system_invalidate(void * vaddress, size_t length);

/*!
 * Cleans the specified contents of all cache levels visible to the current
 * CPU core for the given memory segment.
 *
 * The memory segment address and length specified must align to the
 * characteristics of the cache line. This means the address and length must be
 * multiples of the cache line size. To determine the cache line size, use the
 * \b ALT_CACHE_LINE_SIZE macro.
 *
 * The following pseudocode outlines the operations carried out by this
 * function:
 *  -# L1 clean address(es)
 *  -# DSB instruction
 *  -# L2 clean address(es)
 *  -# L2 cache sync
 *
 * The current implementation of the system cache APIs assumes that the MMU is
 * configured with a flat memory mapping or that every virtual address matches
 * perfectly with the physical address. This restriction may be lifted in a
 * future release of the cache API implementation.
 *
 * \param       vaddress
 *              The virtual address of the memory segment to be cleaned.
 *
 * \param       length
 *              The length of the memory segment to be cleaned.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 * \retval      ALT_E_BAD_ARG   The memory segment is invalid.
 * \retval      ALT_E_TMO       The memory operation timed out.
 */
ALT_STATUS_CODE alt_cache_system_clean(void * vaddress, size_t length);

/*!
 * Cleans and invalidates the specified contents of all cache levels visible
 * to the current CPU core for the given memory segment.
 *
 * The memory segment address and length specified must align to the
 * characteristics of the cache line. This means the address and length must be
 * multiples of the cache line size. To determine the cache line size, use the
 * \b ALT_CACHE_LINE_SIZE macro.
 *
 * The following pseudocode outlines the operations carried out by this
 * function:
 *  -# L1 clean address(es)
 *  -# DSB instruction
 *  -# L2 clean and invalidate address(es)
 *  -# L2 cache sync
 *  -# L1 invalidate address(es)
 *  -# DSB instruction
 *
 * The current implementation of the system cache APIs assumes that the MMU is
 * configured with a flat memory mapping or that every virtual address matches
 * perfectly with the physical address. This restriction may be lifted in a
 * future release of the cache API implementation.
 *
 * \param       vaddress
 *              The virtual address of the memory segment to be purged.
 *
 * \param       length
 *              The length of the memory segment to be purged.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 * \retval      ALT_E_BAD_ARG   The memory segment is invalid.
 * \retval      ALT_E_TMO       The memory operation timed out.
 */
ALT_STATUS_CODE alt_cache_system_purge(void * vaddress, size_t length);

/*!
 * @}
 */

/*!
 * \addtogroup CACHE_L1 L1 Cache Management API
 *
 * This API group provides functions to interact with various components of the
 * L1 cache on the SoCFPGA. This includes the following cache components:
 *  * Instruction Cache
 *  * Data Cache
 *  * Parity error detection
 *  * Dynamic branch prediction
 *  * Data prefetching
 *
 * The API within this group only affects the L1 cache on the current CPU. To
 * interact the L1 cache on another CPU, the API must be called from that other
 * CPU.
 *
 * With respect to bring-up, the L1 and L2 cache controller setups are fully
 * independent. The L2 can be setup at any time, before or after the L1 is setup.
 * \internal
 * Source: Cortex-A9 MPCore TRM, section 5.3.4 "Multiprocessor bring-up".
 * \endinternal
 *
 * @{
 */

/*!
 * Enables all L1 caches and features on the current CPU core. This includes
 * the instruction cache, data cache, parity error detection, branch target
 * address cache, global history buffer, and data prefetching. All necessary
 * maintenance tasks will be taken care of.
 *
 * This function should not be mixed with other L1 cache related functions
 * which enable or disable caches individually.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_enable_all(void);

/*!
 * Disables all L1 caches and features on the current CPU core. This includes
 * the instruction cache, data cache, parity error detection, branch target
 * address cache, global history buffer, and data prefetching. All necessary
 * maintenance tasks will be taken care of.
 *
 * This function should not be mixed with other L1 cache related functions
 * which enable or disable caches individually.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_disable_all(void);

/*!
 * Enables the L1 instruction cache on the current CPU core. If the cache is
 * already enabled, nothing is done. Otherwise the instruction cache is first
 * invalidated before being enabled.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_instruction_enable(void);

/*!
 * Disables the L1 instruction cache on the current CPU core.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_instruction_disable(void);

/*!
 * Returns \b true when the L1 instruction cache is enabled and \b false when
 * it is disabled on the current CPU core.
 *
 * \retval      true            The L1 instruction cache is enabled.
 * \retval      false           The L1 instruction cache is disabled.
 */
bool alt_cache_l1_instruction_is_enabled(void);

/*!
 * Invalidates the contents of the L1 instruction cache on the current CPU
 * core.
 *
 * Normally this is done automatically as part of
 * alt_cache_l1_instruction_enable(), but in certain circumstances it may be
 * necessary to invalidate it manually. An example of this situation is when
 * the address space is remapped and the processor executes instructions from
 * the new memory area.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_instruction_invalidate(void);

/*!
 * Enables the L1 data cache on the current CPU core.
 *
 * If the cache is already enabled nothing is done. Otherwise the data cache is
 * first invalidated before being enabled.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_data_enable(void);

/*!
 * Disables the L1 data cache on the current CPU core.
 *
 * If the cache is already disabled nothing is done. Otherwise the data cache
 * is first cleaned before being disabled.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_data_disable(void);

/*!
 * Returns \b true when the L1 data cache is enabled and \b false when it is
 * disabled on the current CPU core.
 *
 * \retval      true            The L1 data cache is enabled.
 * \retval      false           The L1 data cache is disabled.
 */
bool alt_cache_l1_data_is_enabled(void);

/*!
 * Invalidates the specified contents of the L1 data cache on the current CPU
 * core for the given memory segment.
 *
 * The memory segment address and length specified must align to the
 * characteristics of the cache line. This means the address and length must be
 * multiples of the cache line size. To determine the cache line size, use the
 * \b ALT_CACHE_LINE_SIZE macro.
 *
 * \param       vaddress
 *              The virtual address of the memory segment to be invalidated.
 *
 * \param       length
 *              The length of the memory segment to be invalidated.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 * \retval      ALT_E_BAD_ARG   The memory segment is invalid.
 */
ALT_STATUS_CODE alt_cache_l1_data_invalidate(void * vaddress, size_t length);

/*!
 * Invalidates the entire contents of the L1 data cache on the current CPU
 * core.
 *
 * Normally this is done automatically as part of alt_cache_l1_data_enable(),
 * but in certain circumstances it may be necessary to invalidate it manually.
 * An example of this situation is when the address space is remapped and the
 * processor accesses memory from the new memory area.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_data_invalidate_all(void);

/*!
 * Cleans the specified contents of the L1 data cache on the current CPU core
 * for the given memory segment.
 *
 * The memory segment address and length specified must align to the
 * characteristics of the cache line. This means the address and length must be
 * multiples of the cache line size. To determine the cache line size, use the
 * \b ALT_CACHE_LINE_SIZE macro.
 *
 * \param       vaddress
 *              The virtual address of the memory segment to be cleaned.
 *
 * \param       length
 *              The length of the memory segment to be cleaned.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 * \retval      ALT_E_BAD_ARG   The memory segment is invalid.
 */
ALT_STATUS_CODE alt_cache_l1_data_clean(void * vaddress, size_t length);

/*!
 * Cleans the entire L1 data cache for the current CPU core.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_data_clean_all(void);

/*!
 * Cleans and invalidates the specified contents of the L1 data cache on the
 * current CPU core for the given memory segment.
 *
 * The memory segment address and length specified must align to the
 * characteristics of the cache line. This means the address and length must be
 * multiples of the cache line size. To determine the cache line size, use the
 * \b ALT_CACHE_LINE_SIZE macro.
 *
 * Normally this is done automatically as part of alt_cache_l1_data_disable(),
 * but in certain circumstances it may be necessary to purged it manually.
 * An example of this situation is when the address space is remapped and the
 * processor accesses memory from the new memory area.
 *
 * \param       vaddress
 *              The virtual address of the memory segment to be purged.
 *
 * \param       length
 *              The length of the memory segment to be purged.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 * \retval      ALT_E_BAD_ARG   The memory segment is invalid.
 */
ALT_STATUS_CODE alt_cache_l1_data_purge(void * vaddress, size_t length);

/*!
 * Cleans and invalidates the entire L1 data cache for the current CPU core.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_data_purge_all(void);

/*!
 * Enables the parity error detection feature in the L1 caches on the current
 * CPU core.
 *
 * Ideally parity should be enabled before any L1 caches are enabled. If the
 * instruction, data, and / or dynamic branch predictor caches are already
 * enabled, they will first be cleaned (if needed) and disabled before parity
 * is enabled in hardware. Afterwards, the affected caches will be invalidated
 * and enabled.
 *
 * Parity and TLB interaction deserves special attention. The TLB is considered
 * to be a L1 cache but is enabled when the MMU, which is grouped in another
 * API, is enabled. Due to the system-wide influence of the MMU, it cannot be
 * disabled and enabled with impunity as the other L1 caches, which are
 * designed to operate as transparently as possible. Thus parity error
 * detection must be enabled before the L1 TLB cache, and by extension the MMU,
 * is enabled.
 *
 * For a parity error to be reported, the appropriate CPU PARITYFAIL interrupt
 * for the current CPU core must be enabled using the interrupt controller API.
 * For CPU0, ALT_INT_INTERRUPT_CPU0_PARITYFAIL is asserted if any parity error
 * is detected while the other PARITYFAIL interrupts are for parity errors in a
 * specific memory. Refer to the interrupt controller API for more details
 * about programming the interrupt controller.
 *
 * In the event of a parity error is detected, the appropriate CPU parity
 * interrupt will be raised. CPU parity interrupts are all edge triggered and
 * are cleared by acknowledging them in the interrupt controller API.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_parity_enable(void);

/*!
 * Disables parity error detection in the L1 caches.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_parity_disable(void);

/*!
 * Returns \b true when parity error detection is enabled and \b false when it
 * is disabled on the current CPU core.
 *
 * \retval      true            Parity error detection for L1 caches is
 *                              enabled.
 * \retval      false           Parity error detection for L1 caches is
 *                              disabled.
 */
bool alt_cache_l1_parity_is_enabled(void);

/*!
 * Enables the dynamic branch predictor features on the current CPU core.
 *
 * This operation enables both the Branch Target Address Cache (BTAC) and
 * the Global History Buffer (GHB). Affected caches are automatically
 * invalidated before use.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_branch_enable(void);

/*!
 * Disables the dynamic branch predictor features on the current CPU core.
 *
 * This operation disables both the Branch Target Address Cache (BTAC) and
 * the Global History Buffer (GHB).
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_branch_disable(void);

/*!
 * Returns \b true when both the dynamic predictor features are enabled and
 * \b false when they are disabled on the current CPU core.
 *
 * \retval      true            The L1 branch predictor caches are all enabled.
 * \retval      false           Some or all L1 branch predictor caches are
 *                              disabled.
 */
bool alt_cache_l1_branch_is_enabled(void);

/*!
 * Invalidates the dynamic branch predictor feature caches on the current CPU
 * core.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_branch_invalidate(void);

/*!
 * Enables the L1 cache data prefetch feature on the current CPU core.
 *
 * This allows data to be prefetched into the data cache before it is to be
 * used. For example in a loop the current iteration may want to preload the
 * data which will be used in the next teration. This is done by using the PLD
 * instructions.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_prefetch_enable(void);

/*!
 * Disables the L1 cache data prefetch feature on the current CPU core.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l1_prefetch_disable(void);

/*!
 * Returns \b true if the L1 cache data prefetch feature is enabled and
 * \b false if it is disabled on the current CPU core.
 *
 * \retval      true            The L1 data cache prefetch feature is enabled.
 * \retval      false           The L1 data cache prefetch feature is disabled.
 */
bool alt_cache_l1_prefetch_is_enabled(void);

/*!
 * @}
 */

/*!
 * \addtogroup CACHE_L2 L2 Cache Management API
 *
 * This API group provides functions to interact with various features of the
 * L2 cache on the SoCFPGA. This includes the following features:
 *  * L2 cache
 *  * Parity error detection
 *  * Data prefetching
 *  * Interrupt Management
 *
 * \internal
 * Additional features that may be implemented in the future:
 *  * Lockdown
 *  * Event counter
 * \endinternal
 *
 * The API within this group affects the L2 cache which is visible to all CPUs
 * on the system.
 *
 * With respect to bring-up, the L1 and L2 cache controller setups are fully
 * independent. The L2 can be setup at any time, before or after the L1 is setup.
 * \internal
 * Source: Cortex-A9 MPCore TRM, section 5.3.4 "Multiprocessor bring-up".
 * \endinternal
 *
 * @{
 */

/*!
 * Initializes the L2 cache controller.
 *
 * \retval      ALT_E_SUCCESS   Successful status.
 * \retval      ALT_E_ERROR     Details about error status code
 */
ALT_STATUS_CODE alt_cache_l2_init(void);

/*!
 * Uninitializes the L2 cache controller.
 *
 * \retval      ALT_E_SUCCESS   Successful status.
 * \retval      ALT_E_ERROR     Details about error status code
 */
ALT_STATUS_CODE alt_cache_l2_uninit(void);

/*!
 * Enables the L2 cache features for data and instruction prefetching.
 *
 * Prefetching can be enabled or disabled while the L2 cache is enabled.
 * \internal
 * Source: Use the Prefetch Control Register.
 * \endinternal
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l2_prefetch_enable(void);

/*!
 * Disables the L2 cache features for data and instruction prefetching.
 *
 * Prefetching can be enabled or disabled while the L2 cache is enabled.
 * \internal
 * Source: Use the Prefetch Control Register.
 * \endinternal
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l2_prefetch_disable(void);

/*!
 * Returns \b true if either L2 cache data or instruction prefetch features are
 * enabled and \b false if no prefetching features are enabled.
 *
 * \retval      true            The L2 data and instruction prefetch features
 *                              are enabled.
 * \retval      false           Some L2 data and instruction prefetch features
 *                              are disabled.
 */
bool alt_cache_l2_prefetch_is_enabled(void);

/*!
 * Enables parity error detection in the L2 cache.
 *
 * Ideally parity should be enabled before the L2 cache is enabled. If the
 * cache is already enabled, it will first be cleaned and disabled before
 * parity is enabled in hardware. Afterwards, the cache will be invalidated and
 * enabled.
 *
 * For a parity error to be reported, the ALT_CACHE_L2_INTERRUPT_PARRD and / or
 * ALT_CACHE_L2_INTERRUPT_PARRT interrupt condition(s) must be enabled. This is
 * done by calling alt_cache_l2_int_enable(). As well, the L2 cache interrupt
 * must be enabled using the interrupt controller API. Refer to the interrupt
 * controller API for more details about programming the interrupt controller.
 *
 * In the event of a parity error is detected, the appropriate L2 cache parity
 * interrupt will be raised. To clear the parity interrupt(s), the appropriate
 * L2 cache parity interrupt must be cleared by calling
 * alt_cache_l2_int_status_clear().
 *
 * For ECC support, refer to the ECC related API documentation for more
 * information.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l2_parity_enable(void);

/*!
 * Disables parity error detection in the L2 cache.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l2_parity_disable(void);

/*!
 * Returns \b true when parity error detection is enabled and \b false when it
 * is disabled.
 *
 * \retval      true            The L2 cache parity error detection feature is
 *                              enabled.
 * \retval      false           The L2 cache parity error detection feature is
 *                              disabled.
 */
bool alt_cache_l2_parity_is_enabled(void);

/*!
 * Enables the L2 cache.
 *
 * If the L2 cache is already enabled, nothing is done. Otherwise the entire
 * contents of the cache is first invalidated before being enabled.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l2_enable(void);

/*!
 * Disables the L2 cache.
 *
 * If the L2 cache is already disabled, nothing is done. Otherwise the entire
 * contents of the cache is first cleaned before being disabled.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l2_disable(void);

/*!
 * Returns \b true when the L2 cache is enabled and \b false when it is
 * disabled.
 *
 * \retval      true            The L2 cache is enabled.
 * \retval      false           The L2 cache is disabled.
 */
bool alt_cache_l2_is_enabled(void);

/*!
 * Flushes the L2 cache controller hardware buffers.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 * \retval      ALT_E_TMO       The memory operation timed out.
 */
ALT_STATUS_CODE alt_cache_l2_sync(void);

/*!
 * Invalidates the specified contents of the L2 cache for the given memory
 * segment.
 *
 * The memory segment address and length specified must align to the
 * characteristics of the cache line. This means the address and length must be
 * multiples of the cache line size. To determine the cache line size, use the
 * \b ALT_CACHE_LINE_SIZE macro.
 *
 * \param       paddress
 *              The physical address of the memory segment to be invalidated.
 *
 * \param       length
 *              The length of the memory segment to be invalidated.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 * \retval      ALT_E_BAD_ARG   The memory segment is invalid.
 * \retval      ALT_E_TMO       The memory operation timed out.
 */
ALT_STATUS_CODE alt_cache_l2_invalidate(void * paddress, size_t length);

/*!
 * Invalidates th entire contents of the L2 cache.
 *
 * Normally this is done automatically as part of alt_cache_l2_enable(), but
 * in certain circumstances it may be necessary to invalidate it manually. An
 * example of this situation is when the address space is remapped and the
 * processor accesses memory from the new memory area.

 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 * \retval      ALT_E_TMO       The memory operation timed out.
 */
ALT_STATUS_CODE alt_cache_l2_invalidate_all(void);

/*!
 * Cleans the specified contents of the L2 cache for the given memory segment.
 *
 * The memory segment address and length specified must align to the
 * characteristics of the cache line. This means the address and length must be
 * multiples of the cache line size. To determine the cache line size, use the
 * \b ALT_CACHE_LINE_SIZE macro.
 *
 * \param       paddress
 *              The physical address of the memory segment to be cleaned.
 *
 * \param       length
 *              The length of the memory segment to be cleaned.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 * \retval      ALT_E_BAD_ARG   The memory segment is invalid.
 * \retval      ALT_E_TMO       The memory operation timed out.
 */
ALT_STATUS_CODE alt_cache_l2_clean(void * paddress, size_t length);

/*!
 * Cleans the entire L2 cache. All L2 cache controller interrupts will be
 * temporarily disabled while the clean operation is in progress and restored
 * once the it is finished.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 * \retval      ALT_E_TMO       The memory operation timed out.
 */
ALT_STATUS_CODE alt_cache_l2_clean_all(void);

/*!
 * Cleans and invalidates the specified contents of the L2 cache for the
 * given memory segment.
 *
 * The memory segment address and length specified must align to the
 * characteristics of the cache line. This means the address and length must be
 * multiples of the cache line size. To determine the cache line size, use the
 * \b ALT_CACHE_LINE_SIZE macro.
 *
 * \param       paddress
 *              The physical address of the memory segment to be purged.
 *
 * \param       length
 *              The length of the memory segment to be purged.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 * \retval      ALT_E_BAD_ARG   The memory segment is invalid.
 */
ALT_STATUS_CODE alt_cache_l2_purge(void * paddress, size_t length);

/*!
 * Cleans and invalidates the entire L2 cache. All L2 cache controller
 * interrupts will be temporarily disabled while the clean and invalidate
 * operation is in progress and restored once the it is finished.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 * \retval      ALT_E_TMO       The memory operation timed out.
 */
ALT_STATUS_CODE alt_cache_l2_purge_all(void);

/*!
 * This type definition enumerates all the interrupt conditions that can be
 * generated by the L2 cache controller as register mask values.
 */
enum ALT_CACHE_L2_INTERRUPT_e
{
    /*! Decode error received on the master ports from L3. */
    ALT_CACHE_L2_INTERRUPT_DECERR = 1 << 8,

    /*! Slave error received on the master ports from L3.  */
    ALT_CACHE_L2_INTERRUPT_SLVERR = 1 << 7,

    /*! Error on the L2 data RAM read.                     */
    ALT_CACHE_L2_INTERRUPT_ERRRD  = 1 << 6,

    /*! Error on the L2 tag RAM read.                      */
    ALT_CACHE_L2_INTERRUPT_ERRRT  = 1 << 5,

    /*! Error on the L2 data RAM write.                    */
    ALT_CACHE_L2_INTERRUPT_ERRWD  = 1 << 4,

    /*! Error on the L2 tag RAM write.                     */
    ALT_CACHE_L2_INTERRUPT_ERRWT  = 1 << 3,

    /*! Parity error on the L2 data RAM read.              */
    ALT_CACHE_L2_INTERRUPT_PARRD  = 1 << 2,

    /*! Parity error on the L2 tag RAM read.               */
    ALT_CACHE_L2_INTERRUPT_PARRT  = 1 << 1,

    /*! Event counter overflow or increment.               */
    ALT_CACHE_L2_INTERRUPT_ECNTR  = 1 << 0
};
typedef enum ALT_CACHE_L2_INTERRUPT_e ALT_CACHE_L2_INTERRUPT_t;

/*!
 * Enables the L2 cache controller interrupts for the specified set of
 * condition(s).
 *
 * \param       interrupt
 *              A register mask of the selected L2 cache controller
 *              interrupting conditions.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l2_int_enable(uint32_t interrupt);

/*!
 * Disables the L2 cache controller interrupts for the specified set of
 * condition(s).
 *
 * \param       interrupt
 *              A register mask of the selected L2 cache controller
 *              interrupting conditions.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l2_int_disable(uint32_t interrupt);

/*!
 * Gets the condition(s) causing the L2 cache controller to interrupt as a
 * register mask.
 *
 * \returns     A register mask of the currently asserted and enabled
 *              conditions resulting in an interrupt being generated.
 */
uint32_t alt_cache_l2_int_status_get(void);

/*!
 * Clears the specified conditon(s) causing the L2 cache controller to
 * interrupt as a mask. Condition(s) specified which are not causing an
 * interrupt or condition(s) specified which are not enabled are ignored.
 *
 * \param       interrupt
 *              A register mask of the selected L2 cache controller
 *              interrupting conditions.
 *
 * \retval      ALT_E_SUCCESS   The operation was successful.
 * \retval      ALT_E_ERROR     The operation failed.
 */
ALT_STATUS_CODE alt_cache_l2_int_status_clear(uint32_t interrupt);

/*!
 * @}
 */

/*!
 * @}
 */

#ifdef __cplusplus
}
#endif

#endif /* __ALT_CACHE_H__ */


text:
package edu.arizona.jbv.thesis.crypto;

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.Reader;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.jorgecastle.openssl.PEMDecryptorProvider;
import org.jorgecastle.openssl.PEMEncryptedKeyPair;
import org.jorgecastle.openssl.PEMKeyPair;
import org.jorgecastle.openssl.PEMParser;
import org.jorgecastle.openssl.jcajce.JcaPEMKeyConverter;
import org.jorgecastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;

/**
 * This class is not used by the prototype, but remains in case it proves useful
 * to future versions or other developers. After further reading into RSA, it
 * does not seem useful to encrypt entire messages, but rather smaller things
 * such as keys. RSA is slower than symmetric cryptography methods. There is
 * also a length limit in that the size of the message to be encoded cannot be
 * larger than the key that is used. As such, this class as it is fails on
 * larger data, although this could easily be solved.
 *
 * @author Jorge Vergara
 *
 */
public class RSAEncryptor extends Encryptor {

	private PublicKey publicKey;
	private PrivateKey privateKey;

	public RSAEncryptor(String certFilePath, String privateKeyFilePath) {
		if (privateKeyFilePath != null) {
			try {
				Reader reader = new FileReader(privateKeyFilePath);
				PEMParser pemParser = new PEMParser(reader);
				Object object = pemParser.readObject();

				PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder()
						.build("1234".toCharArray());
				JcaPEMKeyConverter converter = new JcaPEMKeyConverter()
						.setProvider("JC");
				KeyPair kp;
				if (object instanceof PEMEncryptedKeyPair) {
					kp = converter.getKeyPair(((PEMEncryptedKeyPair) object)
							.decryptKeyPair(decProv));
				} else {
					kp = converter.getKeyPair((PEMKeyPair) object);
				}

				pemParser.close();
				privateKey = kp.getPrivate();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (certFilePath != null) {
			InputStream inStream = null;
			try {
				inStream = new FileInputStream(certFilePath);
				CertificateFactory cf = CertificateFactory.getInstance("X.509");
				X509Certificate hrsA = (X509Certificate) cf
						.generateCertificate(inStream);
				publicKey = KeyFactory.getInstance("RSA").generatePublic(
						new X509EncodedKeySpec(hrsA.getEncoded()));
				inStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	public RSAEncryptor(byte[] encryptionKey, byte[] decryptionKey) {
		try {
			if (encryptionKey != null) {
				publicKey = KeyFactory.getInstance("RSA").generatePublic(
						new X509EncodedKeySpec(encryptionKey));
			}
			if (decryptionKey != null) {
				privateKey = KeyFactory.getInstance("RSA").generatePrivate(
						(new X509EncodedKeySpec(decryptionKey)));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Object encrypt(Object o) {
		try {
			Cipher rsa;
			rsa = Cipher.getInstance("RSA");
			rsa.init(Cipher.ENCRYPT_MODE, publicKey);
			byte[] returnVal = rsa.doFinal(objectToByte(o));

			return returnVal;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public byte[] decrypt(Object o) {
		try {
			Cipher rsa;
			rsa = Cipher.getInstance("RSA");
			rsa.init(Cipher.DECRYPT_MODE, privateKey);
			byte[] unencryted = rsa.doFinal((byte[]) o);

			return unencryted;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}


text:
<title>OGRE: Ogre::SceneManager::SkyPlaneGenParameters Struct Reference - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

Class List

Class Index

Class Hierarchy

Class Members

Ogre::SceneManager::SkyPlaneGenParameters

Ogre::SceneManager::SkyPlaneGenParameters Struct Reference

#include <OgreSceneManager.h>

List of all members.

Public Attributes

Real 	skyPlaneScale

Real 	skyPlaneTiling

Real 	skyPlaneBow

int 	skyPlaneXSegments

int 	skyPlaneYSegments

Detailed Description

Definition at line 202 of file OgreSceneManager.h.

Member Data Documentation

          Real Ogre::SceneManager::SkyPlaneGenParameters::skyPlaneBow

Definition at line 206 of file OgreSceneManager.h.

          Real Ogre::SceneManager::SkyPlaneGenParameters::skyPlaneScale

Definition at line 204 of file OgreSceneManager.h.

          Real Ogre::SceneManager::SkyPlaneGenParameters::skyPlaneTiling

Definition at line 205 of file OgreSceneManager.h.

          int Ogre::SceneManager::SkyPlaneGenParameters::skyPlaneXSegments

Definition at line 207 of file OgreSceneManager.h.

          int Ogre::SceneManager::SkyPlaneGenParameters::skyPlaneYSegments

Definition at line 208 of file OgreSceneManager.h.

The documentation for this struct was generated from the following file:

OgreSceneManager.h

Copyright © 2012 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Sun Sep 2 08:19:49 2012


text:
define([
	"jquery",
	"backbone",
	"../models/CategoryModel",
	"../collections/CategoriesCollection",
	"../views/CategoryView"
], function( $, Backbone, CategoryModel, CategoriesCollection, CategoryView ) {

    // Extends Backbone.Router
    var CategoryRouter = Backbone.Router.extend( {

        // The Router constructor
        initialize: function() {

            // Instantiates a new Animal Category View
            this.animalsView = new CategoryView( { el: "#animals", collection: new CategoriesCollection( [] , { type: "animals" } ) } );

            // Instantiates a new Colors Category View
            this.colorsView = new CategoryView( { el: "#colors", collection: new CategoriesCollection( [] , { type: "colors" } ) } );

            // Instantiates a new Vehicles Category View
            this.vehiclesView = new CategoryView( { el: "#vehicles", collection: new CategoriesCollection( [] , { type: "vehicles" } ) } );

            // Tells Backbone to start watching for hashchange events
            Backbone.history.start();

        },

        // Backbone.js Routes
        routes: {

            // When there is no hash bang on the url, the home method is called
            "": "home",

            // When #category? is on the url, the category method is called
            "category?:type": "category"

        },

        // Home method
        home: function() {

            // Programatically changes to the categories page
            $.mobile.changePage( "#categories" , { reverse: false, changeHash: false } );

        },

        // Category method that passes in the type that is appended to the url hash
        category: function(type) {

            // Stores the current Category View  inside of the currentView variable
            var currentView = this[ type + "View" ];

            // If there are no collections in the current Category View
            if(!currentView.collection.length) {

                // Show's the jQuery Mobile loading icon
                $.mobile.loading( "show" );

                // Fetches the Collection of Category Models for the current Category View
                currentView.collection.fetch().done( function() {

                    // Programatically changes to the current categories page
                    $.mobile.changePage( "#" + type, { reverse: false, changeHash: false } );

                } );

            }

            // If there already collections in the current Category View
            else {

                // Programatically changes to the current categories page
                $.mobile.changePage( "#" + type, { reverse: false, changeHash: false } );

            }

        }

    } );

    // Returns the Router class
    return CategoryRouter;

} );