text:
package org.wg3.datatype;

import org.wg3.log.Logger;
import org.wg3.log.LoggerFactory;
import org.wg3.storage.Location;
import org.wg3.storage.Array2D;

/**
 *
 * A regularly spaced grid where the first dimension is latitude and the second
 * dimension is longitude. The (0,0) location is the north-west corner. In the
 * first dimension, latitude decreases (southward) and in the second dimension,
 * longitude increases (eastward).
 *
 * @author lakshman
 * @author Robert Toomey
 *
 */
public class LatLonGrid extends DataType implements Table2DView {

	private final static Logger LOG = LoggerFactory.getLogger(LatLonGrid.class);
	/**
	 * The change in lat distance per grid square
	 */
	private final float deltaLat;
	/**
	 * The change in lon distance per grid square
	 */
	private final float deltaLon;
	/**
	 * The array that stores our data
	 */
	private Array2D<Float> values;
	/** The 'thickness' in KM of the LatLonGrid plane.  Used for
	 * volumes.  Basically it's the equivalent of RadialSet's beamwidth.
	 */
	private float myThicknessKms = .10f;

	public static class LatLonGridMemento extends DataTypeMemento {

		/**
		 * The change in lat distance per grid square
		 */
		public float deltaLat;
		/**
		 * The change in lon distance per grid square
		 */
		public float deltaLon;
		/**
		 * The 2D array of data values.
		 */
		public Array2D<Float> values;
	}

	/**
	 * The query object for LatLonGrids.
	 */
	public static class LatLonGridQuery extends DataTypeQuery {

		public boolean rowInRange;
		public boolean colInRange;
		public int outRow;
		public int outCol;
	};

	public LatLonGrid(LatLonGridMemento m) {
		super(m);
		this.deltaLat = m.deltaLat;
		this.deltaLon = m.deltaLon;
		this.values = m.values;
	}

	/**
	 * All the values are initialized to zero
	 */
	//  public LatLonGrid(Location nwCorner, Date time, String typeName, float deltaLat, float deltaLon, int numLat, int numLon) {
	//     this(nwCorner, time, typeName, deltaLat, deltaLon, new Array2DfloatAsTiles(numLat, numLon, 0.0f));
	// }
	public Array2D<Float> getValues() {
		return values;
	}

	public int getNumLat() {
		return values.getX();
	}

	public int getNumLon() {
		return values.getY();
	}

	/**
	 * positive number that indicates the size of a pixel in lat-direction
	 */
	public float getDeltaLat() {
		return deltaLat;
	}

	/**
	 * positive number that indicates the size of a pixel in lon-direction
	 */
	public float getDeltaLon() {
		return deltaLon;
	}

	/**
	 * Get the value at a Location. The height is ignored and MissingData is
	 * returned for values outside
	 */
	public float getValue(Location loc) {
		//try {
		int i = (int) Math.rint((this.getLocation().getLatitude() - loc.getLatitude()) / this.deltaLat);
		int j = (int) Math.rint((loc.getLongitude() - this.getLocation().getLongitude()) / this.deltaLon);
		if ((i >= 0) && (i < values.getX())
				&& (j >= 0) && (j < values.getY())) {
			return values.get(i, j);
		}
		//	} catch (Exception e) {
		//	}
		return DataType.MissingData;
	}

	/**
	 * Can be used to set all the values of the grid at once.
	 */
	public void setValues(Array2D<Float> values2) {
		values = values2;
	}

	// Table2D implementation --------------------------------------------------------
	@Override
	public int getNumCols() {
		return (getNumLon());
	}

	@Override
	public int getNumRows() {
		return (getNumLat());
	}

	@Override
	public String getRowHeader(int row) {
		return (String.format("[%d/%d]", row, getNumLat()));
	}

	@Override
	public String getColHeader(int col) {
		return (String.format("[%d/%d]", col, getNumLon()));
	}

	@Override
	public boolean getCellValue(int row, int col, CellQuery output) {
		output.value = values.get(row, col);
		return true;
	}

	@Override
	public boolean getLocation(LocationType type, int row, int col,
			Location output) {
		if ((col >= getNumCols()) || (row >= getNumRows())) {
			LOG.warn("********* Out of bound : (" + col + "," + row + ") bounds [" + getNumCols() + "," + getNumRows());
			return false;
		}
		boolean success = false;
		Location loc = getLocation();
		double lat = loc.getLatitude();
		double lon = loc.getLongitude();
		double dLat = getDeltaLat();
		double dLon = getDeltaLon();
		double height = loc.getHeightKms() + 10.0;
		int r = row;
		int c = col;

		switch (type) {
		case TOP_LEFT: {
			output.init(lat - (dLat * r), lon + (dLon * c), height);
		}
		break;
		case TOP_RIGHT: {
			output.init(lat - (dLat * r), lon + (dLon * (c + 1)), height);
		}
		break;
		case BOTTOM_LEFT: {
			output.init(lat - (dLat * r) - dLat, lon + (dLon * c), height);
		}
		break;

		case BOTTOM_RIGHT: {
			output.init(lat - (dLat * r) - dLat, lon + (dLon * (c + 1)), height);
		}
		break;
		case CENTER:  // unused or tested
		{
			LOG.error("Calling unimplemented type in LatLonGrid.  Fix me");
		}
		break;
		default:
			break;
		}

		success = true;
		return success;

	}

	/**
	 * Get the center location of the LatLonGrid..this is used by GUI for the
	 * 'jump' function
	 *
	 * @return center of latlongrid
	 */
	public Location getCenterLocation() {
		Location center = new Location(0, 0, 0);
		getLocation(LocationType.TOP_LEFT, getNumRows() / 2, getNumCols() / 2,
				center);
		return center;
	}

	@Override
	public boolean getCell(Location input, CellQuery output) {
		LatLonGridQuery q = new LatLonGridQuery();
		q.inLocation = input;
		q.inUseHeight = false;
		queryData(q);
		//boolean withinTable = false;
		int row = q.outRow;
		int col = q.outCol;
		output.row = row;
		output.col = col;
		output.rowInRange = ((row > 0) && (row < getNumRows()));
		output.colInRange = ((col > 0) && (col < getNumRows()));
		//withinTable = output.rowInRange && output.colInRange;
		return false;
	}

	/**
	 * Not much to this query function...just pull from the grid
	 */
	public void queryData(LatLonGridQuery q) {

		boolean haveLocation = false;

		if (q.inLocation != null) {
			haveLocation = true;
		}

		// We can query by a Location only...
		if (haveLocation) {
			float v;
			final Location loc = q.inLocation;
			int i = (int) Math.rint((this.getLocation().getLatitude() - loc.getLatitude()) / this.deltaLat);
			int j = (int) Math.rint((loc.getLongitude() - this.getLocation().getLongitude()) / this.deltaLon);
			q.outRow = i; // Note we allow it out of range for clipping.  Check inRange fields
			q.outCol = j;
			q.rowInRange = ((i > 0) && (i < getNumRows()));
			q.colInRange = ((j > 0) && (j < getNumCols()));
			if(q.rowInRange && q.colInRange){
				//if ((i >= 0) && (i < values.getX())
				//	&& (j >= 0) && (j < values.getY())) {
				v = values.get(i, j);
			} else {
				v = DataType.MissingData;
			}

			if (q.inUseHeight) {

				// Thickness test of plane
				double h_diff = this.originLocation.getHeightKms() - q.inLocation.getHeightKms();
				if (Math.abs(h_diff) > myThicknessKms) {
					v = MissingData;
				}
			}
			q.outDataValue = v;
		} else {
			q.outDataValue = MissingData;
		}
	}

}


text:
include_recipe "infoblox::default"

# In forward mapping zone, PTR (pointer) record maps a domain name to the other domain name.
# In Reverse mapping zone, PTR (pointer) record maps an address to domain name.
infoblox_ptr_record "Create a ptr record" do
  name node['ptr_record']['name']
  ptrdname node['ptr_record']['ptrdname']
  extattrs node['ptr_record']['extattrs']
  comment node['ptr_record']['comment']
  disable node['ptr_record']['disable']
  action :create
end

infoblox_ptr_record "Get ptr info" do
  ipv4addr node['ptr_record']['ipv4addr']
  ptrdname node['ptr_record']['ptrdname']
  action :get_record
end

infoblox_ptr_record "Delete a ptr record" do
  name node['ptr_record']['name']
  ptrdname node['ptr_record']['ptrdname']
  action :delete
end

redpajama_set_name: RedPajamaGithub


text:
  <[stateName]>

          <span ng-show="tabNeedUpdatesStatus(TAB_ID_CONTENT)" class="oppia-tab-needs-update"
                uib-tooltip="<[needsUpdateTooltipMessage]>" tooltip-placement="top">⚠
          Content

          <span ng-show="tabNeedUpdatesStatus(TAB_ID_CUSTOMIZATION_ARGS)" class="oppia-tab-needs-update"
                uib-tooltip="<[needsUpdateTooltipMessage]>" tooltip-placement="top">⚠
          Interaction

          <span ng-show="tabNeedUpdatesStatus(TAB_ID_FEEDBACK)" class="oppia-tab-needs-update"
                uib-tooltip="<[needsUpdateTooltipMessage]>" tooltip-placement="top">⚠
          Feedback

          <span ng-show="tabNeedUpdatesStatus(TAB_ID_HINTS)" class="oppia-tab-needs-update"
                uib-tooltip="<[needsUpdateTooltipMessage]>" tooltip-placement="top">⚠
          Hints

          <span ng-show="tabNeedUpdatesStatus(TAB_ID_SOLUTION)" class="oppia-tab-needs-update"
                uib-tooltip="<[needsUpdateTooltipMessage]>" tooltip-placement="top">⚠
          Solution

Original content

          <[getEmptyContentMessage()]>

          <angular-html-bind ng-class="{'oppia-rte-editor-focused': isCopyModeActive()}"
                             ng-click="onContentClick($event)"
                             html-data="getRequiredHtml(stateContent)"
                             class="oppia-rte-editor">
          </angular-html-bind>

Preview - {{INTERACTION_SPECS[stateInteractionId].name}}

      <angular-html-bind html-data="interactionPreviewHtml" class="oppia-translation-state-content-html-data">
      </angular-html-bind>

