text:
/**
 Do not return anything, modify matrix in-place instead.
 */
function rotate(matrix: number[][]): void {
    const length = matrix.length;
    for (let rowIdx = 0; rowIdx < Math.floor(length / 2) + 1; rowIdx++) {
        for (let colIdx = rowIdx; colIdx < length - rowIdx - 1; colIdx++) {
            let temp = matrix[rowIdx][colIdx];
            matrix[rowIdx][colIdx] = matrix[length - colIdx - 1][rowIdx];
            matrix[length - colIdx - 1][rowIdx] = matrix[length - rowIdx - 1][length - colIdx - 1];
            matrix[length - rowIdx - 1][length - colIdx - 1] = matrix[colIdx][length - rowIdx - 1];
            matrix[colIdx][length - rowIdx - 1] = temp;
        }
    }
};


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="sort_api_values">
        <item>offer_price</item>
        <item>points_needed</item>
        <item>distance</item>
        <item>popular_store</item>
        <item>quantity_remains</item>
        <item>o_original_view</item>
        <item>redeem</item>
        <item>offer_price</item>
        <item>createdOn</item>
        <item>discount</item>
        <item>createdOn</item>
    </string-array>

    <string-array name="quote_sort_hints">
        <item>@string/location</item>
    </string-array>

    <string-array name="array_quantity">
        <item>@string/select_quantity</item>
        <item>1</item>
        <item>2</item>
        <item>3</item>
        <item>4</item>
        <item>5</item>
    </string-array>

    <integer-array name="footer_tab_normal">
        <item>@drawable/ic_tab_home</item> // Home
        <item>@drawable/ic_tab_ood</item> // OOD
        <item>@drawable/ic_tab_heart</item> // Favourite
        <item>@drawable/ic_tab_store</item> // Mall/Store
        <item>@drawable/ic_tab_quote</item> // Quotes
        <item>@drawable/ic_tab_loyalty_offers</item> // Loyalty offers
        <item>@drawable/ic_tab_watch</item> // watch list
        <item>@drawable/ic_tab_featured</item> // featured offer
        <item>@drawable/ic_tab_grabbed</item> // grabbed history
    </integer-array>

    <integer-array name="footer_tab_clicked">
        <item>@drawable/ic_tab_home_clicked</item>
        <item>@drawable/ic_tab_ood_clicked</item>
        <item>@drawable/ic_tab_heart_clicked</item>
        <item>@drawable/ic_tab_store_clicked</item>
        <item>@drawable/ic_tab_quote_clicked</item>
        <item>@drawable/ic_tab_loyalty_offers_clicked</item>
        <item>@drawable/ic_tab_watch_clicked</item>
        <item>@drawable/ic_tab_featured_clicked</item>
        <item>@drawable/ic_tab_grabbed_click</item>
    </integer-array>

    <integer-array name="header_tab">
        <item>@drawable/ic_category_fv</item> // Category
        <item>@drawable/ic_tab_filter</item> // Filter
        <item>@drawable/ic_location_fav</item> // Location
        <item>@drawable/ic_tab_sort</item> // Sort By
        <item>@drawable/ic_tab_map</item> // Map
    </integer-array>
</resources>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>FLUID FLOAT GRID</title>

Title

Home

About

Description

Help

Side Bar

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Main Content

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


text:
using __gnu_cxx::__mt_alloc;

void*
operator new(std::size_t n) throw(std::bad_alloc)
{
  new_called = true;
  return std::malloc(n);
}

void
operator delete(void* v) throw()
{
  delete_called = true;
  return std::free(v);
}

void test01()
{
  // Uses new but delete only optionally.
  bool test __attribute__((unused)) = true;
  typedef __mt_alloc<unsigned int> allocator_type;
  VERIFY( bool(__gnu_test::check_new<allocator_type, true>()) );
}

int main()
{
  test01();
  return 0;
}


text:
/*
 * require store/spree_core
*/

div.account-summary {
    float: left;

}


text:
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("ComposableAsync.Concurrent.Test")]
[assembly: InternalsVisibleTo("ComposableAsync.Factory.Test")]
[assembly: InternalsVisibleTo("ComposableAsync.Factory.Examples")]
[assembly: InternalsVisibleTo("PingPongConsole")]


text:
package org.coursera.naptime.ari.graphql.controllers.filters

import org.coursera.naptime.ResourceTestImplicits
import org.junit.Test

class QueryComplexityFilterTest extends FilterTest with ResourceTestImplicits {

  val config = ComplexityFilterConfiguration.DEFAULT
  val filter = new QueryComplexityFilter(graphqlSchemaProvider, config)

  @Test
  def emptyQuery(): Unit = {
    val incomingQuery = generateIncomingQuery()
    val outgoingQuery = run(incomingQuery).futureValue
    assert(outgoingQuery === baseOutgoingQuery)
  }

  @Test
  def complexQuery(): Unit = {
    val query =
      """
        |query {
        |  CoursesV1Resource {
        |    getAll(limit: 100000) {
        |      elements {
        |        id
        |      }
        |    }
        |  }
        |}
      """.stripMargin
    val incomingQuery = generateIncomingQuery(query)
    val outgoingQuery = ensureNotPropagated(incomingQuery).futureValue

    assert(outgoingQuery.response.value("error").as[String] === "Query is too complex.")
    assert(outgoingQuery.response.value("complexity").as[Int] === 200001)
  }
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>
Matching Security Quiz
</title>

Matching Security Quiz

Concept
Definition

<input type="button" value="Back to Main Page" onclick="window.location='hello.html';"/>


text:
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

		<title>Rangy - Tests</title>

		<link rel="stylesheet" type="text/css" href="tests.css"/>


text:
package cryptoattackers

import (
	"errors"
	"fmt"
)

// DetermineBlockSize will return the blocksize of some encryption func which takes in a []byte.
// The function can potentially do some fixed-size transformation on its input (e.g. append a set number of bytes)
// before encrypting.
func DetermineBlockSize(encryptionFunc func([]byte) ([]byte, error)) (int, error) {
	plainTextBytes := []byte("\x00")

	blockSizeBytes := 0
	hasChanged := false
	changedSize := 0

	cipherTextBytes, err := encryptionFunc(plainTextBytes)
	if err != nil {
		return -1, fmt.Errorf("encryptionFunc invocation error: %v", err)
	}

	// Loop until the output changes size twice
	for blockSizeBytes == 0 {
		plainTextBytes = append(plainTextBytes, byte('\x00'))
		cipherTextBytes1, err := encryptionFunc(plainTextBytes)
		if err != nil {
			return -1, errors.New("encryptionFunc invocation error")
		}

		if len(cipherTextBytes) != len(cipherTextBytes1) {
			if hasChanged {
				blockSizeBytes = len(cipherTextBytes1) - changedSize
			} else {
				hasChanged = true
				changedSize = len(cipherTextBytes1)
			}
		}

		cipherTextBytes = cipherTextBytes1
	}

	return blockSizeBytes, nil
}


text:
const SERVICE_NAME_PREFIX = 'chatroom-'

export default () => {
  angular
    .module('chatApp', [])
    .controller('chatCtrl', ['$scope', '$timeout', function (scope, $timeout) {
      const TYPING_TIMER_LENGTH = 600
      let socket = io()
      let connected = false
      let typing = false
      let lastTypingTime
      let $inputMessage = $('input[data-ng-model="viewData.sendContent"]')
      let updateTyping = function () {
        if (connected) {
          if (!typing) {
            typing = true
            socket.emit(SERVICE_NAME_PREFIX + 'typing')
          }
          lastTypingTime = (new Date()).getTime()

          setTimeout(function () {
            let typingTimer = (new Date()).getTime()
            let timeDiff = typingTimer - lastTypingTime
            if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
              socket.emit(SERVICE_NAME_PREFIX + 'stop typing')
              typing = false
            }
          }, TYPING_TIMER_LENGTH)
        }
      }

      scope.keydownHandler = function (event) {
        event.ctrlKey || event.metaKey || event.altKey || $inputMessage.focus()
        if (event.which === 13) {
          scope.sendMessage()
        }
      }

      scope.clearMsg = function (event) {
        scope.viewData.notifications = []
      }

      $inputMessage.on('input', function () {
        updateTyping()
      })

      socket.on(SERVICE_NAME_PREFIX + 'login', function (data) {
        connected = true
        scope.notify({
          content: '欢迎来到聊天室',
          icon: 'fa-smile-o'
        })
        scope.viewData.numUsers = data['numUsers']
        scope.$digest()
      })

      socket.on(SERVICE_NAME_PREFIX + 'new message', function (message) {
        scope.viewData.chatQueue.push(message)
        $timeout(function () {
          $('.direct-chat-messages').scrollTop(99999)
        }, 1)
        scope.$digest()
      })

      socket.on(SERVICE_NAME_PREFIX + 'user joined', function (data) {
        scope.notify({
          content: data.user.name + '来打酱油了...',
          icon: 'fa-user-plus'
        })
        scope.viewData.numUsers = data['numUsers']
        scope.$digest()
      })

      socket.on(SERVICE_NAME_PREFIX + 'user left', function (data) {
        scope.notify({
          content: data.user.name + '妈妈喊他回家吃饭了...',
          icon: 'fa-hand-peace-o'
        })
        scope.viewData.numUsers = data['numUsers']
        scope.$digest()
      })

      socket.on(SERVICE_NAME_PREFIX + 'typing', function (data) {
        scope.addChatTyping(data)
        scope.$digest()
      })

      socket.on(SERVICE_NAME_PREFIX + 'stop typing', function (data) {
        scope.removeChatTyping(data)
        scope.$digest()
      })

      scope.chatroom = {
        name: '食堂开门了,冲!'
      }

      scope.currentUser = __currentUser

      scope.viewData = {
        messages: [],
        notifications: [],
        chatQueue: [],
        logInfo: [],
        contactQueue: [],
        sendContent: '',
        numUsers: 1,
      }

      scope.log = function (data) {
        scope.viewData.logInfo.unshift(data)
      }

      scope.removeLog = function (id) {
        let _index = 0
        while (_index < scope.viewData.logInfo.length) {
          if (scope.viewData.logInfo[_index]['_id'] === id) {
            break
          }
          _index++
        }
        if (_index > -1) {
          scope.viewData.logInfo.splice(_index, 1)
        }
      }

      scope.notify = function (notification) {
        scope.viewData.notifications.unshift(notification)
      }

      /**
       * 发送消息
       */
      scope.sendMessage = function () {
        socket.emit(SERVICE_NAME_PREFIX + 'stop typing')
        typing = false
        if (scope.viewData.sendContent != '') {
          let message = {
            message: scope.viewData.sendContent
          }
          socket.emit(SERVICE_NAME_PREFIX + 'new message', message)
          message.isMine = true
          message.sender = scope.currentUser
          message.createTime = new Date()
          scope.viewData.chatQueue.push(message)
          scope.viewData.sendContent = ''
          // $inputMessage.blur()
          $timeout(function () {
            $('.direct-chat-messages').scrollTop(99999)
          }, 1)
        } else {
          $.warning('发送内容不能为空!')
        }
      }

      scope.addChatTyping = function (data) {
        scope.log({
          _id: data['_id'],
          content: data['user']['name'] + '正在输入...'
        })
      }

      scope.removeChatTyping = function (data) {
        scope.removeLog(data['_id'])
      }

      socket.emit(SERVICE_NAME_PREFIX + 'add user', scope.currentUser)

      scope.$on('$destroy', function () {
        socket.emit()(`${SERVICE_NAME_PREFIX}disconnect`, scope.currentUser)
      })
    }])

}