Content

            <response-header index="$index"
                             summary="caContent.name + ': ' + getSubtitledContentSummary(caContent.content)"
                             short-summary="caContent.name + ': ' + getSubtitledContentSummary(caContent.content)"
                             is-active="$index === activeCustomizationArgContentIndex"
                             show-warning="contentIdNeedUpdates(caContent.content.getContentId())">
            </response-header>

                <[getEmptyContentMessage()]>

                <angular-html-bind ng-class="{'oppia-rte-editor-focused': isCopyModeActive()}"
                                   ng-click="onContentClick($event)"
                                   html-data="getRequiredHtml(caContent.content)"
                                   class="oppia-rte-editor">
                </angular-html-bind>

                <[getEmptyContentMessage()]>

<[caContent.content.getUnicode()]>

            <a class="oppia-rule-tab protractor-test-feedback-<[$index]>"
               ng-click="changeActiveAnswerGroupIndex($index)"
               ng-class="{'oppia-rule-tab-active': activeAnswerGroupIndex === $index}"
               ng-style="contentIdStatusColorStyle(answerGroup.outcome.feedback.getContentId())">
              <response-header index="$index"
                               summary="summarizeAnswerGroup(answerGroup, stateInteractionId, answerChoices, false)"
                               short-summary="summarizeAnswerGroup(answerGroup, stateInteractionId, answerChoices, true)"
                               is-active="$index === activeAnswerGroupIndex"
                               outcome="answerGroup.outcome"
                               num-rules="answerGroup.rules.length"
                               is-response="true"
                               show-warning="contentIdNeedUpdates(answerGroup.outcome.feedback.getContentId())"
                               navigate-to-state="navigateToState"
                               correctness-feedback-enabled="ExplorationCorrectnessFeedbackService.isEnabled()">
              </response-header>

              <div class="oppia-editor-card-section protractor-test-feedback-<[$index]>-text">

                    <[getEmptyContentMessage()]>

                    <angular-html-bind ng-class="{'oppia-rte-editor-focused': isCopyModeActive()}"
                                       ng-click="onContentClick($event)"
                                       html-data="getRequiredHtml(answerGroup.outcome.feedback)"
                                       class="oppia-rte-editor">
                    </angular-html-bind>

            <a class="oppia-rule-tab oppia-default-rule-tab protractor-test-feedback-<[stateAnswerGroups.length]>"
               ng-click="changeActiveAnswerGroupIndex(stateAnswerGroups.length)"
               ng-class="{'oppia-rule-tab-active': activeAnswerGroupIndex == stateAnswerGroups.length}"
               ng-style="contentIdStatusColorStyle(stateDefaultOutcome.feedback.getContentId())">
              <response-header index="$index"
                               is-active="$index === activeAnswerGroupIndex"
                               summary="summarizeDefaultOutcome(stateDefaultOutcome, stateInteractionId, stateDefaultOutcome.length, false)"
                               short-summary="summarizeDefaultOutcome(stateDefaultOutcome, stateInteractionId, stateDefaultOutcome.length, true)"
                               outcome="stateDefaultOutcome"
                               is-response="true"
                               show-warning="contentIdNeedUpdates(stateDefaultOutcome.feedback.getContentId())"
                               navigate-to-state="navigateToState"
                               correctness-feedback-enabled="ExplorationCorrectnessFeedbackService.isEnabled()">
              </response-header>

              <div class="oppia-editor-card-section protractor-test-feedback-<[stateAnswerGroups.length]>-text">

                  <angular-html-bind ng-class="{'oppia-rte-editor-focused': isCopyModeActive()}"
                                     ng-click="onContentClick($event)"
                                     html-data="getRequiredHtml(stateDefaultOutcome.feedback)"
                                     class="oppia-rte-editor">
                  </angular-html-bind>

          <a ng-click="changeActiveHintIndex($index)"
             class="oppia-rule-tab protractor-test-hint-<[$index]>"
             ng-class="{'oppia-rule-tab-active': activeHintIndex === $index}"
             ng-style="contentIdStatusColorStyle(hint.hintContent.getContentId())">
            <response-header index="$index"
                             summary="getSubtitledContentSummary(hint.hintContent)"
                             short-summary="getSubtitledContentSummary(hint.hintContent)"
                             is-active="$index === activeHintIndex"
                             show-warning="contentIdNeedUpdates(hint.hintContent.getContentId())">
            </response-header>

            <div class="oppia-editor-card-section protractor-test-hint-<[$index]>-text">

                <[getEmptyContentMessage()]>

                <angular-html-bind ng-class="{'oppia-rte-editor-focused': isCopyModeActive()}"
                                   ng-click="onContentClick($event)"
                                   html-data="getRequiredHtml(hint.hintContent)"
                                   class="oppia-rte-editor">
                </angular-html-bind>

        <[getEmptyContentMessage()]>

        <angular-html-bind ng-class="{'oppia-rte-editor-focused': isCopyModeActive()}"
                           ng-click="onContentClick($event)"
                           html-data="getRequiredHtml(stateSolution.explanation)"
                           class="oppia-rte-editor">
        </angular-html-bind>

    <audio-translation-bar is-translation-tab-busy="$ctrl.isTranslationTabBusy"></audio-translation-bar>

    <state-translation-editor></state-translation-editor>


text:
FactoryGirl.define do
  factory :gws_workflow_file, class: Gws::Workflow::File do
    cur_site { gws_site }
    cur_user { gws_user }

    name { "name-#{unique_id}" }
    text { "text-#{unique_id}" }
    file_ids { [ create(:ss_temp_file).id ] }
  end
end


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Profiler.Properties {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("0.0.0.0")]
        public string DefaultIP {
            get {
                return ((string)(this["DefaultIP"]));
            }
            set {
                this["DefaultIP"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("31313")]
        public short DefaultPort {
            get {
                return ((short)(this["DefaultPort"]));
            }
            set {
                this["DefaultPort"] = value;
            }
        }
    }
}


text:
import {Component, OnInit, Input, Output, EventEmitter} from "@angular/core";
import {SchemaRepositoryStateService, SchemaRepositoryActions} from "../schema-repository.state";
import {Observable} from "rxjs";
import {Schema} from "../../../../model/schema.repository";
import {ActivatedRoute, Router} from "@angular/router";
import {EditorMode, EditorDataTupel} from "../../editor-mode.enum";
@Component({
    selector: 'global-schema-editor',
    template: `
        <global-schema-editor-presentation
            [schema]="schema|async"
            [mode]="mode|async"
            (save)="onSave($event)"
            (cancel)="onCancel()"
        ></global-schema-editor-presentation>
    `
})
export class GlobalSchemaEditorComponent implements OnInit{
    schema:Observable<Schema>;
    mode:Observable<EditorMode>;

    constructor(
        private route:ActivatedRoute,
        private router:Router,
        private schemaRepositoryState:SchemaRepositoryStateService,
        private schemaRepoitoryStateActions:SchemaRepositoryActions
    ) {}

    ngOnInit(): void {
        this.schema = this.route.params
            .switchMap(({id}) => this.schemaRepositoryState.getSchema(id))
            .map(r => r || new Schema())
        this.mode = this.schema.map(s => s.id ? EditorMode.EDIT : EditorMode.NEW)

    }

    onSave([mode, schema]:EditorDataTupel<Schema>) {
        if(EditorMode.NEW === mode) {
            this.schemaRepoitoryStateActions.createSchema(schema);
        }
        if(EditorMode.EDIT === mode) {
            this.schemaRepoitoryStateActions.updateSchema(schema);
        }
        return this.onCancel();
    }

    onCancel() {
        return this.router.navigate(['configuration', 'schema-repository'])
    }
}

@Component({
    selector: 'global-schema-editor-presentation',
    templateUrl: 'global-schema-editor.html'

})
export class GlobalSchemaEditorPresentationComponent {
    @Input() schema:Schema;
    @Input() mode:EditorMode;

    @Output() save = new EventEmitter<EditorDataTupel<Schema>>();
    @Output() cancel = new EventEmitter<undefined>();

    get isNew() {
        return this.mode === EditorMode.NEW;
    }

    invokeSave() { this.save.next([this.mode, this.schema])}
    invokeCancel() { this.cancel.next()}
}


text:
class CreateSystemStatuses < ActiveRecord::Migration
  def change
    create_table :system_statuses do |t|
      t.boolean :expired, :default => false
      t.boolean :user_count_exceeded, :default => false
      t.string :message, :limit => 2048
      t.timestamps
    end
  end
end


text:
<?php

namespace Del\Person\Service;

use Del\Person\Criteria\PersonCriteria;
use Del\Person\Entity\Person;
use Del\Person\Repository\PersonRepository;
use Doctrine\ORM\EntityManager;
use Barnacle\Container;

class PersonService
{
    /** @var EntityManager $em */
    protected $em;

    /**
     * PersonService constructor.
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager)
    {
        $this->em = $entityManager;
    }

   /**
    * @param array $data
    * @return Person
    */
    public function createFromArray(array $data): Person
    {
        $person = new Person();

        return $this->populateFromArray($person, $data);
    }

    /**
     * @param Person $person
     * @param array $data
     * @return Person
     */
    public function populateFromArray(Person $person, array $data): Person
    {
        isset($data['id']) ? $person->setId($data['id']) : null;
        isset($data['firstname']) ? $person->setFirstname($data['firstname']) : null;
        isset($data['middlename']) ? $person->setMiddlename($data['middlename']) : null;
        isset($data['lastname']) ? $person->setLastname($data['lastname']) : null;
        isset($data['aka']) ? $person->setAka($data['aka']) : null;
        isset($data['dob']) ? $person->setDob($data['dob']) : null;
        isset($data['birthplace']) ? $person->setBirthplace($data['birthplace']) : null;
        isset($data['country']) ? $person->setCountry($data['country']) : null;
        isset($data['image']) ? $person->setImage($data['image']) : null;

        return $person;
    }

    /**
     * @param Person $person
     * @return array
     */
    public function toArray(Person $person): array
    {
        $data = [
            'id' => $person->getId(),
            'firstname' => $person->getFirstname(),
            'middlename' => $person->getMiddlename(),
            'lastname' => $person->getLastname(),
            'aka' => $person->getAka(),
            'dob' => $person->getDob(),
            'birthplace' => $person->getBirthplace(),
            'country' => $person->getCountry(),
            'image' => $person->getImage(),
        ];
        return $data;
    }

    /**
     * @param Person $person
     * @return Person
     */
    public function savePerson(Person $person): Person
    {
        return $this->getRepository()->save($person);
    }

    /**
     * @param Person $person
     */
    public function deletePerson(Person $person): void
    {
        $this->getRepository()->delete($person);
    }

    /**
     * @param PersonCriteria $criteria
     * @return Person[]
     */
    public function findByCriteria(PersonCriteria $criteria): array
    {
        return $this->getRepository()->findByCriteria($criteria);
    }

    public function findOneByCriteria(PersonCriteria $criteria): ?Person
    {
        $results = $this->findByCriteria($criteria);
        return (isset($results[0])) ? $results[0] : null;
    }

    protected function getRepository(): PersonRepository
    {
        return $this->em->getRepository(Person::class);
    }
}


text:
// Load required packages
var Logger = require('../config/logger');
var logger = Logger.logger;
var DataModel = require('../models/clients');
var Client = DataModel.Clients;
// TODO: implementar mas verbos y funciones para administrar los clientes
// ENDPOINT: /clients METHOD: GET
exports.getClientByIdClient = function(req, res){
    // Use the 'Clients' model to find the client by his id [idUser]
    Client.find({ idUser : req.user._id },function(err, client){
        // Check for errors and show message
        if(err){
            logger.error(err);
            res.send(err);
        }
        // success
        res.json(client);
    });
};

// ENDPOINT: /clients METHOD: POST
exports.postClient = function (req, res) {
    // Create a new instance of the Clients model
    var client = new Client();

    // Set the Clients properties that came from the POST data
    client.name = req.body.name;
    client.id = req.body.id;
    client.secret = req.body.secret;
    client.idUser = req.user._id;

    client.save(function(err){
        // Check for errors and show message
        if(err){
            logger.error(err);
            res.send(err);
        }
        // success
        res.json({ message: 'Clients created successfully!', data: client });
    });
};

// ENDPOINT: /clients/:id METHOD: DELETE
exports.deleteClient = function(req, res){
    Client.findByIdAndRemove(req.params.id, function(err){
        // Check for errors and show message
        if(err){
            logger.error(err);
            res.send(err);
        }
        // success
        res.json({ message: 'Clients deleted successfully!' });
    });
};


text:
namespace Orchard.ContentPermissions.ViewModels {
    public class SecurableContentItemsSettingsViewModel {
        public bool SecurableContentItems { get; set; }
    }
}


text:
<?php
namespace ActiveMapperTests\DataTypes;

require_once __DIR__ . "/../bootstrap.php";

use ActiveMapper\DataTypes\Date;

class DateTest extends \PHPUnit_Framework_TestCase
{
	/** @var ActiveMapper\DataTypes\Date */
	private $object;

	public function setUp()
	{
		$this->object = new Date('test');
	}

	public function testIsValidString()
	{
		$this->assertFalse($this->object->isValid("a"));
	}

	public function testIsValidNumber()
	{
		$this->assertFalse($this->object->isValid(1));
	}

	public function testIsValidBoolean()
	{
		$this->assertFalse($this->object->isValid(TRUE));
	}

	public function testIsValidDate()
	{
		$this->assertTrue($this->object->isValid("2012-12-21"));
	}

	public function testIsValidNull1()
	{
		$this->assertFalse($this->object->isValid(NULL));
	}

	public function testIsValidNull2()
	{
		$object = new Date('test', TRUE);
		$this->assertTrue($object->isValid(NULL));
	}

	public function testConvertToPHPValueDate1()
	{
		$data = $this->object->convertToPHPValue("2012-12-21");
		$this->assertType('DateTime', $data);
		$this->assertEquals(new \DateTime("2012-12-21"), $data);
	}

	public function testConvertToPHPValueDate2()
	{
		$data = $this->object->convertToPHPValue(new \DateTime("2012-12-21"));
		$this->assertType('DateTime', $data);
		$this->assertEquals(new \DateTime("2012-12-21"), $data);
	}

	public function testConvertToPHPValueStringException()
	{
		$this->setExpectedException('InvalidArgumentException');
		$data = $this->object->convertToPHPValue("a");
	}

	public function testConvertToPHPValueNumberException()
	{
		$this->setExpectedException('InvalidArgumentException');
		$data = $this->object->convertToPHPValue(1);
	}

	public function testConvertToPHPValueBooleanException()
	{
		$this->setExpectedException('InvalidArgumentException');
		$data = $this->object->convertToPHPValue(TRUE);
	}

	public function testConvertToPHPValueNull1()
	{
		$this->setExpectedException('InvalidArgumentException');
		$data = $this->object->convertToPHPValue(NULL);
	}

	public function testConvertToPHPValueNull2()
	{
		$object = new Date('test', TRUE);
		$this->assertNull($object->convertToPHPValue(NULL));
	}
}


text:
/**
 * @fileoverview Angular2 Service that handles tree keyboard navigation.
 * This is a singleton service for the entire application.
 *
 * @author madeeha@google.com (Madeeha Ghori)
 */