text:
using UnityEngine;
using System.Collections;

namespace Workshop
{
		public class BackgroundPropSpawner : MonoBehaviour
		{
				public Rigidbody2D backgroundProp;		// The prop to be instantiated.
				public float leftSpawnPosX;				// The x coordinate of position if it's instantiated on the left.
				public float rightSpawnPosX;			// The x coordinate of position if it's instantiated on the right.
				public float minSpawnPosY;				// The lowest possible y coordinate of position.
				public float maxSpawnPosY;				// The highest possible y coordinate of position.
				public float minTimeBetweenSpawns;		// The shortest possible time between spawns.
				public float maxTimeBetweenSpawns;		// The longest possible time between spawns.
				public float minSpeed;					// The lowest possible speed of the prop.
				public float maxSpeed;					// The highest possible speeed of the prop.

				void Start ()
				{
						// Set the random seed so it's not the same each game.
						Random.seed = System.DateTime.Today.Millisecond;

						// Start the Spawn coroutine.
						StartCoroutine ("Spawn");
				}

				IEnumerator Spawn ()
				{
						// Create a random wait time before the prop is instantiated.
						float waitTime = Random.Range (minTimeBetweenSpawns, maxTimeBetweenSpawns);

						// Wait for the designated period.
						yield return new WaitForSeconds (waitTime);

						// Randomly decide whether the prop should face left or right.
						bool facingLeft = Random.Range (0, 2) == 0;

						// If the prop is facing left, it should start on the right hand side, otherwise it should start on the left.
						float posX = facingLeft ? rightSpawnPosX : leftSpawnPosX;

						// Create a random y coordinate for the prop.
						float posY = Random.Range (minSpawnPosY, maxSpawnPosY);

						// Set the position the prop should spawn at.
						Vector3 spawnPos = new Vector3 (posX, posY, transform.position.z);

						// Instantiate the prop at the desired position.
						Rigidbody2D propInstance = Instantiate (backgroundProp, spawnPos, Quaternion.identity) as Rigidbody2D;

						// The sprites for the props all face left.  Therefore, if the prop should be facing right...
						if (!facingLeft) {
								// ... flip the scale in the x axis.
								Vector3 scale = propInstance.transform.localScale;
								scale.x *= -1;
								propInstance.transform.localScale = scale;
						}

						// Create a random speed.
						float speed = Random.Range (minSpeed, maxSpeed);

						// These speeds would naturally move the prop right, so if it's facing left, multiply the speed by -1.
						speed *= facingLeft ? -1f : 1f;

						// Set the prop's velocity to this speed in the x axis.
						propInstance.velocity = new Vector2 (speed, 0);

						// Restart the coroutine to spawn another prop.
						StartCoroutine (Spawn ());

						// While the prop exists...
						while (propInstance != null) {
								// ... and if it's facing left...
								if (facingLeft) {
										// ... and if it's beyond the left spawn position...
										if (propInstance.transform.position.x < leftSpawnPosX - 0.5f)
					// ... destroy the prop.
												Destroy (propInstance.gameObject);
								} else {
										// Otherwise, if the prop is facing right and it's beyond the right spawn position...
										if (propInstance.transform.position.x > rightSpawnPosX + 0.5f)
					// ... destroy the prop.
												Destroy (propInstance.gameObject);
								}

								// Return to this point after the next update.
								yield return null;
						}
				}
		}
}


text:
function buildEditorToolbar() {
    var bar = document.createElement('div');
    addClass(bar, 'ebl-toolbar', 'ebl-editor-toolbar');

    var separator = document.createElement('span');
    addClass(separator, 'ebl-separator');

    var format = document.createElement('div');

    var undo = createButton('ebl-action-editor-undo', l18n_("Undo"));
    addClass(undo, 'ebl-icon-rotate-left');
    setDataAttribute(undo, 'wysihtmlCommand', 'undo');

    var textBold = createButton('ebl-action-editor-bold', l18n_("Bold"));
    addClass(textBold, 'ebl-icon-bold');
    setDataAttribute(textBold, 'wysihtmlCommand', 'bold');

    var textItalic = createButton('ebl-action-editor-italic', l18n_("Italic"));
    addClass(textItalic, 'ebl-icon-italic');
    setDataAttribute(textItalic, 'wysihtmlCommand', 'italic');

    var textUnderline = createButton('ebl-action-editor-underline', l18n_("Underline"));
    addClass(textUnderline, 'ebl-icon-underline');
    setDataAttribute(textUnderline, 'wysihtmlCommand', 'underline');

    var textH1 = createButton('ebl-action-editor-h1', l18n_("H1"));
    addClass(textH1, 'ebl-icon-header');
    setDataAttribute(textH1, 'wysihtmlCommand', 'formatBlock');
    setDataAttribute(textH1, 'wysihtmlCommandValue', 'h1');

    var alignLeft = createButton('ebl-action-editor-alignleft', l18n_("Align left"));
    addClass(alignLeft, 'ebl-icon-align-left');
    setDataAttribute(alignLeft, 'wysihtmlCommand', 'justifyLeft');

    var alignCenter = createButton('ebl-action-editor-aligncenter', l18n_("Align center"));
    addClass(alignCenter, 'ebl-icon-align-center');
    setDataAttribute(alignCenter, 'wysihtmlCommand', 'justifyCenter');

    var alignRight = createButton('ebl-action-editor-alignright', l18n_("Align right"));
    addClass(alignRight, 'ebl-icon-align-right');
    setDataAttribute(alignRight, 'wysihtmlCommand', 'justifyRight');

    var addUl = createButton('ebl-action-editor-addul', l18n_("Unordered list"));
    addClass(addUl, 'ebl-icon-list-ul');
    setDataAttribute(addUl, 'wysihtmlCommand', 'insertUnorderedList');

    var addOl = createButton('ebl-action-editor-addol', l18n_("Ordered list"));
    addClass(addOl, 'ebl-icon-list-ol');
    setDataAttribute(addOl, 'wysihtmlCommand', 'insertOrderedList');

    var addImage = createButton('ebl-action-editor-addimage', l18n_("Add image"));
    addClass(addImage, 'ebl-icon-image');
    setDataAttribute(addImage, 'wysihtmlCommand', 'insertImage');

    var addLink = createButton('ebl-action-editor-addlink', l18n_("Add link"));
    addClass(addLink, 'ebl-icon-chain');
    setDataAttribute(addLink, 'wysihtmlCommand', 'createLink');

    var showHtml = createButton('ebl-action-editor-html', l18n_("Edit HTML"));
    addClass(showHtml, 'ebl-icon-file-code');
    setDataAttribute(showHtml, 'wysihtmlAction', 'change_view');

    format.appendChild(undo);
    format.appendChild(separator.cloneNode(true));

    format.appendChild(textBold);
    format.appendChild(textItalic);
    format.appendChild(textUnderline);
    format.appendChild(textH1);
    format.appendChild(separator.cloneNode(true));

    format.appendChild(alignLeft);
    format.appendChild(alignCenter);
    format.appendChild(alignRight);
    format.appendChild(separator.cloneNode(true));

    format.appendChild(addUl);
    format.appendChild(addOl);
    format.appendChild(separator.cloneNode(true));

    format.appendChild(addImage);
    format.appendChild(addLink);
    format.appendChild(separator.cloneNode(true));

    format.appendChild(showHtml);

    var image = document.createElement('div');
    setDataAttribute(image, 'wysihtmlDialog', 'insertImage');
    addClass(image, 'ebl-editor-toolbar-sub', 'toolbar-sub-2');

    var imageSrc = document.createElement('input');
    setDataAttribute(imageSrc, 'wysihtmlDialogField', 'src');
    imageSrc.type = 'text';
    imageSrc.value = 'http://';

    var imageSrcSave = createButton('ebl-action-editor-image-save', l18n_("Add image"));
    imageSrcSave.innerHTML = l18n_("Add image");
    setDataAttribute(imageSrcSave, 'wysihtmlDialogAction', 'save');

    image.appendChild(imageSrc);
    image.appendChild(imageSrcSave);
    hideElement(image);

    var link = document.createElement('div');
    setDataAttribute(link, 'wysihtmlDialog', 'createLink');
    addClass(link, 'ebl-editor-toolbar-sub', 'toolbar-sub-2');

    var linkUrl = document.createElement('input');
    setDataAttribute(linkUrl, 'wysihtmlDialogField', 'href');
    linkUrl.type = 'text';
    linkUrl.value = 'http://';

    var linkUrlSave = createButton('ebl-action-editor-link-save', l18n_("Add link"));
    linkUrlSave.innerHTML = l18n_("Add link");
    setDataAttribute(linkUrlSave, 'wysihtmlDialogAction', 'save');

    link.appendChild(linkUrl);
    link.appendChild(linkUrlSave);
    hideElement(link);

    bar.appendChild(format);
    bar.appendChild(image);
    bar.appendChild(link);

    bar.style.visibility = 'hidden';
    prependTo(gState.container, bar);

    return bar;
}