blocklyApp.TreeService = ng.core.Class({
  constructor: [
    blocklyApp.AudioService,
    blocklyApp.BlockConnectionService,
    blocklyApp.BlockOptionsModalService,
    blocklyApp.NotificationsService,
    blocklyApp.UtilsService,
    function(
        audioService, blockConnectionService, blockOptionsModalService,
        notificationsService, utilsService) {
      this.audioService = audioService;
      this.blockConnectionService = blockConnectionService;
      this.blockOptionsModalService = blockOptionsModalService;
      this.notificationsService = notificationsService;
      this.utilsService = utilsService;

      // Stores active descendant ids for each tree in the page.
      this.activeDescendantIds_ = {};
    }
  ],
  // Returns a list of all top-level workspace tree nodes on the page.
  getWorkspaceFocusTargets_: function() {
    return Array.from(
        document.querySelectorAll('.blocklyWorkspaceFocusTarget'));
  },
  getSidebarButtonNodes_: function() {
    return Array.from(document.querySelectorAll('button.blocklySidebarButton'));
  },
  // Returns a list of all top-level tree nodes on the page.
  getAllTreeNodes_: function() {
    return this.getWorkspaceFocusTargets_().concat(
        this.getSidebarButtonNodes_());
  },
  focusOnCurrentTree_: function(treeId) {
    var trees = this.getAllTreeNodes_();
    for (var i = 0; i < trees.length; i++) {
      if (trees[i].id == treeId) {
        trees[i].focus();
        return trees[i].id;
      }
    }
    return null;
  },
  getIdOfNextTree_: function(treeId) {
    var trees = this.getAllTreeNodes_();
    for (var i = 0; i < trees.length - 1; i++) {
      if (trees[i].id == treeId) {
        return trees[i + 1].id;
      }
    }
    return null;
  },
  getIdOfPreviousTree_: function(treeId) {
    var trees = this.getAllTreeNodes_();
    for (var i = trees.length - 1; i > 0; i--) {
      if (trees[i].id == treeId) {
        return trees[i - 1].id;
      }
    }
    return null;
  },
  getActiveDescId: function(treeId) {
    return this.activeDescendantIds_[treeId] || '';
  },
  unmarkActiveDesc_: function(activeDescId) {
    var activeDesc = document.getElementById(activeDescId);
    if (activeDesc) {
      activeDesc.classList.remove('blocklyActiveDescendant');
    }
  },
  markActiveDesc_: function(activeDescId) {
    var newActiveDesc = document.getElementById(activeDescId);
    newActiveDesc.classList.add('blocklyActiveDescendant');
  },
  // Runs the given function while preserving the focus and active descendant
  // for the given tree.
  runWhilePreservingFocus: function(func, treeId, optionalNewActiveDescId) {
    var oldDescId = this.getActiveDescId(treeId);
    var newDescId = optionalNewActiveDescId || oldDescId;
    this.unmarkActiveDesc_(oldDescId);
    func();

    // The timeout is needed in order to give the DOM time to stabilize
    // before setting the new active descendant, especially in cases like
    // pasteAbove().
    var that = this;
    setTimeout(function() {
      that.markActiveDesc_(newDescId);
      that.activeDescendantIds_[treeId] = newDescId;
      document.getElementById(treeId).focus();
    }, 0);
  },
  // This clears the active descendant of the given tree. It is used just
  // before the tree is deleted.
  clearActiveDesc: function(treeId) {
    this.unmarkActiveDesc_(this.getActiveDescId(treeId));
    delete this.activeDescendantIds_[treeId];
  },
  // Make a given node the active descendant of a given tree.
  setActiveDesc: function(newActiveDescId, treeId) {
    this.unmarkActiveDesc_(this.getActiveDescId(treeId));
    this.markActiveDesc_(newActiveDescId);
    this.activeDescendantIds_[treeId] = newActiveDescId;

    // Scroll the new active desc into view, if needed. This has no effect
    // for blind users, but is helpful for sighted onlookers.
    var activeDescNode = document.getElementById(newActiveDescId);
    var documentNode = document.body || document.documentElement;
    if (activeDescNode.offsetTop < documentNode.scrollTop ||
        activeDescNode.offsetTop >
            documentNode.scrollTop + window.innerHeight) {
      window.scrollTo(0, activeDescNode.offsetTop);
    }
  },
  initActiveDesc: function(treeId) {
    // Set the active desc to the first child in this tree.
    var tree = document.getElementById(treeId);
    this.setActiveDesc(this.getFirstChild(tree).id, treeId);
  },
  getTreeIdForBlock: function(blockId) {
    // Walk up the DOM until we get to the root node of the tree.
    var domNode = document.getElementById(blockId + 'blockRoot');
    while (!domNode.classList.contains('blocklyTree')) {
      domNode = domNode.parentNode;
    }
    return domNode.id;
  },
  focusOnBlock: function(blockId) {
    // Set focus to the tree containing the given block, and set the active
    // desc for this tree to the given block.
    var domNode = document.getElementById(blockId + 'blockRoot');
    // Walk up the DOM until we get to the root node of the tree.
    while (!domNode.classList.contains('blocklyTree')) {
      domNode = domNode.parentNode;
    }
    domNode.focus();

    // We need to wait a while to set the active desc, because domNode takes
    // a while to be given an ID if a new tree has just been created.
    // TODO(sll): Make this more deterministic.
    var that = this;
    setTimeout(function() {
      that.setActiveDesc(blockId + 'blockRoot', domNode.id);
    }, 100);
  },
  getNextActiveDescWhenBlockIsDeleted: function(blockRootNode) {
    // Go up a level, if possible.
    var nextNode = blockRootNode.parentNode;
    while (nextNode && nextNode.tagName != 'LI') {
      nextNode = nextNode.parentNode;
    }
    if (nextNode) {
      return nextNode;
    }

    // Otherwise, go to the next sibling.
    var nextSibling = this.getNextSibling(blockRootNode);
    if (nextSibling) {
      return nextSibling;
    }

    // Otherwise, go to the previous sibling.
    var previousSibling = this.getPreviousSibling(blockRootNode);
    if (previousSibling) {
      return previousSibling;
    }

    // Otherwise, this is a top-level isolated block, which means that
    // something's gone wrong and this function should not have been called
    // in the first place.
    console.error('Could not handle deletion of block.' + blockRootNode);
  },
  notifyUserAboutCurrentTree_: function(treeId) {
    var workspaceFocusTargets = this.getWorkspaceFocusTargets_();
    for (var i = 0; i < workspaceFocusTargets.length; i++) {
      if (workspaceFocusTargets[i].tagName == 'OL' &&
          workspaceFocusTargets[i].id == treeId) {
        this.notificationsService.speak(
            'Now in workspace group ' + (i + 1) + ' of ' +
            workspaceFocusTargets.length);
      }
    }
  },
  isIsolatedTopLevelBlock_: function(block) {
    // Returns whether the given block is at the top level, and has no
    // siblings.
    var blockIsAtTopLevel = !block.getParent();
    var blockHasNoSiblings = (
        (!block.nextConnection ||
         !block.nextConnection.targetConnection) &&
        (!block.previousConnection ||
         !block.previousConnection.targetConnection));
    return blockIsAtTopLevel && blockHasNoSiblings;
  },
  removeBlockAndSetFocus: function(block, blockRootNode, deleteBlockFunc) {
    // This method runs the given deletion function and then does one of two
    // things:
    // - If the block is an isolated top-level block, it shifts the tree
    //   focus.
    // - Otherwise, it sets the correct new active desc for the current tree.
    var treeId = this.getTreeIdForBlock(block.id);
    if (this.isIsolatedTopLevelBlock_(block)) {
      // Find the node to focus on after the deletion happens.
      var nextNodeToFocusOn = null;
      var focusTargets = this.getWorkspaceFocusTargets_();
      for (var i = 0; i < focusTargets.length; i++) {
        if (focusTargets[i].id == treeId) {
          if (i + 1 < focusTargets.length) {
            nextNodeToFocusOn = focusTargets[i + 1];
          } else if (i > 0) {
            nextNodeToFocusOn = focusTargets[i - 1];
          }
          break;
        }
      }

      this.clearActiveDesc(treeId);
      deleteBlockFunc();
      // Invoke a digest cycle, so that the DOM settles.
      setTimeout(function() {
        nextNodeToFocusOn = nextNodeToFocusOn || document.getElementById(
            'blocklyEmptyWorkspaceButton');
        nextNodeToFocusOn.focus();
      });
    } else {
      var nextActiveDesc = this.getNextActiveDescWhenBlockIsDeleted(
          blockRootNode);
      this.runWhilePreservingFocus(
          deleteBlockFunc, treeId, nextActiveDesc.id);
    }
  },
  showBlockOptionsModal: function(block, blockRootNode) {
    var that = this;
    var actionButtonsInfo = [];

    if (block.previousConnection) {
      actionButtonsInfo.push({
        action: function() {
          that.blockConnectionService.markConnection(block.previousConnection);
          that.focusOnBlock(block.id);
        },
        translationIdForText: 'MARK_SPOT_BEFORE'
      });
    }

    if (block.nextConnection) {
      actionButtonsInfo.push({
        action: function() {
          that.blockConnectionService.markConnection(block.nextConnection);
          that.focusOnBlock(block.id);
        },
        translationIdForText: 'MARK_SPOT_AFTER'
      });
    }

    if (this.blockConnectionService.canBeMovedToMarkedConnection(block)) {
      actionButtonsInfo.push({
        action: function() {
          var blockDescription = that.utilsService.getBlockDescription(
            block);
          var oldDestinationTreeId = that.getTreeIdForBlock(
              that.blockConnectionService.getMarkedConnectionSourceBlock().id);
          that.clearActiveDesc(oldDestinationTreeId);

          var newBlockId = that.blockConnectionService.attachToMarkedConnection(
              block);

          that.removeBlockAndSetFocus(block, blockRootNode, function() {
            block.dispose(true);
          });

          // Invoke a digest cycle, so that the DOM settles.
          setTimeout(function() {
            that.focusOnBlock(newBlockId);

            var newDestinationTreeId = that.getTreeIdForBlock(newBlockId);
            if (newDestinationTreeId != oldDestinationTreeId) {
              // It is possible for the tree ID for the pasted block to
              // change after the paste operation, e.g. when inserting a
              // block between two existing blocks that are joined
              // together. In this case, we need to also reset the active
              // desc for the old destination tree.
              that.initActiveDesc(oldDestinationTreeId);
            }

            that.notificationsService.speak(
                blockDescription + ' ' +
                Blockly.Msg.ATTACHED_BLOCK_TO_LINK_MSG +
                '. Now on attached block in workspace.');
          });
        },
        translationIdForText: 'MOVE_TO_MARKED_SPOT'
      });
    }

    actionButtonsInfo.push({
      action: function() {
        var blockDescription = that.utilsService.getBlockDescription(block);

        that.removeBlockAndSetFocus(block, blockRootNode, function() {
          block.dispose(true);
          that.audioService.playDeleteSound();
        });

        setTimeout(function() {
          if (that.utilsService.isWorkspaceEmpty()) {
            that.notificationsService.speak(
                blockDescription + ' deleted. Workspace is empty.');
          } else {
            that.notificationsService.speak(
                blockDescription + ' deleted. Now on workspace.');
          }
        });
      },
      translationIdForText: 'DELETE'
    });

    this.blockOptionsModalService.showModal(actionButtonsInfo, function() {
      that.focusOnBlock(block.id);
    });
  },
  getBlockRootSuffix_: function() {
    return 'blockRoot';
  },
  getCurrentBlockRootNode_: function(activeDesc) {
    // Starting from the activeDesc, walk up the tree until we find the
    // root of the current block.
    var blockRootSuffix = this.getBlockRootSuffix_();
    var putativeBlockRootNode = activeDesc;
    while (putativeBlockRootNode.id.indexOf(blockRootSuffix) === -1) {
      putativeBlockRootNode = putativeBlockRootNode.parentNode;
    }
    return putativeBlockRootNode;
  },
  getBlockFromRootNode_: function(blockRootNode) {
    var blockRootSuffix = this.getBlockRootSuffix_();
    var blockId = blockRootNode.id.substring(
        0, blockRootNode.id.length - blockRootSuffix.length);
    return blocklyApp.workspace.getBlockById(blockId);
  },
  onKeypress: function(e, tree) {
    // TODO(sll): Instead of this, have a common ActiveContextService which
    // returns true if at least one modal is shown, and false otherwise.
    if (this.blockOptionsModalService.isModalShown()) {
      return;
    }

    var treeId = tree.id;
    var activeDesc = document.getElementById(this.getActiveDescId(treeId));
    if (!activeDesc) {
      console.error('ERROR: no active descendant for current tree.');
      this.initActiveDesc(treeId);
      return;
    }

    if (e.altKey || e.ctrlKey) {
      // Do not intercept combinations such as Alt+Home.
      return;
    }

    if (document.activeElement.tagName == 'INPUT') {
      // For input fields, only Esc and Tab keystrokes are handled specially.
      if (e.keyCode == 27 || e.keyCode == 9) {
        // For Esc and Tab keys, the focus is removed from the input field.
        this.focusOnCurrentTree_(treeId);

        if (e.keyCode == 9) {
          var destinationTreeId =
              e.shiftKey ? this.getIdOfPreviousTree_(treeId) :
              this.getIdOfNextTree_(treeId);
          if (destinationTreeId) {
            this.notifyUserAboutCurrentTree_(destinationTreeId);
          }
        }

        // Allow Tab keypresses to go through.
        if (e.keyCode == 27) {
          e.preventDefault();
          e.stopPropagation();
        }
      }
    } else {
      // Outside an input field, Enter, Tab and navigation keys are all
      // recognized.
      if (e.keyCode == 13) {
        // Enter key. The user wants to interact with a button, interact with
        // an input field, or open the block options modal.
        // Algorithm to find the field: do a DFS through the children until
        // we find an INPUT, BUTTON or SELECT element (in which case we use it).
        // Truncate the search at child LI elements.
        var found = false;
        var dfsStack = Array.from(activeDesc.children);
        while (dfsStack.length) {
          var currentNode = dfsStack.shift();
          if (currentNode.tagName == 'BUTTON') {
            this.moveUpOneLevel_(treeId);
            currentNode.click();
            found = true;
            break;
          } else if (currentNode.tagName == 'INPUT') {
            currentNode.focus();
            currentNode.select();
            this.notificationsService.speak(
              'Type a value, then press Escape to exit');
            found = true;
            break;
          } else if (currentNode.tagName == 'SELECT') {
            currentNode.focus();
            found = true;
            return;
          } else if (currentNode.tagName == 'LI') {
            continue;
          }

          if (currentNode.children) {
            var reversedChildren = Array.from(currentNode.children).reverse();
            reversedChildren.forEach(function(childNode) {
              dfsStack.unshift(childNode);
            });
          }
        }

        // If we cannot find a field to interact with, we open the modal for
        // the current block instead.
        if (!found) {
          var blockRootNode = this.getCurrentBlockRootNode_(activeDesc);
          var block = this.getBlockFromRootNode_(blockRootNode);

          e.stopPropagation();
          this.showBlockOptionsModal(block, blockRootNode);
        }
      } else if (e.keyCode == 9) {
        // Tab key. Note that allowing the event to propagate through is
        // intentional.
        var destinationTreeId =
            e.shiftKey ? this.getIdOfPreviousTree_(treeId) :
            this.getIdOfNextTree_(treeId);
        if (destinationTreeId) {
          this.notifyUserAboutCurrentTree_(destinationTreeId);
        }
      } else if (e.keyCode == 27) {
        this.moveUpOneLevel_(treeId);
      } else if (e.keyCode >= 35 && e.keyCode <= 40) {
        // End, home, and arrow keys.
        if (e.keyCode == 35) {
          // End key. Go to the last sibling in the subtree.
          var finalSibling = this.getFinalSibling(activeDesc);
          if (finalSibling) {
            this.setActiveDesc(finalSibling.id, treeId);
          }
        } else if (e.keyCode == 36) {
          // Home key. Go to the first sibling in the subtree.
          var initialSibling = this.getInitialSibling(activeDesc);
          if (initialSibling) {
            this.setActiveDesc(initialSibling.id, treeId);
          }
        } else if (e.keyCode == 37) {
          // Left arrow key. Go up a level, if possible.
          this.moveUpOneLevel_(treeId);
        } else if (e.keyCode == 38) {
          // Up arrow key. Go to the previous sibling, if possible.
          var prevSibling = this.getPreviousSibling(activeDesc);
          if (prevSibling) {
            this.setActiveDesc(prevSibling.id, treeId);
          } else {
            var statusMessage = 'Reached top of list.';
            if (this.getParentListElement_(activeDesc)) {
              statusMessage += ' Press left to go to parent list.';
            }
            this.audioService.playOopsSound(statusMessage);
          }
        } else if (e.keyCode == 39) {
          // Right arrow key. Go down a level, if possible.
          this.moveDownOneLevel_(treeId);
        } else if (e.keyCode == 40) {
          // Down arrow key. Go to the next sibling, if possible.
          var nextSibling = this.getNextSibling(activeDesc);
          if (nextSibling) {
            this.setActiveDesc(nextSibling.id, treeId);
          } else {
            this.audioService.playOopsSound('Reached bottom of list.');
          }
        }

        e.preventDefault();
        e.stopPropagation();
      }
    }
  },
  moveDownOneLevel_: function(treeId) {
    var activeDesc = document.getElementById(this.getActiveDescId(treeId));
    var firstChild = this.getFirstChild(activeDesc);
    if (firstChild) {
      this.setActiveDesc(firstChild.id, treeId);
    } else {
      this.audioService.playOopsSound();
    }
  },
  moveUpOneLevel_: function(treeId) {
    var activeDesc = document.getElementById(this.getActiveDescId(treeId));
    var nextNode = this.getParentListElement_(activeDesc);
    if (nextNode) {
      this.setActiveDesc(nextNode.id, treeId);
    } else {
      this.audioService.playOopsSound();
    }
  },
  getParentListElement_: function(element) {
    var nextNode = element.parentNode;
    while (nextNode && nextNode.tagName != 'LI') {
      nextNode = nextNode.parentNode;
    }
    return nextNode;
  },
  getFirstChild: function(element) {
    if (!element) {
      return element;
    } else {
      var childList = element.children;
      for (var i = 0; i < childList.length; i++) {
        if (childList[i].tagName == 'LI') {
          return childList[i];
        } else {
          var potentialElement = this.getFirstChild(childList[i]);
          if (potentialElement) {
            return potentialElement;
          }
        }
      }
      return null;
    }
  },
  getFinalSibling: function(element) {
    while (true) {
      var nextSibling = this.getNextSibling(element);
      if (nextSibling && nextSibling.id != element.id) {
        element = nextSibling;
      } else {
        return element;
      }
    }
  },
  getInitialSibling: function(element) {
    while (true) {
      var previousSibling = this.getPreviousSibling(element);
      if (previousSibling && previousSibling.id != element.id) {
        element = previousSibling;
      } else {
        return element;
      }
    }
  },
  getNextSibling: function(element) {
    if (element.nextElementSibling) {
      // If there is a sibling, find the list element child of the sibling.
      var node = element.nextElementSibling;
      if (node.tagName == 'LI') {
        return node;
      } else {
        // getElementsByTagName returns in DFS order, therefore the first
        // element is the first relevant list child.
        return node.getElementsByTagName('li')[0];
      }
    } else {
      var parent = element.parentNode;
      while (parent && parent.tagName != 'OL') {
        if (parent.nextElementSibling) {
          var node = parent.nextElementSibling;
          if (node.tagName == 'LI') {
            return node;
          } else {
            return this.getFirstChild(node);
          }
        } else {
          parent = parent.parentNode;
        }
      }
      return null;
    }
  },
  getPreviousSibling: function(element) {
    if (element.previousElementSibling) {
      var sibling = element.previousElementSibling;
      if (sibling.tagName == 'LI') {
        return sibling;
      } else {
        return this.getLastChild(sibling);
      }
    } else {
      var parent = element.parentNode;
      while (parent) {
        if (parent.tagName == 'OL') {
          break;
        }
        if (parent.previousElementSibling) {
          var node = parent.previousElementSibling;
          if (node.tagName == 'LI') {
            return node;
          } else {
            // Find the last list element child of the sibling of the parent.
            return this.getLastChild(node);
          }
        } else {
          parent = parent.parentNode;
        }
      }
      return null;
    }
  },
  getLastChild: function(element) {
    if (!element) {
      return element;
    } else {
      var childList = element.children;
      for (var i = childList.length - 1; i >= 0; i--) {
        // Find the last child that is a list element.
        if (childList[i].tagName == 'LI') {
          return childList[i];
        } else {
          var potentialElement = this.getLastChild(childList[i]);
          if (potentialElement) {
            return potentialElement;
          }
        }
      }
      return null;
    }
  }
});


text:
Center on earth

Center on mars

Center on sun


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--

    Copyright 2004-2014 The Kuali Foundation

    Licensed under the Educational Community License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.opensource.org/licenses/ecl2.php

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:dd="http://rice.kuali.org/dd"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                           http://rice.kuali.org/dd
                           http://rice.kuali.org/dd/dd.xsd">

  <bean id="PositionBaseMaintenanceDocument" parent="PositionBaseMaintenanceDocument-parentBean"/>
  <bean id="PositionBaseMaintenanceDocument-parentBean" abstract="true" parent="uifMaintenanceDocumentEntry"
  		p:dataObjectClass="org.kuali.kpme.core.position.PositionBaseBo"
  		p:businessRulesClass="org.kuali.kpme.core.position.validation.PositionBaseValidation"
  		p:maintainableClass="org.kuali.kpme.core.position.web.PositionBaseMaintainableServiceImpl"
  		p:documentAuthorizerClass="org.kuali.kpme.core.position.authorization.PositionBaseAuthorizer">
    <property name="lockingKeys">
        <list>
            <value>positionNumber</value>
        </list>
    </property>
    <property name="documentTypeName" value="PositionBaseMaintenanceDocumentType"/>

    <!-- 05.02.2013 This is a kns property, which will be supported in rice 2.3 -->
    <!-- We will need to find a work around before KPME release in August
    <property name="promptBeforeValidationClass" value="org.kuali.kpme.core.position.validation.PositionEffectiveDatePrompt"/>
    -->

  </bean>

  <!-- Maintenance Section Definitions -->

  <bean id="PositionBaseMaintenanceDocument-MaintenanceView" parent="PositionBaseMaintenanceDocument-PositionBaseMaintenance-parentBean"/>
  <bean id="PositionBaseMaintenanceDocument-PositionBaseMaintenance-parentBean" abstract="true" parent="KPMEEffectiveDateBO-MaintenanceView">
    <property name="headerText" value="Position Maintenance"/>
    <property name="dataObjectClassName" value="org.kuali.kpme.core.position.PositionBaseBo"/>
    <property name="items">
      <list merge="true">
        <bean parent="KPMEGroupKeyed-MaintenanceGridSection">
        	<property name="items">
            	<list merge = "true">
                    <bean parent="Uif-InputField" p:propertyName="positionNumber" p:readOnly="true" p:required="false"/>
                    <bean parent="Uif-InputField" p:propertyName="description" p:required="true"/>
                    <bean parent="Uif-InputField" p:propertyName="active" p:defaultValue="true"/>
			    </list>
			</property>
	    </bean>
      </list>
    </property>
  </bean>

</beans>


text:
class Naturaldocs < Formula
  desc "Extensible, multi-language documentation generator"
  homepage "http://www.naturaldocs.org/"
  url "https://downloads.sourceforge.net/project/naturaldocs/Stable%20Releases/1.52/NaturalDocs-1.52.zip"
  sha256 "3f13c99e15778afe6c5555084a083f856e93567b31b08acd1fd81afb10082681"

  bottle :unneeded

  def install
    # Remove Windows files
    rm_rf Dir["*.bat"]

    libexec.install Dir["*"]
    chmod 0755, libexec+"NaturalDocs"
    bin.install_symlink libexec+"NaturalDocs"
  end

  test do
    system "#{bin}/naturaldocs", "-h"
  end
end


text:
namespace hi {

typedef std::vector<std::string> ModuleFiles;

struct Args {
  typedef std::map<std::string, std::string> NameVals;

  ModuleFiles  mfiles;
  std::string  evalExpr;
  bool         showDbg;
  bool         useDefColors;
  bool         silent;
  int          replPort;
  int          httpdPort;
  bool         exitAfterEval;
  NameVals     scriptNameVals;
  bool         machineREPL;    // should we structure console I/O for machine-reading?

  Args() : useDefColors(false), silent(false), replPort(-1), httpdPort(-1), exitAfterEval(false), machineREPL(false) {
  }
};

class evaluator {
public:
  evaluator(const Args&);
  ~evaluator();

  void runMachineREPL();

  // support the 'evaluator' interface on a local compiler context
  void showClass(const std::string& cname);
  void showInstances(const std::string& cname);

  void loadModule(const std::string& mfile);

  void evalExpr(const std::string& expr);
  void printUnsweetenedExpr(const std::string& expr);
  void printTypeOf(const std::string& expr, bool);

  void printTypeEnv();
  hobbes::str::seq completionsFor(const std::string& prefix) const;
  void printLLVMModule();
  void printAssembly(const std::string& expr, void (*)(void*,size_t));

  void perfTestExpr(const std::string& expr);
  void breakdownEvalExpr(const std::string& expr);
  void resetREPLCycle();
private:
  hobbes::cc ctx;
  bool       silent;
  WWWServer* wwwd;
};

}

#endif


text:
package org.mitre.synthea.export;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.validation.FhirValidator;
import ca.uhn.fhir.validation.SingleValidationMessage;
import ca.uhn.fhir.validation.ValidationResult;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mitre.synthea.TestHelper;
import org.mitre.synthea.engine.Generator;
import org.mitre.synthea.helpers.Config;
import org.mitre.synthea.world.agents.Provider;
import org.mitre.synthea.world.agents.ProviderTest;
import org.mitre.synthea.world.concepts.ClinicianSpecialty;
import org.mitre.synthea.world.concepts.HealthRecord.EncounterType;
import org.mitre.synthea.world.geography.Location;

public class PractitionerExportTestStu3 {

  @Rule
  public TemporaryFolder tempFolder = new TemporaryFolder();