function buildTitleToolbar() {
    var bar = document.createElement('div');
    addClass(bar, 'ebl-toolbar', 'ebl-title-toolbar');

    var tags = createButton('ebl-action-title-tag',  l18n_("Tags"));
    addClass(tags, 'ebl-icon-tags');
    tags.onmousedown = function() {
        showTagsDialog(printTagsFromArray(lState.post.tags), function (newTags) {
            lState.post.tags = parseTagsFromString(newTags);
        });
    };

    bar.appendChild(tags);

    bar.style.visibility = 'hidden';
    prependTo(gState.container, bar);

    return bar;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>establishment</type>
  <type>point_of_interest</type>
  <formatted_address>37 College Green, Dublin, Ireland</formatted_address>
  <address_component>
   <long_name>37</long_name>
   <short_name>37</short_name>
   <type>street_number</type>
  </address_component>
  <address_component>
   <long_name>College Green</long_name>
   <short_name>College Green</short_name>
   <type>route</type>
  </address_component>
  <address_component>
   <long_name>Dublin</long_name>
   <short_name>Dublin</short_name>
   <type>postal_town</type>
  </address_component>
  <address_component>
   <long_name>County Dublin</long_name>
   <short_name>County Dublin</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Ireland</long_name>
   <short_name>IE</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <geometry>
   <location>
    <lat>53.3441906</lat>
    <lng>-6.2596103</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>53.3428416</lat>
     <lng>-6.2609593</lng>
    </southwest>
    <northeast>
     <lat>53.3455396</lat>
     <lng>-6.2582613</lng>
    </northeast>
   </viewport>
  </geometry>
  <place_id>ChIJ6dPJX5sOZ0gR2BkK3EMa250</place_id>
 </result>
</GeocodeResponse>


text:
package org.bubblecloud.zigbee.api.device.impl;

import org.bubblecloud.zigbee.api.ZigBeeApiConstants;
import org.bubblecloud.zigbee.ZigBeeApiContext;
import org.bubblecloud.zigbee.network.ZigBeeEndpoint;
import org.bubblecloud.zigbee.api.*;
import org.bubblecloud.zigbee.api.cluster.general.Identify;
import org.bubblecloud.zigbee.api.cluster.security_safety.IASACE;
import org.bubblecloud.zigbee.api.cluster.security_safety.IASZone;
import org.bubblecloud.zigbee.api.device.security_safety.IASAncillaryControlEquipment;
import org.bubblecloud.zigbee.api.DeviceBase;

/**
 * @author Manlio Bacco
 * @version $LastChangedRevision$ ($LastChangedDate$)
 * @since 0.7.0
 */
public class IASAncillaryControlEquipmentDevice extends DeviceBase implements IASAncillaryControlEquipment {

    private Identify identify;
    private IASZone iasZone;
    private IASACE iasAce;

    public IASAncillaryControlEquipmentDevice(ZigBeeApiContext ctx, ZigBeeEndpoint zbDevice) throws ZigBeeDeviceException {

        super(ctx, zbDevice);
        iasAce = (IASACE) getCluster(ZigBeeApiConstants.CLUSTER_ID_IAS_ACE);
        iasZone = (IASZone) getCluster(ZigBeeApiConstants.CLUSTER_ID_IAS_ZONE);
        identify = (Identify) getCluster(ZigBeeApiConstants.CLUSTER_ID_IDENTIFY);
    }

    public IASACE getIASACE() {
        return iasAce;
    }

    public IASZone getIASZone() {
        return iasZone;
    }

    /*public Identify getIdentify(){
        return identify;
    }*/

    @Override
    public String getDeviceType() {
        return IASAncillaryControlEquipment.NAME;
    }

    @Override
    public DeviceDescription getDescription() {

        return DEVICE_DESCRIPTOR;
    }

    final static DeviceDescription DEVICE_DESCRIPTOR = new AbstractDeviceDescription() {

        public int[] getCustomClusters() {
            return IASAncillaryControlEquipment.CUSTOM;
        }

        public int[] getMandatoryCluster() {
            return IASAncillaryControlEquipment.MANDATORY;
        }

        public int[] getOptionalCluster() {
            return IASAncillaryControlEquipment.OPTIONAL;
        }

        public int[] getStandardClusters() {
            return IASAncillaryControlEquipment.STANDARD;
        }
    };
}


text:
namespace media {

// Contains all information that a decryptor needs to decrypt a media sample.
class MEDIA_EXPORT DecryptConfig {
 public:
  // Keys are always 128 bits.
  static const int kDecryptionKeySize = 16;

  // |key_id| is the ID that references the decryption key for this sample.
  // |iv| is the initialization vector defined by the encrypted format.
  //   Currently |iv| must be 16 bytes as defined by WebM and ISO. It must
  //   be provided.
  // |subsamples| defines the clear and encrypted portions of the sample as
  //   described above. A decrypted buffer will be equal in size to the sum
  //   of the subsample sizes.
  // |encryption_pattern| is the pattern used ('cbcs' only). It is optional
  //   as Common encryption of MPEG-2 transport streams v1 (23009-1:2014)
  //   does not specify patterns for cbcs encryption mode. The pattern is
  //   assumed to be 1:9 for video. Tracks other than video are protected
  //   using whole-block full-sample encryption (pattern 0:0 or unspecified).
  static std::unique_ptr<DecryptConfig> CreateCencConfig(
      const std::string& key_id,
      const std::string& iv,
      const std::vector<SubsampleEntry>& subsamples);
  static std::unique_ptr<DecryptConfig> CreateCbcsConfig(
      const std::string& key_id,
      const std::string& iv,
      const std::vector<SubsampleEntry>& subsamples,
      absl::optional<EncryptionPattern> encryption_pattern);

  DecryptConfig(EncryptionScheme encryption_scheme,
                const std::string& key_id,
                const std::string& iv,
                const std::vector<SubsampleEntry>& subsamples,
                absl::optional<EncryptionPattern> encryption_pattern);

  DecryptConfig& operator=(const DecryptConfig&) = delete;

  ~DecryptConfig();

  const std::string& key_id() const { return key_id_; }
  const std::string& iv() const { return iv_; }
  const std::vector<SubsampleEntry>& subsamples() const { return subsamples_; }
  EncryptionScheme encryption_scheme() const { return encryption_scheme_; }
  const absl::optional<EncryptionPattern>& encryption_pattern() const {
    return encryption_pattern_;
  }

  std::unique_ptr<DecryptConfig> Clone() const;

  // Makes a new config which has the same configuration options (mode, pattern)
  // while providing a new vector of subsamples and initialization vector.
  std::unique_ptr<DecryptConfig> CopyNewSubsamplesIV(
      const std::vector<SubsampleEntry>& subsamples,
      const std::string& iv);

  // Returns whether this config has EncryptionPattern set or not.
  bool HasPattern() const;

  // Returns true if all fields in |config| match this config.
  bool Matches(const DecryptConfig& config) const;

  // Prints to std::ostream.
  std::ostream& Print(std::ostream& os) const;

 private:
  DecryptConfig(const DecryptConfig& other);

  const EncryptionScheme encryption_scheme_;
  const std::string key_id_;

  // Initialization vector.
  const std::string iv_;

  // Subsample information. May be empty for some formats, meaning entire frame
  // (less data ignored by data_offset_) is encrypted.
  const std::vector<SubsampleEntry> subsamples_;

  // Only specified if |encryption_mode_| requires a pattern.
  absl::optional<EncryptionPattern> encryption_pattern_;
};

inline std::ostream& operator<<(std::ostream& os,
                                const media::DecryptConfig& obj) {
  return obj.Print(os);
}

}  // namespace media

#endif  // MEDIA_BASE_DECRYPT_CONFIG_H_


text:
	{{title}}
	 - {{subtitle}}


text:
<?php

namespace Ignittion\Kong\Exceptions;

use Exception;

/**
 * Kong Http Exception.
 *
 * Thrown whenever an error happens when communicating with a Kong Gateway
 * server.
 *
 * @category Exceptions
 * @package Kong-PHP
 */
class KongHttpException extends Exception
{
    //
}


text:
package com.google.sitebricks.compiler;

import java.lang.reflect.Type;
import java.util.List;

import org.mvel2.ErrorDetail;

import com.google.sitebricks.Evaluator;

/**
 * @author Dhanji R. Prasanna (dhanji@gmail.com)
 */
public interface EvaluatorCompiler {

  /**
   * @param expression An expression to compile against this compiler (and context class)
   *
   * @return Returns An evaluator that can execute the expression against the context class and a
   *         real instance of data.
   * @throws ExpressionCompileException If there is a problem compiling the expression.
   */
  Evaluator compile(String expression) throws ExpressionCompileException;

  /**
   * @param template A String template with embedded EL expressions to convert into a list of
   * evaluable tokens. These tokens evaluate against given data or simply render plain text as
   * appropriate. Performs a compile of each expression against the context class of this
   * EvaluatorCompiler.
   *
   * @return Returns the egress type of the entire expression chain
   * @throws com.google.sitebricks.compiler.ExpressionCompileException If there is a problem
   * compiling the expression.
   */
  List<Token> tokenizeAndCompile(String template) throws ExpressionCompileException;

  /**
   * @param expression An expression to compile against this compiler (and context class)
   *
   * @return Returns the egress type of the entire expression chain
   * @throws com.google.sitebricks.compiler.ExpressionCompileException If there is a problem
   * compiling the expression.
   */
  Type resolveEgressType(String expression) throws ExpressionCompileException;

  /**
   * @param property A property of this class to test.
   * @return True if the property has a setter or reasonable alternative that can
   * be written to by the evaluator produced by this compiler.
   */
  boolean isWritable(String property) throws ExpressionCompileException;

  public static class CompileErrorDetail {
    private final String expression;
    private final ErrorDetail error;

    public CompileErrorDetail(String expression, ErrorDetail error) {
      this.expression = expression;
      this.error = error;
    }

    public String getExpression() {
      return expression;
    }

    public ErrorDetail getError() {
      return error;
    }
  }
}


text:
package org.apache.flex.compiler.problems;

/**
 * Problem generated when a supplied attribute on an element cannot be resolved.
 */
public final class FXGUndefinedPropertyProblem extends FXGProblem
{
    public static final String DESCRIPTION = "Undefined property ${property}.";
    public static final int errorCode = 1402;
    public final String property;

    public FXGUndefinedPropertyProblem(String property)
    {
        super(null);
        this.property = property;
    }
}


text:
"""Abstract linear algebra library.

This module defines a class hierarchy that implements a kind of "lazy"
matrix representation, called the ``LinearOperator``. It can be used to do
linear algebra with extremely large sparse or structured matrices, without
representing those explicitly in memory. Such matrices can be added,
multiplied, transposed, etc.

As a motivating example, suppose you want have a matrix where almost all of
the elements have the value one. The standard sparse matrix representation
skips the storage of zeros, but not ones. By contrast, a LinearOperator is
able to represent such matrices efficiently. First, we need a compact way to
represent an all-ones matrix::

    >>> import numpy as np
    >>> class Ones(LinearOperator):
    ...     def __init__(self, shape):
    ...         super(Ones, self).__init__(dtype=None, shape=shape)
    ...     def _matvec(self, x):
    ...         return np.repeat(x.sum(), self.shape[0])

Instances of this class emulate ``np.ones(shape)``, but using a constant
amount of storage, independent of ``shape``. The ``_matvec`` method specifies
how this linear operator multiplies with (operates on) a vector. We can now
add this operator to a sparse matrix that stores only offsets from one::

    >>> from scipy.sparse import csr_matrix
    >>> offsets = csr_matrix([[1, 0, 2], [0, -1, 0], [0, 0, 3]])
    >>> A = aslinearoperator(offsets) + Ones(offsets.shape)
    >>> A.dot([1, 2, 3])
    array([13,  4, 15])

The result is the same as that given by its dense, explicitly-stored
counterpart::

    >>> (np.ones(A.shape, A.dtype) + offsets.toarray()).dot([1, 2, 3])
    array([13,  4, 15])

Several algorithms in the ``scipy.sparse`` library are able to operate on
``LinearOperator`` instances.
"""

from __future__ import division, print_function, absolute_import

import numpy as np

from scipy.sparse import isspmatrix
from scipy.sparse.sputils import isshape, isintlike

__all__ = ['LinearOperator', 'aslinearoperator']

class LinearOperator(object):
    """Common interface for performing matrix vector products

    Many iterative methods (e.g. cg, gmres) do not need to know the
    individual entries of a matrix to solve a linear system A*x=b.
    Such solvers only require the computation of matrix vector
    products, A*v where v is a dense vector.  This class serves as
    an abstract interface between iterative solvers and matrix-like
    objects.

    To construct a concrete LinearOperator, either pass appropriate
    callables to the constructor of this class, or subclass it.

    A subclass must implement either one of the methods ``_matvec``
    and ``_matmat``, and the attributes/properties ``shape`` (pair of
    integers) and ``dtype`` (may be None). It may call the ``__init__``
    on this class to have these attributes validated. Implementing
    ``_matvec`` automatically implements ``_matmat`` (using a naive
    algorithm) and vice-versa.

    Optionally, a subclass may implement ``_rmatvec`` or ``_adjoint``
    to implement the Hermitian adjoint (conjugate transpose). As with
    ``_matvec`` and ``_matmat``, implementing either ``_rmatvec`` or
    ``_adjoint`` implements the other automatically. Implementing
    ``_adjoint`` is preferable; ``_rmatvec`` is mostly there for
    backwards compatibility.

    Parameters
    ----------
    shape : tuple
        Matrix dimensions (M,N).
    matvec : callable f(v)
        Returns returns A * v.
    rmatvec : callable f(v)
        Returns A^H * v, where A^H is the conjugate transpose of A.
    matmat : callable f(V)
        Returns A * V, where V is a dense matrix with dimensions (N,K).
    dtype : dtype
        Data type of the matrix.

    Attributes
    ----------
    args : tuple
        For linear operators describing products etc. of other linear
        operators, the operands of the binary operation.

    See Also
    --------
    aslinearoperator : Construct LinearOperators

    Notes
    -----
    The user-defined matvec() function must properly handle the case
    where v has shape (N,) as well as the (N,1) case.  The shape of
    the return type is handled internally by LinearOperator.

    LinearOperator instances can also be multiplied, added with each
    other and exponentiated, all lazily: the result of these operations
    is always a new, composite LinearOperator, that defers linear
    operations to the original operators and combines the results.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.sparse.linalg import LinearOperator
    >>> def mv(v):
    ...     return np.array([2*v[0], 3*v[1]])
    ...
    >>> A = LinearOperator((2,2), matvec=mv)
    >>> A
    <2x2 _CustomLinearOperator with dtype=float64>
    >>> A.matvec(np.ones(2))
    array([ 2.,  3.])
    >>> A * np.ones(2)
    array([ 2.,  3.])

    """
    def __new__(cls, *args, **kwargs):
        if cls is LinearOperator:
            # Operate as _CustomLinearOperator factory.
            return _CustomLinearOperator(*args, **kwargs)
        else:
            obj = super(LinearOperator, cls).__new__(cls)

            if (type(obj)._matvec == LinearOperator._matvec
                    and type(obj)._matmat == LinearOperator._matmat):
                raise TypeError("LinearOperator subclass should implement"
                                " at least one of _matvec and _matmat.")

            obj.__init__(*args, **kwargs)
            return obj

    def __init__(self, dtype, shape):
        """Initialize this LinearOperator.

        To be called by subclasses. ``dtype`` may be None; ``shape`` should
        be convertible to a length-2 tuple.
        """
        if dtype is not None:
            dtype = np.dtype(dtype)

        shape = tuple(shape)
        if not isshape(shape):
            raise ValueError("invalid shape %r (must be 2-d)" % shape)

        self.dtype = dtype
        self.shape = shape

    def _init_dtype(self):
        """Called from subclasses at the end of the __init__ routine.
        """
        if self.dtype is None:
            v = np.zeros(self.shape[-1])
            self.dtype = np.asarray(self.matvec(v)).dtype

    def _matmat(self, X):
        """Default matrix-matrix multiplication handler.

        Falls back on the user-defined _matvec method, so defining that will
        define matrix multiplication (though in a very suboptimal way).
        """

        return np.hstack([self.matvec(col.reshape(-1,1)) for col in X.T])

    def _matvec(self, x):
        """Default matrix-vector multiplication handler.

        If self is a linear operator of shape (M, N), then this method will
        be called on a shape (N,) or (N, 1) ndarray, and should return a
        shape (M,) or (M, 1) ndarray.

        This default implementation falls back on _matmat, so defining that
        will define matrix-vector multiplication as well.
        """
        return self.matmat(x.reshape(-1, 1))

    def matvec(self, x):
        """Matrix-vector multiplication.

        Performs the operation y=A*x where A is an MxN linear
        operator and x is a column vector or 1-d array.

        Parameters
        ----------
        x : {matrix, ndarray}
            An array with shape (N,) or (N,1).

        Returns
        -------
        y : {matrix, ndarray}
            A matrix or ndarray with shape (M,) or (M,1) depending
            on the type and shape of the x argument.

        Notes
        -----
        This matvec wraps the user-specified matvec routine or overridden
        _matvec method to ensure that y has the correct shape and type.

        """

        x = np.asanyarray(x)

        M,N = self.shape

        if x.shape != (N,) and x.shape != (N,1):
            raise ValueError('dimension mismatch')

        y = self._matvec(x)

        if isinstance(x, np.matrix):
            y = np.asmatrix(y)
        else:
            y = np.asarray(y)

        if x.ndim == 1:
            y = y.reshape(M)
        elif x.ndim == 2:
            y = y.reshape(M,1)
        else:
            raise ValueError('invalid shape returned by user-defined matvec()')

        return y

    def rmatvec(self, x):
        """Adjoint matrix-vector multiplication.

        Performs the operation y = A^H * x where A is an MxN linear
        operator and x is a column vector or 1-d array.

        Parameters
        ----------
        x : {matrix, ndarray}
            An array with shape (M,) or (M,1).

        Returns
        -------
        y : {matrix, ndarray}
            A matrix or ndarray with shape (N,) or (N,1) depending
            on the type and shape of the x argument.

        Notes
        -----
        This rmatvec wraps the user-specified rmatvec routine or overridden
        _rmatvec method to ensure that y has the correct shape and type.

        """

        x = np.asanyarray(x)

        M,N = self.shape

        if x.shape != (M,) and x.shape != (M,1):
            raise ValueError('dimension mismatch')

        y = self._rmatvec(x)

        if isinstance(x, np.matrix):
            y = np.asmatrix(y)
        else:
            y = np.asarray(y)

        if x.ndim == 1:
            y = y.reshape(N)
        elif x.ndim == 2:
            y = y.reshape(N,1)
        else:
            raise ValueError('invalid shape returned by user-defined rmatvec()')

        return y

    def _rmatvec(self, x):
        """Default implementation of _rmatvec; defers to adjoint."""
        if type(self)._adjoint == LinearOperator._adjoint:
            # _adjoint not overridden, prevent infinite recursion
            raise NotImplementedError
        else:
            return self.H.matvec(x)

    def matmat(self, X):
        """Matrix-matrix multiplication.

        Performs the operation y=A*X where A is an MxN linear
        operator and X dense N*K matrix or ndarray.

        Parameters
        ----------
        X : {matrix, ndarray}
            An array with shape (N,K).

        Returns
        -------
        Y : {matrix, ndarray}
            A matrix or ndarray with shape (M,K) depending on
            the type of the X argument.

        Notes
        -----
        This matmat wraps any user-specified matmat routine or overridden
        _matmat method to ensure that y has the correct type.

        """

        X = np.asanyarray(X)

        if X.ndim != 2:
            raise ValueError('expected 2-d ndarray or matrix, not %d-d'
                             % X.ndim)

        M,N = self.shape

        if X.shape[0] != N:
            raise ValueError('dimension mismatch: %r, %r'
                             % (self.shape, X.shape))

        Y = self._matmat(X)

        if isinstance(Y, np.matrix):
            Y = np.asmatrix(Y)

        return Y

    def __call__(self, x):
        return self*x

    def __mul__(self, x):
        return self.dot(x)

    def dot(self, x):
        """Matrix-matrix or matrix-vector multiplication.

        Parameters
        ----------
        x : array_like
            1-d or 2-d array, representing a vector or matrix.

        Returns
        -------
        Ax : array
            1-d or 2-d array (depending on the shape of x) that represents
            the result of applying this linear operator on x.

        """
        if isinstance(x, LinearOperator):
            return _ProductLinearOperator(self, x)
        elif np.isscalar(x):
            return _ScaledLinearOperator(self, x)
        else:
            x = np.asarray(x)

            if x.ndim == 1 or x.ndim == 2 and x.shape[1] == 1:
                return self.matvec(x)
            elif x.ndim == 2:
                return self.matmat(x)
            else:
                raise ValueError('expected 1-d or 2-d array or matrix, got %r'
                                 % x)

    def __rmul__(self, x):
        if np.isscalar(x):
            return _ScaledLinearOperator(self, x)
        else:
            return NotImplemented

    def __pow__(self, p):
        if np.isscalar(p):
            return _PowerLinearOperator(self, p)
        else:
            return NotImplemented

    def __add__(self, x):
        if isinstance(x, LinearOperator):
            return _SumLinearOperator(self, x)
        else:
            return NotImplemented

    def __neg__(self):
        return _ScaledLinearOperator(self, -1)

    def __sub__(self, x):
        return self.__add__(-x)

    def __repr__(self):
        M,N = self.shape
        if self.dtype is None:
            dt = 'unspecified dtype'
        else:
            dt = 'dtype=' + str(self.dtype)

        return '<%dx%d %s with %s>' % (M, N, self.__class__.__name__, dt)

    def adjoint(self):
        """Hermitian adjoint.

        Returns the Hermitian adjoint of self, aka the Hermitian
        conjugate or Hermitian transpose. For a complex matrix, the
        Hermitian adjoint is equal to the conjugate transpose.

        Can be abbreviated self.H instead of self.adjoint().

        Returns
        -------
        A_H : LinearOperator
            Hermitian adjoint of self.
        """
        return self._adjoint()

    H = property(adjoint)

    def transpose(self):
        """Transpose this linear operator.

        Returns a LinearOperator that represents the transpose of this one.
        Can be abbreviated self.T instead of self.transpose().
        """
        return self._transpose()

    T = property(transpose)

    def _adjoint(self):
        """Default implementation of _adjoint; defers to rmatvec."""
        shape = (self.shape[1], self.shape[0])
        return _CustomLinearOperator(shape, matvec=self.rmatvec,
                                     rmatvec=self.matvec,
                                     dtype=self.dtype)

class _CustomLinearOperator(LinearOperator):
    """Linear operator defined in terms of user-specified operations."""

    def __init__(self, shape, matvec, rmatvec=None, matmat=None, dtype=None):
        super(_CustomLinearOperator, self).__init__(dtype, shape)

        self.args = ()

        self.__matvec_impl = matvec
        self.__rmatvec_impl = rmatvec
        self.__matmat_impl = matmat

        self._init_dtype()

    def _matmat(self, X):
        if self.__matmat_impl is not None:
            return self.__matmat_impl(X)
        else:
            return super(_CustomLinearOperator, self)._matmat(X)

    def _matvec(self, x):
        return self.__matvec_impl(x)

    def _rmatvec(self, x):
        func = self.__rmatvec_impl
        if func is None:
            raise NotImplemented("rmatvec is not defined")
        return self.__rmatvec_impl(x)

    def _adjoint(self):
        return _CustomLinearOperator(shape=(self.shape[1], self.shape[0]),
                                     matvec=self.__rmatvec_impl,
                                     rmatvec=self.__matvec_impl,
                                     dtype=self.dtype)

def _get_dtype(operators, dtypes=[]):
    for obj in operators:
        if obj is not None and hasattr(obj, 'dtype'):
            dtypes.append(obj.dtype)
    return np.find_common_type(dtypes, [])

class _SumLinearOperator(LinearOperator):
    def __init__(self, A, B):
        if not isinstance(A, LinearOperator) or \
                not isinstance(B, LinearOperator):
            raise ValueError('both operands have to be a LinearOperator')
        if A.shape != B.shape:
            raise ValueError('cannot add %r and %r: shape mismatch'
                             % (A, B))
        self.args = (A, B)
        super(_SumLinearOperator, self).__init__(_get_dtype([A, B]), A.shape)

    def _matvec(self, x):
        return self.args[0].matvec(x) + self.args[1].matvec(x)

    def _rmatvec(self, x):
        return self.args[0].rmatvec(x) + self.args[1].rmatvec(x)

    def _matmat(self, x):
        return self.args[0].matmat(x) + self.args[1].matmat(x)

    def _adjoint(self):
        A, B = self.args
        return A.H + B.H

class _ProductLinearOperator(LinearOperator):
    def __init__(self, A, B):
        if not isinstance(A, LinearOperator) or \
                not isinstance(B, LinearOperator):
            raise ValueError('both operands have to be a LinearOperator')
        if A.shape[1] != B.shape[0]:
            raise ValueError('cannot multiply %r and %r: shape mismatch'
                             % (A, B))
        super(_ProductLinearOperator, self).__init__(_get_dtype([A, B]),
                                                     (A.shape[0], B.shape[1]))
        self.args = (A, B)

    def _matvec(self, x):
        return self.args[0].matvec(self.args[1].matvec(x))

    def _rmatvec(self, x):
        return self.args[1].rmatvec(self.args[0].rmatvec(x))

    def _matmat(self, x):
        return self.args[0].matmat(self.args[1].matmat(x))

    def _adjoint(self):
        A, B = self.args
        return B.H * A.H

class _ScaledLinearOperator(LinearOperator):
    def __init__(self, A, alpha):
        if not isinstance(A, LinearOperator):
            raise ValueError('LinearOperator expected as A')
        if not np.isscalar(alpha):
            raise ValueError('scalar expected as alpha')
        dtype = _get_dtype([A], [type(alpha)])
        super(_ScaledLinearOperator, self).__init__(dtype, A.shape)
        self.args = (A, alpha)

    def _matvec(self, x):
        return self.args[1] * self.args[0].matvec(x)

    def _rmatvec(self, x):
        return np.conj(self.args[1]) * self.args[0].rmatvec(x)

    def _matmat(self, x):
        return self.args[1] * self.args[0].matmat(x)

    def _adjoint(self):
        A, alpha = self.args
        return A.H * alpha

class _PowerLinearOperator(LinearOperator):
    def __init__(self, A, p):
        if not isinstance(A, LinearOperator):
            raise ValueError('LinearOperator expected as A')
        if A.shape[0] != A.shape[1]:
            raise ValueError('square LinearOperator expected, got %r' % A)
        if not isintlike(p):
            raise ValueError('integer expected as p')

        super(_PowerLinearOperator, self).__init__(_get_dtype([A]), A.shape)
        self.args = (A, p)

    def _power(self, fun, x):
        res = np.array(x, copy=True)
        for i in range(self.args[1]):
            res = fun(res)
        return res

    def _matvec(self, x):
        return self._power(self.args[0].matvec, x)

    def _rmatvec(self, x):
        return self._power(self.args[0].rmatvec, x)

    def _matmat(self, x):
        return self._power(self.args[0].matmat, x)

    def _adjoint(self):
        A, p = self.args
        return A.H ** p

class MatrixLinearOperator(LinearOperator):
    def __init__(self, A):
        super(MatrixLinearOperator, self).__init__(A.dtype, A.shape)
        self.A = A
        self.__adj = None
        self.args = (A,)

    def _matmat(self, X):
        return self.A.dot(X)

    def _adjoint(self):
        if self.__adj is None:
            self.__adj = _AdjointMatrixOperator(self)
        return self.__adj

class _AdjointMatrixOperator(MatrixLinearOperator):
    def __init__(self, adjoint):
        self.A = adjoint.A.T.conj()
        self.__adjoint = adjoint
        self.args = (adjoint,)
        self.shape = adjoint.shape[1], adjoint.shape[0]

    @property
    def dtype(self):
        return self.__adjoint.dtype

    def _adjoint(self):
        return self.__adjoint

class IdentityOperator(LinearOperator):
    def __init__(self, shape, dtype=None):
        super(IdentityOperator, self).__init__(dtype, shape)

    def _matvec(self, x):
        return x

    def _rmatvec(self, x):
        return x

    def _matmat(self, x):
        return x

    def _adjoint(self):
        return self

def aslinearoperator(A):
    """Return A as a LinearOperator.

    'A' may be any of the following types:
     - ndarray
     - matrix
     - sparse matrix (e.g. csr_matrix, lil_matrix, etc.)
     - LinearOperator
     - An object with .shape and .matvec attributes

    See the LinearOperator documentation for additional information.

    Examples
    --------
    >>> from scipy.sparse.linalg import aslinearoperator
    >>> M = np.array([[1,2,3],[4,5,6]], dtype=np.int32)
    >>> aslinearoperator(M)
    <2x3 MatrixLinearOperator with dtype=int32>

    """
    if isinstance(A, LinearOperator):
        return A

    elif isinstance(A, np.ndarray) or isinstance(A, np.matrix):
        if A.ndim > 2:
            raise ValueError('array must have ndim <= 2')
        A = np.atleast_2d(np.asarray(A))
        return MatrixLinearOperator(A)

    elif isspmatrix(A):
        return MatrixLinearOperator(A)

    else:
        if hasattr(A, 'shape') and hasattr(A, 'matvec'):
            rmatvec = None
            dtype = None

            if hasattr(A, 'rmatvec'):
                rmatvec = A.rmatvec
            if hasattr(A, 'dtype'):
                dtype = A.dtype
            return LinearOperator(A.shape, A.matvec,
                                  rmatvec=rmatvec, dtype=dtype)

        else:
            raise TypeError('type not understood')


text:
/* eslint-env mocha */

'use strict'

const testUtil = require('./_util/testUtil')
const stack = require('../lib/_private/stack')
const common = require('./PromiseContractCommon')
const PromiseContract = require('../lib/PromiseContract')
const abstractContractCommon = require('./AbstractContractCommon')
const AbstractContract = require('../lib/AbstractContract')
const Contract = require('../lib/Contract')

function expectConstructorPost (pre, post, exception, fastException, location, result) {
  // noinspection JSUnresolvedFunction
  common.expectConstructorPost(pre, post, exception, location, result)
  // noinspection JSUnresolvedFunction
  common.expectArrayPost(result, fastException, 'fastException', '_fastException')
}

describe('PromiseContract', function () {
  describe('PromiseContract', function () {
    it('has the expected properties', function () {
      PromiseContract.should.have.ownProperty('prototype')
      // noinspection JSUnresolvedVariable
      abstractContractCommon.expectInvariants(PromiseContract.prototype)
      // noinspection JSUnresolvedVariable
      PromiseContract.prototype.implementation.should.be.a.Function()
      PromiseContract.should.have.ownProperty('root')
      // noinspection JSUnresolvedVariable
      PromiseContract.root.should.equal(AbstractContract.root)
      PromiseContract.should.have.ownProperty('isAContractFunction')
      // noinspection JSUnresolvedVariable
      PromiseContract.isAContractFunction.should.equal(AbstractContract.isAContractFunction)
      PromiseContract.falseCondition.should.equal(AbstractContract.falseCondition)
      PromiseContract.mustNotHappen.should.equal(AbstractContract.mustNotHappen)
      PromiseContract.outcome.should.equal(AbstractContract.outcome)
      PromiseContract.callee.should.equal(AbstractContract.callee)
    })
  })

  describe('#PromiseContract()', function () {
    // noinspection JSUnresolvedVariable
    common.constructorPreCases.forEach(pre => {
      // noinspection JSUnresolvedVariable
      common.constructorPostCases.forEach(post => {
        // noinspection JSUnresolvedVariable
        common.constructorExceptionCases.forEach(exception => {
          // noinspection JSUnresolvedVariable
          common.constructorExceptionCases.forEach(fastException => {
            it(
              'works for pre: ' +
                pre +
                ', post: ' +
                post +
                ', exception: ' +
                exception +
                ', fastException: ' +
                fastException,
              function () {
                const preConditions = pre()
                const postConditions = post()
                const exceptionConditions = exception()
                const fastExceptionConditions = fastException()
                const result = new PromiseContract({
                  pre: preConditions,
                  post: postConditions,
                  fastException: fastExceptionConditions,
                  exception: exceptionConditions
                })
                // noinspection JSUnresolvedFunction
                expectConstructorPost(
                  preConditions,
                  postConditions,
                  exceptionConditions,
                  fastExceptionConditions,
                  stack.location(),
                  result
                )
              }
            )
          })
        })
      })
    })
  })

  common.generateConstructorMethodsDescriptions(PromiseContract)

  // noinspection JSUnresolvedVariable
  common.generatePrototypeMethodsDescriptions(
    () => new PromiseContract({}),
    testUtil
      .x(
        common.constructorPreCases,
        common.constructorPostCases,
        common.constructorExceptionCases,
        common.constructorExceptionCases
      )
      .map(parameters => ({
        subject: () =>
          new PromiseContract({
            pre: parameters[0](),
            post: parameters[1](),
            fastException: parameters[2](),
            exception: parameters[3]()
          }),
        description: parameters.join(' - ')
      }))
  )

  describe('@isAContractFunction specific', function () {
    it('does not accept a Contract', function () {
      const contract = new Contract({})
      const contractFunction = contract.implementation(() => {})
      const result = PromiseContract.isAContractFunction(contractFunction)
      result.should.be.false()
    })
  })
})


text:
package org.codehaus.groovy.runtime;

import groovy.lang.Closure;

/**
 * A wrapper for Closure to support currying.
 * Normally used only internally through the curry(), rcurry() or
 * ncurry() methods on Closure.
 * Typical usages:
 *

 * // normal usage
 * def unitAdder = { first, second, unit -> "${first + second} $unit" }
 * assert unitAdder(10, 15, "minutes") == "25 minutes"
 * assert unitAdder.curry(60)(15, "minutes") == "75 minutes"
 * def minuteAdder = unitAdder.rcurry("minutes")
 * assert minuteAdder(15, 60) == "75 minutes"
 *
 * // explicit creation
 * import org.codehaus.groovy.runtime.CurriedClosure
 * assert new CurriedClosure(unitAdder, 45)(15, "minutes") == "60 minutes"
 * assert new CurriedClosure(unitAdder, "six", "ty")("minutes") == "sixty minutes"
 *

 *
 * @author Jochen Theodorou
 * @author Paul King
 */
public final class CurriedClosure<V> extends Closure<V> {

    private Object[] curriedParams;
    private int index;
    private int numTrailingArgs = 0;
    private Class varargType = null;

    public CurriedClosure(int index, Closure<V> uncurriedClosure, Object... arguments) {
        super(uncurriedClosure.clone());
        curriedParams = arguments;
        this.index = index;
        final int origMaxLen = uncurriedClosure.getMaximumNumberOfParameters();
        maximumNumberOfParameters = origMaxLen - arguments.length;
        Class[] classes = uncurriedClosure.getParameterTypes();
        Class lastType = classes.length == 0 ? null : classes[classes.length-1];
        if (lastType != null && lastType.isArray()) {
            varargType = lastType;
        }

        if (isVararg()) {
            if (index < 0) {
                numTrailingArgs = (-index) - arguments.length;
            }
        } else {
            // perform some early param checking for non-vararg case
            if (index < 0) {
                // normalise
                this.index += origMaxLen;
            }
            if (maximumNumberOfParameters < 0) {
                throw new IllegalArgumentException("Can't curry " + arguments.length + " arguments for a closure with " + origMaxLen + " parameters.");
            }
            if (index < 0) {
                if (index < -origMaxLen || index > -arguments.length)
                    throw new IllegalArgumentException("To curry " + arguments.length + " argument(s) expect index range " +
                            (-origMaxLen) + ".." + (-arguments.length) + " but found " + index);
            } else if (index > maximumNumberOfParameters) {
                throw new IllegalArgumentException("To curry " + arguments.length + " argument(s) expect index range 0.." +
                        maximumNumberOfParameters + " but found " + index);
            }
        }
    }

    public CurriedClosure(Closure<V> uncurriedClosure, Object... arguments) {
        this(0, uncurriedClosure, arguments);
    }

    public Object[] getUncurriedArguments(Object... arguments) {
        if (isVararg()) {
            int normalizedIndex = index < 0 ? index + arguments.length + curriedParams.length : index;
            if (normalizedIndex < 0 || normalizedIndex > arguments.length) {
                throw new IllegalArgumentException("When currying expected index range between " +
                        (-arguments.length - curriedParams.length) + ".." + (arguments.length + curriedParams.length) + " but found " + index);
            }
            final Object newCurriedParams[] = new Object[curriedParams.length + arguments.length];
            System.arraycopy(arguments, 0, newCurriedParams, 0, normalizedIndex);
            System.arraycopy(curriedParams, 0, newCurriedParams, normalizedIndex, curriedParams.length);
            if (arguments.length - normalizedIndex > 0)
                System.arraycopy(arguments, normalizedIndex, newCurriedParams, curriedParams.length + normalizedIndex, arguments.length - normalizedIndex);
            return newCurriedParams;
        }
        final Object newCurriedParams[] = new Object[curriedParams.length + arguments.length];
        int newIndex = Math.min(index, curriedParams.length + arguments.length - 1);
        System.arraycopy(arguments, 0, newCurriedParams, 0, newIndex);
        System.arraycopy(curriedParams, 0, newCurriedParams, newIndex, curriedParams.length);
        if (arguments.length - newIndex > 0)
            System.arraycopy(arguments, newIndex, newCurriedParams, curriedParams.length + newIndex, arguments.length - newIndex);
        return newCurriedParams;
    }

    public void setDelegate(Object delegate) {
        ((Closure) getOwner()).setDelegate(delegate);
    }

    public Object getDelegate() {
        return ((Closure) getOwner()).getDelegate();
    }

    public void setResolveStrategy(int resolveStrategy) {
        ((Closure) getOwner()).setResolveStrategy(resolveStrategy);
    }

    public int getResolveStrategy() {
        return ((Closure) getOwner()).getResolveStrategy();
    }

    @SuppressWarnings("unchecked")
    public Object clone() {
        Closure<V> uncurriedClosure = (Closure<V>) ((Closure) getOwner()).clone();
        return new CurriedClosure<V>(index, uncurriedClosure, curriedParams);
    }

    public Class[] getParameterTypes() {
        Class[] oldParams = ((Closure) getOwner()).getParameterTypes();
        int extraParams = 0;
        int gobbledParams = curriedParams.length;
        if (isVararg()) {
            int numNonVarargs = oldParams.length - 1;
            if (index < 0) {
                int absIndex = index < 0 ? -index : index;
                // do -ve indexes based on actual args, so can't accurately calculate type here
                // so work out minimal type params and vararg on end will allow for other possibilities
                if (absIndex > numNonVarargs) gobbledParams = numNonVarargs;
                int newNumNonVarargs = numNonVarargs - gobbledParams;
                if (absIndex - curriedParams.length > newNumNonVarargs) extraParams = absIndex - curriedParams.length - newNumNonVarargs;
                int keptParams = Math.max(numNonVarargs - absIndex, 0);
                Class[] newParams = new Class[keptParams + newNumNonVarargs + extraParams + 1];
                System.arraycopy(oldParams, 0, newParams, 0, keptParams);
                for (int i = 0; i < newNumNonVarargs; i++) newParams[keptParams + i] = Object.class;
                for (int i = 0; i < extraParams; i++) newParams[keptParams + newNumNonVarargs + i] = varargType.getComponentType();
                newParams[newParams.length - 1] = varargType;
                return newParams;
            }
            int leadingKept = Math.min(index, numNonVarargs);
            int trailingKept = Math.max(numNonVarargs - leadingKept - curriedParams.length, 0);
            if (index > leadingKept) extraParams = index - leadingKept;
            Class[] newParams = new Class[leadingKept + trailingKept + extraParams + 1];
            System.arraycopy(oldParams, 0, newParams, 0, leadingKept);
            if (trailingKept > 0) System.arraycopy(oldParams, leadingKept + curriedParams.length, newParams, leadingKept, trailingKept);
            for (int i = 0; i < extraParams; i++) newParams[leadingKept + trailingKept + i] = varargType.getComponentType();
            newParams[newParams.length - 1] = varargType;
            return newParams;
        }
        Class[] newParams = new Class[oldParams.length - gobbledParams + extraParams];
        System.arraycopy(oldParams, 0, newParams, 0, index);
        if (newParams.length - index > 0)
            System.arraycopy(oldParams, curriedParams.length + index, newParams, index, newParams.length - index);
        return newParams;
    }

    private boolean isVararg() {
        return varargType != null;
    }
}


text:
package com.mobimvp.privacybox.ui.browser;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mobimvp.privacybox.R;
import com.mobimvp.privacybox.utility.BitmapUtility;
import com.mobimvp.privacybox.utility.ImageWorker;
import com.mobimvp.privacybox.utility.SystemInfo;

public class MediaBrowserAdapter extends BaseAdapter {
	private static final int MSG_NEW_FOLDER = 0;

	private static final int THUMBNAIL_SIZE = 128;

	public static enum MediaType {
		Video, Image
	}

	public static enum BrowseMode {
		FolderList, FileList
	}

	private static class BrowserItemHolder {
		public ImageView thumbnail;
		public RelativeLayout container;
		public LinearLayout folderInfo;
		public TextView folderName;
		public TextView fileCount;
		public ImageView videoIndicator;
		public CheckBox selected;
		public TextView fileName;
	}

	private static class MediaFolder {
		public File folder;
		public ArrayList<File> mediaFileList;
	}

	private class MediaScannerThread extends Thread {

		private boolean pendingExit;
		private ConditionVariable cv;
		private File root;

		public MediaScannerThread(File root) {
			cv = new ConditionVariable();
			cv.open();
			this.root = root;
		}

		public void exit() {
			pendingExit = true;
		}

		public void pauseScan() {
			cv.close();
		}

		public void resumeScan() {
			cv.open();
		}

		@Override
		public void run() {
			LinkedList<String> pendingList = new LinkedList<String>();
			pendingList.add(root.getAbsolutePath());

			while (pendingList.size() > 0 && !pendingExit) {
				try {
					cv.block();
				} catch (Exception e) {
				}

				if (pendingExit) {
					break;
				}

				File folder = new File(pendingList.removeFirst());
				if (!folder.exists() || !folder.isDirectory()) {
					continue;
				}
				if (folder.getName().startsWith(".")) {
					continue;
				}
				if (new File(folder, ".nomedia").exists()) {
					continue;
				}

				String[][] list = SystemInfo.listFiles(folder.getAbsolutePath());
				if (list == null || list.length != 2) {
					continue;
				}

				if (list[0] != null) {
					for (int i=0; i<list[0].length; i++) {
						pendingList.add(list[0][i]);
					}
				}

				ArrayList<File> fileList = new ArrayList<File>();

				if (list[1] != null) {
					for (int i=0; i<list[1].length; i++) {
						String fileName = list[1][i];
						String fileExt = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
						if (extSet.contains(fileExt)) {
							fileList.add(new File(fileName));
						}
					}
				}

				if (fileList.size() > 0) {
					MediaFolder mf = new MediaFolder();
					mf.folder = folder;
					mf.mediaFileList = fileList;
					mUIHandler.obtainMessage(MSG_NEW_FOLDER, mf).sendToTarget();
				}
			}
			if (mListener != null) {
				mListener.OnScanFinished(pendingExit);
			}
		}
	};

	private Handler mUIHandler = new Handler(Looper.getMainLooper()) {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_NEW_FOLDER:
				folderList.add((MediaFolder) msg.obj);
				notifyDataSetChanged();
				break;
			}
		}
	};

	private class ThumbLoader extends ImageWorker {

		public ThumbLoader() {
			super(mContext);
		}

		@Override
		protected Bitmap processBitmap(Object data) {
			try {
				File file = (File)data;
				if (mType == MediaType.Image) {
					return BitmapUtility.createThumbnail(file, THUMBNAIL_SIZE);
				} else if (mType == MediaType.Video) {
					return BitmapUtility.createVideoThumb(file);
				} else {
					return null;
				}
			} catch (Exception e) {
				return null;
			}
		}
	}

	private HashSet<String> extSet;

	private Context mContext;
	private LayoutInflater mInflater;
	private ThumbLoader mThumbLoader;
	private MediaScannerThread mScanThread;
	private MediaType mType;
	private BrowseMode mMode;

	private MediaBrowserListener mListener;
	private ArrayList<MediaFolder> folderList;
	private MediaFolder currentFolder;
	private HashSet<File> selectedFileList;
	private File root;

	public MediaBrowserAdapter(Context context, MediaType type, File sdRoot) {
		root = sdRoot;
		mContext = context;
		extSet = new HashSet<String>();
		mInflater = LayoutInflater.from(mContext);

		mType = type;

		String[] extList;
		if (type == MediaType.Image) {
			extList = mContext.getResources().getStringArray(R.array.imgsuffix);
		} else if (type == MediaType.Video) {
			extList = mContext.getResources().getStringArray(R.array.videosuffix);
		} else {
			extList = new String[0];
		}

		for (int i=0; i<extList.length; i++) {
			extSet.add(extList[i]);
		}

		mMode = BrowseMode.FolderList;
		folderList = new ArrayList<MediaFolder>();
		currentFolder = null;
		selectedFileList = new HashSet<File>();
		mThumbLoader = new ThumbLoader();
		mScanThread = new MediaScannerThread(sdRoot);
	}

	public void recycle() {
		mScanThread.exit();
		mThumbLoader.recycle();
	}

	public void startScan() {
		mScanThread.start();
		if (mListener != null) {
			mListener.OnBrowse(mMode, null);
		}
	}

	public void stopScan() {
		System.out.println("mScanThread:stop");
		mScanThread.exit();
	}

	public void setBrowserListener(MediaBrowserListener listener) {
		mListener = listener;
	}

	public void select(int position) {
		if (mMode == BrowseMode.FolderList) {
			mMode = BrowseMode.FileList;
			currentFolder = folderList.get(position);
			selectedFileList.clear();

			mScanThread.pauseScan();

			notifyDataSetChanged();

			if (mListener != null) {
				mListener.OnBrowse(mMode, currentFolder.folder);
			}
		} else {
			File file = currentFolder.mediaFileList.get(position);
			if (selectedFileList.contains(file)) {
				selectedFileList.remove(file);
			} else {
				selectedFileList.add(file);
			}
		}
		notifyDataSetChanged();
	}

	public BrowseMode getMode() {
		return mMode;
	}

	public void exitFileListMode() {
		currentFolder = null;
		mMode = BrowseMode.FolderList;

		mScanThread.resumeScan();
		notifyDataSetChanged();

		if (mListener != null) {
			mListener.OnBrowse(mMode, null);
		}
	}

	public File getCurrentFolder() {
		if (mMode == BrowseMode.FolderList) {
			return root;
		} else {
			return currentFolder.folder;
		}
	}

	public ArrayList<String> getSelectedFiles() {
		ArrayList<String> result = new ArrayList<String>();
		if (mMode == BrowseMode.FileList) {
			for (File file : selectedFileList) {
				result.add(file.getAbsolutePath());
			}
		}

		return result;
	}

	public void selectAll() {
		if (mMode == BrowseMode.FileList) {
			if (selectedFileList.size() < currentFolder.mediaFileList.size()) {
				selectedFileList.addAll(currentFolder.mediaFileList);
			} else {
				selectedFileList.clear();
			}

			notifyDataSetChanged();
		}
	}

	@Override
	public int getCount() {
		if (mMode == BrowseMode.FolderList) {
			return folderList.size();
		} else {
			return currentFolder.mediaFileList.size();
		}
	}

	@Override
	public Object getItem(int position) {
		if (mMode == BrowseMode.FolderList) {
			return folderList.get(position);
		} else {
			return currentFolder.mediaFileList.get(position);
		}
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		BrowserItemHolder holder;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.mediabrowser_item, null);
			holder = new BrowserItemHolder();
			holder.thumbnail = (ImageView) convertView.findViewById(R.id.thumbnail);
			holder.container = (RelativeLayout) convertView.findViewById(R.id.thumbnail_container);
			holder.folderInfo = (LinearLayout) convertView.findViewById(R.id.folderinfo);
			holder.folderName = (TextView) convertView.findViewById(R.id.name);
			holder.fileCount = (TextView) convertView.findViewById(R.id.filecount);
			holder.videoIndicator = (ImageView) convertView.findViewById(R.id.video);
			holder.selected = (CheckBox) convertView.findViewById(R.id.selected);
			holder.fileName = (TextView) convertView.findViewById(R.id.filename);
			convertView.setTag(holder);
		} else {
			holder = (BrowserItemHolder) convertView.getTag();
		}
		if (mMode == BrowseMode.FolderList) {
			MediaFolder folder = folderList.get(position);
			holder.fileName.setVisibility(View.GONE);
			holder.selected.setVisibility(View.GONE);
			holder.folderInfo.setVisibility(View.VISIBLE);
			holder.container.setBackgroundResource(R.drawable.ic_folder_background);
			holder.folderName.setText(folder.folder.getName());
			holder.fileCount.setText(Integer.toString(folder.mediaFileList.size()));
			mThumbLoader.loadImage(folder.mediaFileList.get(0), holder.thumbnail);
		} else {
			File file = currentFolder.mediaFileList.get(position);
			holder.fileName.setVisibility(View.VISIBLE);
			holder.selected.setVisibility(View.VISIBLE);
			holder.folderInfo.setVisibility(View.GONE);
			holder.container.setBackgroundResource(R.drawable.ic_media_background);

			holder.fileName.setText(file.getName());
			holder.selected.setChecked(selectedFileList.contains(file));
			mThumbLoader.loadImage(file, holder.thumbnail);
		}

		if (mType == MediaType.Video) {
			holder.videoIndicator.setVisibility(View.VISIBLE);
		} else {
			holder.videoIndicator.setVisibility(View.GONE);
		}

		return convertView;
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title></title>
<#include "/jeecms_sys/head.html"/>