  @Test
  public void testFHIRExport() throws Exception {
    FhirContext ctx = FhirStu3.getContext();
    FhirValidator validator = ctx.newValidator();
    validator.setValidateAgainstStandardSchema(true);
    validator.setValidateAgainstStandardSchematron(true);

    File tempOutputFolder = tempFolder.newFolder();
    Config.set("exporter.baseDirectory", tempOutputFolder.toString());
    Config.set("exporter.practitioner.fhir_stu3.export", "true");
    Config.set("exporter.fhir.bulk_data", "false");
    Config.set("exporter.fhir.transaction_bundle", "true");
    FhirStu3.TRANSACTION_BUNDLE = true; // set this manually, in case it has already been loaded.
    TestHelper.loadTestProperties();
    Generator.DEFAULT_STATE = Config.get("test_state.default", "Massachusetts");
    Location location = new Location(Generator.DEFAULT_STATE, null);
    Provider.clear();
    Provider.loadProviders(location, ProviderTest.providerRandom);
    assertNotNull(Provider.getProviderList());
    assertFalse(Provider.getProviderList().isEmpty());

    Provider.getProviderList().get(0).incrementEncounters(EncounterType.WELLNESS, 0);
    Provider.getProviderList().get(0).clinicianMap.get(
        ClinicianSpecialty.GENERAL_PRACTICE).get(0).incrementEncounters();
    FhirPractitionerExporterStu3.export(0L);

    File expectedExportFolder = tempOutputFolder.toPath().resolve("fhir_stu3").toFile();
    assertTrue(expectedExportFolder.exists() && expectedExportFolder.isDirectory());

    File expectedExportFile = expectedExportFolder.toPath()
        .resolve("practitionerInformation0.json").toFile();
    assertTrue(expectedExportFile.exists() && expectedExportFile.isFile());

    FileReader fileReader = new FileReader(expectedExportFile.getPath());
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    StringBuilder fhirJson = new StringBuilder();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
      fhirJson.append(line);
    }
    bufferedReader.close();
    IBaseResource resource = ctx.newJsonParser().parseResource(fhirJson.toString());
    ValidationResult result = validator.validateWithResult(resource);
    if (result.isSuccessful() == false) {
      for (SingleValidationMessage message : result.getMessages()) {
        System.out.println(message.getSeverity().toString() + ": " + message.getMessage());
      }
    }
    assertTrue(result.isSuccessful());
  }

  @Test
  public void testBulkExport() throws Exception {
    File tempOutputFolder = tempFolder.newFolder();
    Config.set("exporter.baseDirectory", tempOutputFolder.toString());
    Config.set("exporter.practitioner.fhir_stu3.export", "true");
    Config.set("exporter.fhir.bulk_data", "true");
    Config.set("exporter.fhir.transaction_bundle", "false");
    FhirStu3.TRANSACTION_BUNDLE = true; // set this manually, in case it has already been loaded.
    TestHelper.loadTestProperties();
    Generator.DEFAULT_STATE = Config.get("test_state.default", "Massachusetts");
    Location location = new Location(Generator.DEFAULT_STATE, null);
    Provider.clear();
    Provider.loadProviders(location, ProviderTest.providerRandom);
    assertNotNull(Provider.getProviderList());
    assertFalse(Provider.getProviderList().isEmpty());

    Provider.getProviderList().get(0).incrementEncounters(EncounterType.WELLNESS, 0);
    Provider.getProviderList().get(0).clinicianMap.get(
        ClinicianSpecialty.GENERAL_PRACTICE).get(0).incrementEncounters();
    FhirPractitionerExporterStu3.export(0L);

    File expectedExportFolder = tempOutputFolder.toPath().resolve("fhir_stu3").toFile();
    assertTrue(expectedExportFolder.exists() && expectedExportFolder.isDirectory());

    File expectedExportFile = expectedExportFolder.toPath().resolve("Practitioner.0.ndjson")
        .toFile();
    assertTrue(expectedExportFile.exists() && expectedExportFile.isFile());
  }
}


text:
function log(text) { console.log(text.replace(/^\s+|\s+$/g, '')); }
function error(err) { log('Encountered an error: ' + err.name); pc.close(); }

//
// overhead for signaling
//

// change to 'answer' if not the initiator
var offer_type = 'offer';
var channel = prompt('Please choose a room name', 'filetx')
function send(data) {post_ajax("/send/" + channel, {msg: data} );}
function messages() {
  getJSON("/read/" + channel, function(offer) {
    switch(offer.type) {
      case 'offer':
        document.querySelector('button#startButton').disabled = true;
        offer_type = 'answer';
        pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
          pc.createAnswer(function(answer) {
            pc.setLocalDescription(new RTCSessionDescription(answer), function() {}, error);
          }, error);
        }, error);
        log('Received an offer: ' + offer.sdp);
        send_channel = pc.createDataChannel('sendDataChannel', {reliable: true});
        break;
      case 'answer':
        pc.setRemoteDescription(new RTCSessionDescription(offer), function() {}, error);
        break;
      default: break;
    }
  });
}
var interval = setInterval(messages, 5000);

//
// meat of webRTC functionality
//

// main peer connection object - need one per peer
// pc will always been in the global scope
// Note: RTCPeerConnection is abstracted in adapter.js for cross-browser support
var pc = window.pc = new RTCPeerConnection(null, null);
var send_channel, outgoing_file, incoming_file = {};
var start_token = 0, data_token = 1, end_token = 2;

var rx_progress = document.querySelector('progress#rx_progress');
var tx_progress = document.querySelector('progress#tx_progress');

// if our peer sets up a data channel, set our receive channel to that channel
pc.ondatachannel = function(data_channel_event) {
  // this function is invoked whenever a message from our peer arrives
  data_channel_event.channel.onmessage = function(data_channel_event) {
    var raw_data = data_channel_event.data.slice(2);
    var type = (new Uint16Array(data_channel_event.data.slice(0, 2)))[0];
    switch(type) {
      case start_token:
        var result = "";
        raw_data = new Uint16Array(raw_data);
        // this message contains metadata about an incoming file transfer
        // jump through Javascript hoops to turn it into JSON
        for(var i = 0; i < raw_data.length; i++) { result += String.fromCharCode(raw_data[i]); }
        var data = JSON.parse(result);
        incoming_file = data;
        incoming_file.received_size = 0;
        incoming_file.content = [];
        log('New incoming file: ' + JSON.stringify(incoming_file));
        rx_progress.max = incoming_file.size;
        break;
      case data_token:
        incoming_file.content.push(raw_data);
        incoming_file.received_size += raw_data.byteLength;
        rx_progress.value = incoming_file.received_size;

        // if we've received everything from our peer
        if(incoming_file.received_size == incoming_file.size) {
          log('Incoming file finished');
          // add a link to the file
          var received = new window.Blob(incoming_file.content);
          var link = document.createElement('a');
          link.href = URL.createObjectURL(received);
          link.download = incoming_file.name;
          link.target = '_blank';
          link.appendChild(document.createTextNode(
            'Download ' + incoming_file.name + ' [' + incoming_file.size +' bytes]')
          );
          document.querySelector('div#receivedFiles').appendChild(link);
          document.querySelector('div#receivedFiles').appendChild(document.createElement('br'));
        }
        break;
      default:
        break;
    }
  }
  document.querySelector('input[type=file]').disabled = false;
  // logged to the console to let us know when this happens
  log('Created a receive data channel - may now receive data from peer.');
  clearInterval(interval);
}

// add a callback for when ice candidates are created by the peer connection
pc.onicecandidate = function(ice_event) {
  if (!ice_event.candidate) {
    log('Description sent to peer: ' + JSON.stringify(pc.localDescription));
    send({type: offer_type, sdp: pc.localDescription.sdp});
  }
};

// call this to kick off the session negotiation process with a remote peer
document.querySelector('button#startButton').onclick = function() {
  document.querySelector('button#startButton').disabled = true;
  send_channel = pc.createDataChannel('sendDataChannel', {reliable: true});
  pc.createOffer(function(offer) {
    pc.setLocalDescription(new RTCSessionDescription(offer), function() {}, error);
  }, error);
};

var chunk_length = 1024;
// called whenever a file is selected through the front-end
document.querySelector('input[type=file]').onchange = function() {
  outgoing_file = this.files[0];

  // this function transfers a little bit of the file at a time
  var slice_file = function(offset) {
    var reader = new window.FileReader();
    reader.onload = (function() {
      return function(e) {
        var data = new Uint8Array(e.target.result.byteLength + 2);
        // set the first byte to the data token
        data.set([data_token], 0);
        // read the file into an array
        data.set(new Uint8Array(e.target.result), 2);
        send_channel.send(data.buffer);
        tx_progress.value = offset;
        // if there is more file to send, send it
        if (outgoing_file.size > offset + e.target.result.byteLength) {
          window.setTimeout(slice_file, 5, offset + chunk_length);
        }
        else {
          tx_progress.value = outgoing_file.size;
        }
      };
    })(outgoing_file);
    var slice = outgoing_file.slice(offset, offset + chunk_length);
    reader.readAsArrayBuffer(slice);
  };
  // tell the other end what they're about to get
  var file_desc = JSON.stringify({
    name: outgoing_file.name, type: outgoing_file.type, size: outgoing_file.size
  });
  // jump through JavaScript's hoops to get that string (16-bit chars) into the
  // destination buffer
  var data = new Uint16Array(1 + file_desc.length);
  for(var i = 1; i <= file_desc.length; i++) { data.set([file_desc.charCodeAt(i - 1)], i) }
  data.set([start_token], 0);
  tx_progress.max = outgoing_file.size;
  // send the description of the incoming file to the recipient
  send_channel.send(data.buffer);
  // start the file transfer
  slice_file(0);
};


text:
import { TaroSvgIconFC } from '@yzfe/taro-svgicon'

const icons: TaroSvgIconFC[] = []

const req = require.context('@fa', true, /\.svg/)
req.keys().forEach((key) => {
    icons.push(req(key).default)
})

export default icons


text:
<?xml version="1.0" encoding="UTF-8"?>
<com.example.google.playservices.placepicker.cardstream.CardLayout
    android:id="@+id/card_layout"
    style="@style/Card"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/card_actionarea"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/card_contentarea"
        android:background="@color/card_action_bg"
        android:orientation="vertical"
        android:paddingBottom="@dimen/card_action_margin"
        android:visibility="gone"
        >
        <include layout="@layout/card_button_seperator"/>
    </LinearLayout>

    <LinearLayout
        android:id="@id/card_contentarea"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        style="@style/CardContentArea">

        <TextView
            android:id="@+id/card_title"
            style="@style/CardTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/card_content"
            style="@style/CardContent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/card_title"/>

    </LinearLayout>

    <View
        android:id="@+id/card_overlay"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignBottom="@id/card_contentarea"
        android:layout_alignLeft="@id/card_contentarea"
        android:layout_alignRight="@id/card_contentarea"
        android:layout_alignTop="@id/card_contentarea"
        android:layout_alignWithParentIfMissing="false"
        android:visibility="invisible"/>

</com.example.google.playservices.placepicker.cardstream.CardLayout>


text:
// Copyright (c) 2019 Andrew Vardeman.  Published under the MIT license.
// See license.txt in the FileSharper distribution or repository for the
// full text of the license.

using System.IO;
using System.Threading;
using FileSharperCore.Processors.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FileSharperCore.Tests.Processors.Text
{
    [TestClass]
    public class PrependOrAppendTextProcessorTests : TestBase
    {
        [TestMethod]
        public void PrependSuccess()
        {
            Success(PrependAppend.Prepend, "foo bar baz", LineEndings.MatchInput,
                OutputEncodingType.MatchInput);
        }

        [TestMethod]
        public void PrependOneNewlineSuccess()
        {
            Success(PrependAppend.Prepend, "foo bar baz\r\n", LineEndings.MatchInput,
                OutputEncodingType.MatchInput);
        }

        [TestMethod]
        public void PrependTwoNewlineSuccess()
        {
            Success(PrependAppend.Prepend, "foo bar baz\r\n\r\n", LineEndings.MatchInput,
                OutputEncodingType.MatchInput);
        }

        [TestMethod]
        public void AppendSuccess()
        {
            Success(PrependAppend.Append, "foo bar baz", LineEndings.MatchInput,
                OutputEncodingType.MatchInput);
        }

        [TestMethod]
        public void AppendOneNewlineSuccess()
        {
            Success(PrependAppend.Append, "foo bar baz\r\n", LineEndings.MatchInput,
                OutputEncodingType.MatchInput);
        }

        [TestMethod]
        public void AppendTwoNewlineSuccess()
        {
            Success(PrependAppend.Append, "foo bar baz\r\n\r\n", LineEndings.MatchInput,
                OutputEncodingType.MatchInput);
        }

        [TestMethod]
        public void PrependClassicMacOSSuccess()
        {
            Success(PrependAppend.Prepend, "foo bar baz", LineEndings.ClassicMacOS,
                OutputEncodingType.MatchInput);
        }

        [TestMethod]
        public void PrependUtf16Success()
        {
            Success(PrependAppend.Prepend, "foo bar baz", LineEndings.MatchInput,
                OutputEncodingType.UTF16_LE);
        }

        [TestMethod]
        public void FailsFileExists()
        {
            string outFilename = GetCurrentTestResultsFilePath("out.txt");
            FileInfo file = GetTestFile("Lipsum.txt");
            PrependOrAppendTextProcessor processor = new PrependOrAppendTextProcessor();
            processor.SetParameter("Text", "foo bar baz");
            processor.SetParameter("FileName", outFilename);
            processor.SetParameter("OverwriteExistingFile", false);
            File.WriteAllBytes(outFilename, new byte[0]);
            processor.Init(RunInfo);
            ProcessingResult result = processor.Process(file, MatchResultType.Yes, new string[0],
                new FileInfo[0], ProcessInput.OriginalFile, CancellationToken.None);
            processor.Cleanup();
            Assert.AreEqual(ProcessingResultType.Failure, result.Type);
            Assert.AreEqual(0, result.OutputFiles.Length);
        }

        [TestMethod]
        public void SucceedsFileExists()
        {
            string outFilename = GetCurrentTestResultsFilePath("out.txt");
            FileInfo file = GetTestFile("Lipsum.txt");
            PrependOrAppendTextProcessor processor = new PrependOrAppendTextProcessor();
            processor.SetParameter("Text", "foo bar baz");
            processor.SetParameter("FileName", outFilename);
            processor.SetParameter("OverwriteExistingFile", true);
            File.WriteAllBytes(outFilename, new byte[0]);
            processor.Init(RunInfo);
            ProcessingResult result = processor.Process(file, MatchResultType.Yes, new string[0],
                new FileInfo[0], ProcessInput.OriginalFile, CancellationToken.None);
            processor.Cleanup();
            Assert.AreEqual(ProcessingResultType.Success, result.Type);
            Assert.AreEqual(1, result.OutputFiles.Length);
        }

        [TestMethod]
        public void FailsFileInUse()
        {
            string outFilename = GetCurrentTestResultsFilePath("out.txt");
            FileInfo file = GetTestFile("Lipsum.txt");
            PrependOrAppendTextProcessor processor = new PrependOrAppendTextProcessor();
            processor.SetParameter("Text", "foo bar baz");
            processor.SetParameter("FileName", outFilename);
            processor.SetParameter("OverwriteExistingFile", true);
            ProcessingResult result;
            using (FileStream fs = File.OpenWrite(outFilename))
            {
                processor.Init(RunInfo);
                result = processor.Process(file, MatchResultType.Yes, new string[0],
                    new FileInfo[0], ProcessInput.OriginalFile, CancellationToken.None);
                processor.Cleanup();
            }
            Assert.AreEqual(ProcessingResultType.Failure, result.Type);
            Assert.AreEqual(0, result.OutputFiles.Length);
        }

        private void Success(PrependAppend prependAppend, string text, LineEndings lineEndings,
            OutputEncodingType outputEncoding)
        {
            FileInfo file = GetTestFile("Lipsum.txt");
            PrependOrAppendTextProcessor processor = new PrependOrAppendTextProcessor();
            processor.SetParameter("PrependOrAppend", prependAppend);
            processor.SetParameter("Text", text);
            processor.SetParameter("LineEndings", lineEndings);
            processor.SetParameter("OutputEncoding", outputEncoding);
            processor.SetParameter("FileName", GetCurrentTestResultsFilePath("out.txt"));
            processor.SetParameter("OverwriteExistingFile", false);
            processor.SetParameter("MoveOriginalToRecycleBin", false);
            processor.Init(RunInfo);
            ProcessingResult result = processor.Process(file, MatchResultType.Yes, new string[0],
                new FileInfo[0], ProcessInput.OriginalFile, CancellationToken.None);
            processor.Cleanup();
            Assert.AreEqual(ProcessingResultType.Success, result.Type);
            Assert.AreEqual(1, result.OutputFiles.Length);
        }
    }
}


text:
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {GraphFooterModule} from '../../graph-footer/graph-footer.module';
import {CommonTooltipModule} from '../../../thirdparty/ngx-charts-universal/common/tooltip/common-tooltip.module';
import {GraphIndicatorStructureComponent} from './indicator-structure.component';
import {RadarPieChartModule} from '../../../thirdparty/ngx-charts-universal/radar-pie-chart/radar-pie-chart.module';

@NgModule({
	imports: [
		CommonModule,
		GraphFooterModule,
		RadarPieChartModule,
		CommonTooltipModule
	],
	declarations: [
		GraphIndicatorStructureComponent
	],
	exports: [
		GraphIndicatorStructureComponent
	]
})
export class GraphsRadarPieModule {
}


text:
const {google} = require('googleapis');
const SHEETS_SCOPE = 'https://www.googleapis.com/auth/spreadsheets.readonly';
const ACCOUNTS_SHEET_ID = '1kxW15ZI48mh4KkvgsMpg7gInmEQmyKYRnZdbUOSMRnU';
const ACCOUNTS_SHEET_URL = 'https://docs.google.com/spreadsheets/d/1kxW15ZI48mh4KkvgsMpg7gInmEQmyKYRnZdbUOSMRnU/edit#gid=0';
const ACCOUNT_IMAGE_URL = 'https://www.gstatic.com/images/icons/material/system_gm/1x/account_circle_black_18dp.png';

/**
 * Looks up the account owner for the company requested.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
*/
exports.accountsBot = async (req, res) => {
  const message = req.body.message;
  if (!message || !message.text) {
    console.log('invalid request');
  }

  const messageParts = message.text.split(/[ ,]+/);
  if (messageParts.length != 2) {
    res.send(createTextResponse('Please enter a single account to look up.'));
  }

  const accountName = messageParts[1];
  console.log(`accountName: ${accountName}`);
  const sheetsClient = await getSheetsClient();
  try {
    const ownerData = await accountLookup(sheetsClient, accountName);
    res.send(createOwnerCard(ownerData));
  } catch (error) {
    res.send(createErrorCard(accountName));
  }
};

/**
 * Looks up ownership information for the account.
 *
 * @param {Object} client initialized Sheets API client.
 * @param {String} accountName inbound message
 * @return {String} owner data
 */
async function accountLookup(client, accountName) {
  const accountsSheet = await client.spreadsheets.values.get({
    spreadsheetId: ACCOUNTS_SHEET_ID,
    range: 'Sheet1!A:D',
  });
  const accountsTable = accountsSheet.data.values;

  return accountsTable.find((entry) => entry[0] === accountName);
}

/**
 * Authenticates the Sheets API client for read-only access.
 *
 * @return {Object} sheets client
 */
async function getSheetsClient() {
  // Should change this to file.only probably
  const auth = await google.auth.getClient({
    scopes: [SHEETS_SCOPE],
  });
  return google.sheets({version: 'v4', auth});
}

/**
 * Creates JSON response for a simple text message for Hangouts.
 *
 * @param {String} message the text of message response
 * @return {JSON} the reponse data
*/
function createTextResponse(message) {
  return {text: message};
}

/**
 * Creates a JSON with the fields specified.
 *
 * @param {Array} data owner info
 * @return {Object} a card with the owner info
 */
function createOwnerCard(data) {
  const company = data[0];
  const name = data[1];
  const location = data[2];
  const email = data[3];

  const cardHeader = {
    title: company + ' Account Owner',
    subtitle: name,
    imageUrl: ACCOUNT_IMAGE_URL,
    imageStyle: 'IMAGE',
  };

  const emailWidget = {
    keyValue: {
      content: 'Email',
      bottomLabel: email,
    },
  };

  const locationWidget = {
    keyValue: {
      content: 'Location',
      bottomLabel: location,
    },
  };

  const infoSection = {widgets: [emailWidget, locationWidget]};

  const cards = [{
    name: 'Status Card',
    header: cardHeader,
    sections: [infoSection],
  }];

  return {cards: cards};
}

/**
 * Creates a card to respond if no account is found.
 *
 * @param {String} accountName the company that could not be found.
 * @return {Object} a card with default info.
 */