<@s.m "global.position"/>: <@s.m "cmsMessage.function"/> - <@s.m "cmsMessage.trashbox"/>

	<#include "inc_opt.html"/>

<form id="tableForm" method="post">
<input type="hidden" name="pageNo" value="${pageNo!}"/>
<input type="hidden" name="box" value="${box!}"/>
<input type="hidden" name="msg" value="<@s.m "cmsMessage.msg"/>"/>
<@p.table value=pagination;message,i,has_next><#rt/>
	<@p.column title="<input type='checkbox' onclick='Pn.checkbox(\"ids\",this.checked)'/>" width="20">
		<input type='checkbox' name='ids' value='${message.id}' id="id_${message.id!}" onclick="Pn.selectCheckBox('${message.id}',this.checked)"/><#t/>
	</@p.column><#t/>
	<@p.column title="ID">${message.id}</@p.column><#t/>
	<@p.column code="cmsMessage.title">
		<#if message.msgStatus>
			<@text_cut s=message.titleHtml len='15' append='...'/>
		<#else>
			<@text_cut s=message.titleHtml len='15' append='...'/>
		</#if>
	</@p.column><#t/>
	<@p.column code="cmsMessage.sendUser" align="center">${message.msgSendUser.username!}</@p.column><#t/>
	<@p.column code="cmsMessage.receiverUser" align="center">${message.msgReceiverUser.username!}</@p.column><#t/>
	<#if message.sendTime??>
		<@p.column code="cmsMessage.sendTime" align="center">${message.sendTime?string('yyyy-MM-dd HH:mm:ss')}</@p.column><#t/>
	<#else>
		<@p.column code="cmsMessage.sendTime" align="center"></@p.column><#t/>
	</#if>