function createErrorCard(accountName) {
  const cardHeader = {
    title: 'Account Information Not Found',
    subtitle: 'Account requested: ' + accountName,
    imageUrl: ACCOUNT_IMAGE_URL,
    imageStyle: 'IMAGE',
  };

  const textWidget = {
    textParagraph: {
      text: 'Please check the account data is up to date',
    },
  };

  const buttonWidget = {
    buttons: [
      {
        textButton: {
          text: 'Account Data',
          onClick: {
            openLink: {
              url: ACCOUNTS_SHEET_URL,
            },
          },
        },
      },
    ],
  };

  const infoSection = {widgets: [textWidget, buttonWidget]};

  const cards = [{
    name: 'No Owner Found',
    header: cardHeader,
    sections: [infoSection],
  }];
  return {cards: cards};
}


text:
.. _footprint:

Optimizing for Footprint
########################

Stack Sizes
***********

Stack sizes of various system threads are specified generously to allow for
usage in different scenarios on as many supported platforms as possible. You
should start the optimization process by reviewing all stack sizes and adjusting
them for your application:

:kconfig:option:`CONFIG_ISR_STACK_SIZE`
  Set to 2048 by default

:kconfig:option:`CONFIG_MAIN_STACK_SIZE`
  Set to 1024 by default

:kconfig:option:`CONFIG_IDLE_STACK_SIZE`
  Set to 320 by default

:kconfig:option:`CONFIG_SYSTEM_WORKQUEUE_STACK_SIZE`
  Set to 1024 by default

:kconfig:option:`CONFIG_PRIVILEGED_STACK_SIZE`
  Set to 1024 by default, depends on userspace feature.

Unused Peripherals
******************

Some peripherals are enabled by default. You can disable unused
peripherals in your project configuration, for example::

        CONFIG_GPIO=n
        CONFIG_SPI=n

Various Debug/Informational Options
***********************************

The following options are enabled by default to provide more information about
the running application and to provide means for debugging and error handling:

:kconfig:option:`CONFIG_BOOT_BANNER`
  This option can be disabled to save a few bytes.

:kconfig:option:`CONFIG_DEBUG`
  This option can be disabled for production builds

MPU/MMU Support
***************

Depending on your application and platform needs, you can disable MPU/MMU
support to gain some memory and improve performance.  Consider the consequences
of this configuration choice though, because you'll lose advanced stack
checking and support.


text:
Package.describe({
  name: 'planifica:encryption',
  version: '0.0.5',
  // Brief, one-line summary of the package.
  summary: 'Client-Side Encryption for Mongo Collections',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/Planifica/encryption',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');

  api.use(['underscore', 'check'], ['client', 'server']);
  api.use('u2622:persistent-session@0.4.1', 'client');
  api.use('aldeed:collection2@2.5.0');
  api.use('ongoworks:security@1.2.0');
  api.use('matb33:collection-hooks@0.7.13');
  api.use('robertlowe:persistent-reactive-dict@0.1.2', 'client');
  api.use('jparker:crypto-core@0.1.0', 'client');
  api.use('jparker:crypto-base64@0.1.0', 'client');
  api.use('dburles:mongo-collection-instances@0.3.4', ['server']);

  api.addFiles('tweetnacl-js-master/nacl-fast.min.js', 'client');

  api.addFiles('principals.js', ['client', 'server']);
  api.addFiles('server.js', 'server');
  api.addFiles('utils.js', 'client');
  api.addFiles('EncryptionUtils.js', 'client');
  api.addFiles('CollectionEncryption.js', 'client');

  api.export('CollectionEncryption');
  api.export('EncryptionUtils');
  api.export('Principals');
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('planifica:encryption');
});


text:
package com.gl051.oop;

public class Teacher extends Person {

    public Teacher(String firstName, String lastName) {
        super(firstName, lastName);
    }

    @Override
    public String getOccupation() {
        return "Teacher";
    }

}


text:
#include "testutils.h"

#include "rsa.h"
#include "knuth-lfib.h"

void
test_main(void)
{
  struct rsa_public_key pub;
  struct rsa_private_key key;
  struct knuth_lfib_ctx lfib;

  /* FIXME: How is this spelled? */
  const uint8_t *msg = "Squemish ossifrage";
  unsigned msg_length;

  uint8_t *decrypted;
  unsigned decrypted_length;
  uint8_t after;

  mpz_t gibberish;

  rsa_private_key_init(&key);
  rsa_public_key_init(&pub);
  mpz_init(gibberish);

  knuth_lfib_init(&lfib, 17);

  test_rsa_set_key_1(&pub, &key);
  msg_length = strlen(msg);

  if (verbose)
    fprintf(stderr, "msg: `%s', length = %d\n", msg, msg_length);

  ASSERT(rsa_encrypt(&pub,
		     &lfib, (nettle_random_func *) knuth_lfib_random,
		     msg_length, msg,
		     gibberish));

  if (verbose)
    {
      /* In which GMP version was gmp_fprintf introduced? */
      fprintf(stderr, "encrypted: ");
      mpz_out_str(stderr, 10, gibberish);
    }

  decrypted = xalloc(msg_length + 1);

  knuth_lfib_random (&lfib, msg_length + 1, decrypted);
  after = decrypted[msg_length];

  decrypted_length = msg_length - 1;
  ASSERT(!rsa_decrypt(&key, &decrypted_length, decrypted, gibberish));

  decrypted_length = msg_length;
  ASSERT(rsa_decrypt(&key, &decrypted_length, decrypted, gibberish));
  ASSERT(decrypted_length == msg_length);
  ASSERT(MEMEQ(msg_length, msg, decrypted));
  ASSERT(decrypted[msg_length] == after);

  knuth_lfib_random (&lfib, msg_length + 1, decrypted);
  after = decrypted[msg_length];

  decrypted_length = key.size;
  ASSERT(rsa_decrypt(&key, &decrypted_length, decrypted, gibberish));
  ASSERT(decrypted_length == msg_length);
  ASSERT(MEMEQ(msg_length, msg, decrypted));
  ASSERT(decrypted[msg_length] == after);

  knuth_lfib_random (&lfib, msg_length + 1, decrypted);
  after = decrypted[msg_length];

  decrypted_length = msg_length;
  ASSERT(rsa_decrypt_tr(&pub, &key,
			&lfib, (nettle_random_func *) knuth_lfib_random,
			&decrypted_length, decrypted, gibberish));
  ASSERT(decrypted_length == msg_length);
  ASSERT(MEMEQ(msg_length, msg, decrypted));
  ASSERT(decrypted[msg_length] == after);

  rsa_private_key_clear(&key);
  rsa_public_key_clear(&pub);
  mpz_clear(gibberish);
  free(decrypted);
}


text:
package myconet;

import peersim.cdsim.*;
import peersim.config.*;
import peersim.core.*;
import peersim.util.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.*;
import java.io.*;
//import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import edu.uci.ics.jung.algorithms.importance.*;
import edu.uci.ics.jung.algorithms.layout.*;
import edu.uci.ics.jung.algorithms.shortestpath.*;
import edu.uci.ics.jung.algorithms.util.*;
import edu.uci.ics.jung.graph.*;
import edu.uci.ics.jung.graph.util.*;
import edu.uci.ics.jung.visualization.*;
import edu.uci.ics.jung.visualization.control.*;
import edu.uci.ics.jung.visualization.decorators.*;
import edu.uci.ics.jung.visualization.picking.*;
import edu.uci.ics.jung.visualization.renderers.*;
import org.apache.commons.collections15.*;
import org.apache.commons.collections15.functors.*;

public class FluctuationObserver implements Control {
  private Graph<MycoNode,MycoEdge> graph;

  private static final String PAR_TESTNAME = "config.basename";

  private static String basename;
  private static String filename;

  private static final String PAR_PERIOD = "period";
  private static int period;

  private static Logger log =
      Logger.getLogger(FluctuationObserver.class.getName());

  private static Set<ChangeListener> changeListeners =
      new HashSet<ChangeListener>();

  // ah: (key, val) = (times fluctuated, number of nodes)
  public static HashMap<Integer,Integer> fluctuations;

  public FluctuationObserver(String prefix) {
    basename = Configuration.getString(PAR_TESTNAME);
    period = Configuration.getInt(prefix + "." + PAR_PERIOD);
    graph = JungGraphObserver.getGraph();
    clearStats();

    File resultsDir = new File("results");
    if (!resultsDir.exists()) {
      resultsDir.mkdir();
    }
    StringBuffer fn = new StringBuffer();
    java.util.Formatter f = new java.util.Formatter(fn, Locale.US);
    f.format("%s/fluc-%s-%d.txt", resultsDir.getPath(), basename,
             CommonState.seed);
    filename = fn.toString();
  }

  private static void clearStats() {
    fluctuations = new HashMap<Integer,Integer>();
  }

  public static void updateStats() {

    clearStats();
    MycoList all = MycoCast.getAllNodes();

    for (MycoNode n : all) {
      int flucs = n.getHyphaData().getBulwarkEntries();
      // ah: it's not a fluctuation until second time in bulwark state
      if (flucs > 0) {
        flucs = flucs -1;
      }
      Integer key = new Integer(flucs);
      Integer val = fluctuations.get(key);
      if (val == null) {
        fluctuations.put(key, new Integer(1));
      }
      else {
        fluctuations.put(key, val + 1);
      }
    }
  }

  @SuppressWarnings("unchecked")
  public boolean execute() {

    if (CDState.getCycle() % period != 0)
        return false;

    updateStats();
    if (fluctuations.isEmpty())
        return false;

    StringBuilder sb = new StringBuilder();
    java.util.Formatter f = new java.util.Formatter(sb, Locale.US);

    Integer i = 0;

    HashMap<Integer,Integer> map =
        (HashMap<Integer,Integer>) fluctuations.clone();
    while (!map.isEmpty()) {
      Integer val = map.remove(i);
      if (val == null) {
        f.format("%1d:%1d, ", i, 0);
      }
      else {
        f.format("%1d:%1d, ", i, val);
      }
      i++;
    }

    // ah: remove last commaspace and add a newline
    sb.delete(sb.length()-2, sb.length());
    sb.append("\n");

    // ah: TODO: copy experiment writer to get this writing to
    // a file, too, so i can make a graph out of it.
    try {
      FileOutputStream out = new FileOutputStream(filename, true);
      PrintStream p = new PrintStream(out);
      p.print(sb.toString());
      out.close();
    } catch (IOException e) {
      log.severe("Error writing fluctuation data to file");
      debug(e.getMessage());
    }

    log.info("fluctuation counts " + sb.toString());
    return false;
  }

  public static void debug(String s) {
    System.out.println("DEBUG: " + s);
  }

}