</@p.table>

<input class="recycle" type="button" onclick="revert()" value="<@s.m "cmsMessage.revert"/>"/>
<input class="delete-complete" type="button" onclick="empty()" value="<@s.m "cmsMessage.trash"/>"/>

</form>

<#include "/common/alert_message.html"/>


text:
package test

import (
	"bytes"
	"github.com/GochoMugo/getme/lib"
	"io/ioutil"
	"os"
	"path"
	"testing"
)

func TestFetch(t *testing.T) {
  actualUrl := "https://raw.githubusercontent.com/GochoMugo/getme/master/LICENSE"
  bogusUrl := "https://raw.githubusercontent.com/GochoMugo/getme/master/index.js"

  _, err := lib.Fetch(actualUrl)
  if err != nil {
    t.Errorf("Error dowloading from URL")
    return
  }

  _, err = lib.Fetch(bogusUrl)
  if err == nil {
    t.Errorf("Error not thrown on a bogus url")
  }
}

func TestDownloadFromGithub(t *testing.T) {
	shorthand := "GochoMugo/getme"
	branch := "master"
	filePath := "LICENSE"
	cwd, _ := os.Getwd()

	content, err := lib.DownloadFromGithub(shorthand, branch, filePath)
	if err != nil {
		t.Errorf("Error downloading from github: %s", err)
		return
	}
	realcontent, err := ioutil.ReadFile(path.Join(cwd, "..", "LICENSE"))
	if err != nil {
		t.Errorf("internal error: %s", err)
		return
	}
	if bytes.Compare(content, realcontent) != 0 {
		t.Errorf("content downloaded does not seem right")
		return
	}

  _, err = lib.DownloadFromGithub(shorthand, branch, "missing")
  if err == nil {
    t.Errorf("error is not thrown for missing file from remote")
  }
}


text:
<?php

class ZeroFormatTest extends NumeralTestCase
{

    public function testYouCanSetAZeroFormat()
    {
        $this->numeral->setZeroFormat('A format');
        $this->assertEquals('A format', $this->numeral->getZeroFormat());
    }

    public function testZeroFormatIsReturnedOnZero()
    {
        $this->numeral->setZeroFormat('TestFormat');
        $value = $this->numeral->format(0, '');
        $this->assertEquals('TestFormat', $value);
    }

    public function testZeroFormatCanBeReset()
    {
        $this->numeral->setZeroFormat('TestFormat');
        $value = $this->numeral->format(0, '');
        $this->assertEquals('TestFormat', $value);
        $this->numeral->setZeroFormat(null);
        $value = $this->numeral->format(0, '');
        $this->assertEquals(0, $value);
    }

}


text:
package simulator;

import basestation.BaseStation;
import com.google.gson.*;
import org.jbox2d.callbacks.QueryCallback;
import org.jbox2d.collision.AABB;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Fixture;
import org.jbox2d.dynamics.World;
import simulator.baseinterface.SimulatorVisionSystem;
import simulator.physics.PhysicalObject;
import simulator.simbot.ShortestPathGenerator;
import simulator.simbot.SimBot;
import simulator.simbot.SimBotConnection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class Simulator {

    public static final float UPDATES_PER_SECOND = 30;
    /**
     * For protecting the world
     */
    private final Object worldLock = new Object();
    private int[][] occupancyMatrix;
    private Set<PhysicalObject> physicalObjectSet;
    private World world;
    private SimulatorVisionSystem visionSystem;
    private SimRunner simRunner;
    private long lastUpdateTime;

    public Simulator() {
        visionSystem = SimulatorVisionSystem.getInstance();
        world = new World(new Vec2(0f, 0f));
        physicalObjectSet = ConcurrentHashMap.newKeySet();
        lastUpdateTime = System.nanoTime();
        SimRunner sr = new SimRunner();
        sr.start();
    }

    /**
     * @return the vision system that is tied to the simulator
     */
    public SimulatorVisionSystem getVisionSystem() {
        return visionSystem;
    }

    /**
     * @return the JBox2D world that the simulation is running in
     */
    public World getWorld() {
        return world;
    }

    /**
     * This is called when a new scenario is added (starting a new simulation
     * based on the scenario)
     * <p>
     * Resets the simulation by creating a new world, resetting all physical
     * objects and vision objcts, and starting a new simulation
     */
    public void resetWorld() {
        // cleanup previous state
        if (world != null) {
            synchronized (worldLock) {
                for (PhysicalObject physicalObject : physicalObjectSet) {
                    world.destroyBody(physicalObject.getBody());
                }
            }
        }
        if (simRunner != null) {
            simRunner.setShouldStep(false);
            while (simRunner.isGoing()) {
                try {
                    Thread.sleep(0, 1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        physicalObjectSet.clear();
        world = new World(new Vec2(0f, 0f));
        physicalObjectSet = ConcurrentHashMap.newKeySet();
        lastUpdateTime = System.nanoTime();
        visionSystem.resetWorld();

        simRunner = new SimRunner();
        simRunner.start();
    }

    /**
     * A single step of the simulation- updates JBox2D world, updates all the
     * physical objects in the world, and updates all the corresponding
     * vision objects in the vision system
     */
    public void stepSimulation() {
        synchronized (worldLock) {
            long now = System.nanoTime();
            long delta = now - lastUpdateTime;
            lastUpdateTime = now;
            float timeStep = (float) (delta / 10e8);
            int velocityIterations = 6;
            int positionIterations = 4;
            world.step(timeStep, velocityIterations, positionIterations);
        }

        visionSystem.updateVisionCoordinates(physicalObjectSet);
    }

    public boolean importScenario(Gson gson, JsonParser jsonParser, JsonObject scenario) {
        // clear previous
        resetWorld();
        String scenarioBody = scenario.get("scenario").getAsString();
        JsonArray addInfo = jsonParser.parse(scenarioBody).getAsJsonArray();

        synchronized (worldLock) {
            for (JsonElement je : addInfo) {
                String type = je.getAsJsonObject().get("type").getAsString();
                int angle = je.getAsJsonObject().get("angle").getAsInt();
                int[] position = gson.fromJson(je.getAsJsonObject().get("position")
                        .getAsString(), int[].class);
                String name = Integer.toString(angle)
                        + Arrays.toString(position);

                //for scenario obstacles
                PhysicalObject physicalObject;
                if (!type.equals("simulator.simbot")) {
                    int size = je.getAsJsonObject().get("size").getAsInt();
                    physicalObject = new PhysicalObject(name, 100,
                            world, (float) position[0],
                            (float) position[1], size, angle);
                    importPhysicalObject(physicalObject);
                }
                //for bots listed in scenario
                else {
                    if (addSimBot("Simbot" + name, position[0], position[1],
                            angle) == null) {
                        return false;
                    }
                }
            }
        }

        return true;
    }

    public SimBot addSimBot(String name, float x, float y, float angle) {
        synchronized (worldLock) {
            SimBotConnection sbc = new SimBotConnection();
            SimBot simBot = new SimBot(sbc, this, name, 50, world, 0.0f,
                    0.0f, x,
                    y, angle, true);

            PhysicalObject physicalObject = simBot.getMyPhysicalObject();
            importPhysicalObject(physicalObject);

            try {
                BaseStation.getInstance().getBotManager().addBot(simBot);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }

            return simBot;
        }
    }

    /**
     * Adds pObj to the simulation for vision tracking
     */
    public void importPhysicalObject(PhysicalObject pObj) {
        physicalObjectSet.add(pObj);
    }

    /**
     * @returns 2D occupancy matrix of the simulator
     */
    public int[][] getOccupancyMatrix() {
        return occupancyMatrix;
    }

    /**
     * Sets the simulator's occupancy matrix
     *
     * @param om, a 2D occupancy matrix
     */
    public void setOccupancyMatrix(int[][] om) {
        occupancyMatrix = om;
    }

    /**
     * Returns the corner points of a path. In other words, where the path turns
     *
     * @param om, the path of a 2d occupancy matrix
     * @returns an ArrayList of points
     */
    public ArrayList<ArrayList<Integer>> getWayPoints(int[][] om) {
        ArrayList<ArrayList<Integer>> points = new ArrayList<ArrayList<Integer>>();
        for (int i = 1; i < om.length - 1; i++) {
            for (int j = 1; j < om[0].length - 1; j++) {
                if (om[i][j] == 1 &&
                        ((om[i - 1][j] == 1 && om[i][j + 1] == 1) || (om[i][j + 1] == 1 && om[i + 1][j] == 1))) {
                    points.get(0).add(i);
                    points.get(1).add(j);
                }
            }
        }
        return points;
    }

    /**
     * Queries the JBox2D world of the simulator, looking for squares in which a body is present.
     * A cel is a 1 if an object is present and 0 otherwise. Set the simulator occupancy matrix to be the result.
     *
     * @param occupancyMatrixHeight,  the height of the resulting occupancy matrix
     * @param occupancyMatrixWidth,   the width of the resulting occupancy
     * @param occupancyMatrixBoxSize, the size of the querying window
     */
    public void generateOccupancyMatrix(int occupancyMatrixHeight, int occupancyMatrixWidth, float occupancyMatrixBoxSize) {
        int[][] om = new int[occupancyMatrixHeight][occupancyMatrixWidth];
        boolean[] finishQuery = new boolean[1];
        final int height = occupancyMatrixHeight;
        final int width = occupancyMatrixWidth;
        AABBCBLock lock = new AABBCBLock((height * width));
        //System.out.println("The occupancy matrix box size is " + occupancyMatrixBoxSize);
        for (int i = 0; i < occupancyMatrixHeight; i++) {
            for (int j = 0; j < occupancyMatrixWidth; j++) {
                float lower_x = (float) (i * occupancyMatrixBoxSize);
                float lower_y = (float) (j * occupancyMatrixBoxSize);
                Vec2 lowerVertex = new Vec2(lower_x, lower_y);
                Vec2 upperVertex = new Vec2(lower_x + occupancyMatrixBoxSize, lower_y + occupancyMatrixBoxSize);
                AABB currentSquare = new AABB(lowerVertex, upperVertex);
                final Vec2 testpoint1 = new Vec2(lower_x + occupancyMatrixBoxSize / 2, lower_y + occupancyMatrixBoxSize / 2);
                final Vec2 testpoint2 = new Vec2(lower_x + occupancyMatrixBoxSize / 4, lower_y + occupancyMatrixBoxSize / 4);
                final Vec2 testpoint3 = new Vec2(lower_x + 3 * occupancyMatrixBoxSize / 4, lower_y + 3 * occupancyMatrixBoxSize / 4);
                final Vec2 testpoint4 = new Vec2(lower_x + occupancyMatrixBoxSize / 4, lower_y + 3 * occupancyMatrixBoxSize / 4);
                final Vec2 testpoint5 = new Vec2(lower_x + 3 * occupancyMatrixBoxSize / 4, lower_y + occupancyMatrixBoxSize / 4);

                final int icopy = i;
                final int jcopy = j;
                QueryCallback callback = new QueryCallback() {
                    @Override
                    public boolean reportFixture(Fixture fixture) {
                        if (fixture.testPoint(testpoint1) || fixture.testPoint(testpoint2) || fixture.testPoint(testpoint3) || fixture.testPoint(testpoint4) || fixture.testPoint(testpoint5)) {
                            om[icopy][jcopy] = 1;
                        }
                        lock.increment();

                        return true;
                    }
                };
                world.queryAABB(callback, currentSquare);
            }
        }
        //TODO, ensure that setOccupancyMatrix(om) is not called before the callback has completed
        while (lock.isDone()) {
        }
        setOccupancyMatrix(om);
    }

    /**
     * @return a matrix representation of the shortest path, where the 1's are nodes on the path
     */
    public int[][] getDijkstras() {
        ShortestPathGenerator.answer(occupancyMatrix);
        ShortestPathGenerator.Node targetNode = ShortestPathGenerator.targetNode;

        LinkedList<ShortestPathGenerator.Node> path = ShortestPathGenerator.getPath(targetNode);
        int[][] pathMatrix = new int[occupancyMatrix.length + 1][occupancyMatrix[0].length + 1];

        for (int i = 0; i < path.size(); i++) {
            //System.out.println("X:" + path.get(i).getX() + " Y:" + path.get(i).getY());
            pathMatrix[path.get(i).getX()][path.get(i).getY()] = 1;
        }

        return pathMatrix;
    }

    /**
     * Runs the simulations at the specified number of updates/second
     */
    private class SimRunner extends Thread {

        private final Object lock = new Object();
        private boolean shouldStep;
        private boolean going;

        boolean isShouldStep() {
            synchronized (lock) {
                return shouldStep;
            }
        }

        void setShouldStep(boolean update) {
            synchronized (lock) {
                this.shouldStep = update;
            }
        }

        boolean isGoing() {
            synchronized (lock) {
                return going;
            }
        }

        void setGoing(boolean update) {
            synchronized (lock) {
                this.going = update;
            }
        }

        @Override
        public void run() {
            setShouldStep(true);
            while (true) {
                if (!isShouldStep()) return;
                setGoing(true);
                stepSimulation();
                try {
                    Thread.sleep((long) (1000f / UPDATES_PER_SECOND));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    setGoing(false);
                }
            }
        }
    }

    /**
     * A lock object implementation used to ensure that the callbacks used when doing
     * AABB-querying have all completed before we return the occupancy matrix.
     */
    public class AABBCBLock {
        private Object lock;
        private int count;
        private int max;

        private AABBCBLock(int max) {
            this.max = max;
        }

        public void increment() {
            synchronized (lock) {
                count++;
            }
        }

        public boolean isDone() {
            synchronized (lock) {
                return count == max;
            }
        }
    }

}