text:
angular.module('baasic.blog')
    .directive('baasicBlogEdit', ['$parse',
        function baasicBlogList($parse) {
            'use strict';

            return {
                restrict: 'AE',
                scope: true,
                compile: function () {
                    return {
                        pre: function (scope, elem, attrs) {
                            if (attrs.blog) {
                                scope.$parent.$watch(attrs.blog, function (newValue) {
                                    scope.blog = newValue;
                                    scope.isNew = newValue === undefined || newValue === null;
                                });
                            }
                            if (attrs.onSave) {
                                scope.onSaveFn = $parse(attrs.onSave);
                            }

                            if (attrs.onCancel) {
                                scope.onCancelFn = $parse(attrs.onCancel);
                            }
                        }
                    };
                },
                controller: ['$scope', '$q', 'baasicBlogService', 'markdownConverter',
                    function baasicBlogEditCtrl($scope, $q, blogService, markdownConverter) {
                        function readingTime(text) {
                            var words = 0, start = 0, end = text.length - 1, i;

                            // fetch bounds
                            while (whitespace(text[start])) {
                                start++;
                            }
                            while (whitespace(text[end])) {
                                end--;
                            }

                            // there no words if bounds are equal
                            if (start === end) {
                                return null;
                            }

                            // calculates the number of words
                            for (i = start; i <= end;) {
                                for (; i <= end && !whitespace(text[i]) ; i++) {
                                    words++;
                                }
                                for (; i <= end && whitespace(text[i]) ; i++) {
                                }
                            }

                            // reading time stats
                            var minutes = words / 200;
                            var time = minutes * 60 * 1000;
                            var displayed = Math.ceil(minutes);

                            return {
                                text: displayed + ' min read',
                                time: time,
                                words: words
                            };
                        }

                        function whitespace(c) {
                            return (
                                (' ' === c) ||
                                ('\n' === c) ||
                                ('\t' === c)
                            );
                        }

                        $scope.isNew = true;

                        $scope.state = {
                            conentent: {
                                viewMode: 'markdown'
                            }
                        };

                        $scope.saveBlog = function saveBlog() {
                            if ($scope.blogPost.$valid) {
                                $scope.$root.loader.suspend();

                                $scope.blog.readingTime = readingTime($scope.blog.content);
                                $scope.blog.authorName = $scope.$root.user.displayName;

                                var promise;
                                if ($scope.isNew) {
                                    $scope.blog.status = blogService.blogStatus.published; // Publish blog
                                    promise = blogService.create($scope.blog);
                                } else {
                                    promise = blogService.update($scope.blog);
                                }

                                promise
                                    .success(function () {
                                        if ($scope.onSaveFn) {
                                            $scope.onSaveFn($scope.$parent);
                                        }
                                    })
                                    .error(function (error) {
                                        $scope.error = error.message;
                                    })
                                    .finally(function () {
                                        $scope.$root.loader.resume();
                                    });
                            }
                        };

                        $scope.cancelEdit = function cancelEdit() {
                            if ($scope.onCancelFn) {
                                $scope.onCancelFn($scope.$parent);
                            }
                        };

                        $scope.getHtml = function getHtml(content) {
                            return markdownConverter.makeHtml(content);
                        };

                        $scope.setViewMode = function setViewMode(mode) {
                            $scope.state.conentent.viewMode = mode;
                        };

                        $scope.loadTags = function loadTags(query) {
                            var deferred = $q.defer();

                            blogService.tags.find({
                                search: query
                            })
                                .success(function (tags) {
                                    deferred.resolve(tags.item);
                                })
                                .error(function () {
                                    deferred.reject();
                                });

                            return deferred.promise;
                        };
                    }
                ],
                templateUrl: 'templates/blog/blog-post-edit-form.html'
            };
        }
    ]
    );


text:
package org.hibernate.cache.redis.jpa.models;

import com.google.common.base.Objects;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.cache.redis.AbstractHibernateEntity;

import javax.persistence.*;

/**
 * @author sunghyouk.bae@gmail.com
 */
@Entity
@org.hibernate.annotations.Cache(region = "common", usage = CacheConcurrencyStrategy.READ_WRITE)
@Getter
@Setter
public class VersionedItem extends AbstractHibernateEntity {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  @Version
  private Long version;

  private String name;
  private String description;

  @Override
  public int hashCode() {
    return Objects.hashCode(name, version);
  }

  private static final long serialVersionUID = -8467548718319032093L;
}

redpajama_set_name: RedPajamaGithub


text:
{% extends "blog/base.html" %}

{% load i18n %}

{% block content %}

{% trans "About my blog. Contacts here." %}

{% block form %}

        <form method="POST" action="">
        {% csrf_token %}

            {% for field in form %}

{{ field.label }}{{ field }}

                {% for err in field.errors %}
                {{ err }}
                {% endfor %}

            {% endfor %}

        <input class="button" type="submit" value="{% trans "Send mail" %}">

{% trans "*Required fields are bold" %}

        </form>

{% endblock %}

{% endblock %}


text:
<?php

/**
 * Customer address entity resource model
 *
 * @category    Mage
 * @package     Mage_Customer
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Customer_Model_Resource_Address extends Mage_Eav_Model_Entity_Abstract
{
    /**
     * Resource initialization
     */
    protected function _construct()
    {
        $resource = Mage::getSingleton('core/resource');
        $this->setType('customer_address')->setConnection(
            $resource->getConnection('customer_read'),
            $resource->getConnection('customer_write')
        );
    }

    /**
     * Set default shipping to address
     *
     * @param Varien_Object $address
     * @return Mage_Customer_Model_Resource_Address
     */
    protected function _afterSave(Varien_Object $address)
    {
        if ($address->getIsCustomerSaveTransaction()) {
            return $this;
        }
        if ($address->getId() && ($address->getIsDefaultBilling() || $address->getIsDefaultShipping())) {
            $customer = Mage::getModel('customer/customer')
                ->load($address->getCustomerId());

            if ($address->getIsDefaultBilling()) {
                $customer->setDefaultBilling($address->getId());
            }
            if ($address->getIsDefaultShipping()) {
                $customer->setDefaultShipping($address->getId());
            }
            $customer->save();
        }
        return $this;
    }

    /**
     * Return customer id
     * @deprecated
     *
     * @param Mage_Customer_Model_Address $object
     * @return int
     */
    public function getCustomerId($object)
    {
        return $object->getData('customer_id') ? $object->getData('customer_id') : $object->getParentId();
    }

    /**
     * Set customer id
     * @deprecated
     *
     * @param Mage_Customer_Model_Address $object
     * @param int $id
     * @return Mage_Customer_Model_Address
     */
    public function setCustomerId($object, $id)
    {
        return $this;
    }
}


text:
<?php

// autoload_namespaces.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Psr\\Log\\' => array($vendorDir . '/psr/log'),
    'Instaphp' => array($baseDir . '/src'),
);


text:
local require = require

local version = require "syscall.freebsd.version".version

local errors = {
  PERM = "Operation not permitted",
  NOENT = "No such file or directory",
  SRCH = "No such process",
  INTR = "Interrupted system call",
  IO = "Input/output error",
  NXIO = "Device not configured",
  ["2BIG"] = "Argument list too long",
  NOEXEC = "Exec format error",
  BADF = "Bad file descriptor",
  CHILD = "No child processes",
  DEADLK = "Resource deadlock avoided",
  NOMEM = "Cannot allocate memory",
  ACCES = "Permission denied",
  FAULT = "Bad address",
  NOTBLK = "Block device required",
  BUSY = "Resource busy",
  EXIST = "File exists",
  XDEV = "Cross-device link",
  NODEV = "Operation not supported by device",
  NOTDIR = "Not a directory",
  ISDIR = "Is a directory",
  INVAL = "Invalid argument",
  NFILE = "Too many open files in system",
  MFILE = "Too many open files",
  NOTTY = "Inappropriate ioctl for device",
  TXTBSY = "Text file busy",
  FBIG = "File too large",
  NOSPC = "No space left on device",
  SPIPE = "Illegal seek",
  ROFS = "Read-only file system",
  MLINK = "Too many links",
  PIPE = "Broken pipe",
  DOM = "Numerical argument out of domain",
  RANGE = "Result too large",
  AGAIN = "Resource temporarily unavailable",
  INPROGRESS = "Operation now in progress",
  ALREADY = "Operation already in progress",
  NOTSOCK = "Socket operation on non-socket",
  DESTADDRREQ = "Destination address required",
  MSGSIZE = "Message too long",
  PROTOTYPE = "Protocol wrong type for socket",
  NOPROTOOPT = "Protocol not available",
  PROTONOSUPPORT = "Protocol not supported",
  SOCKTNOSUPPORT = "Socket type not supported",
  OPNOTSUPP = "Operation not supported",
  PFNOSUPPORT = "Protocol family not supported",
  AFNOSUPPORT = "Address family not supported by protocol family",
  ADDRINUSE = "Address already in use",
  ADDRNOTAVAIL = "Can't assign requested address",
  NETDOWN = "Network is down",
  NETUNREACH = "Network is unreachable",
  NETRESET = "Network dropped connection on reset",
  CONNABORTED = "Software caused connection abort",
  CONNRESET = "Connection reset by peer",
  NOBUFS = "No buffer space available",
  ISCONN = "Socket is already connected",
  NOTCONN = "Socket is not connected",
  SHUTDOWN = "Can't send after socket shutdown",
  TOOMANYREFS = "Too many references: can't splice",
  TIMEDOUT = "Operation timed out",
  CONNREFUSED = "Connection refused",
  LOOP = "Too many levels of symbolic links",
  NAMETOOLONG = "File name too long",
  HOSTDOWN = "Host is down",
  HOSTUNREACH = "No route to host",
  NOTEMPTY = "Directory not empty",
  PROCLIM = "Too many processes",
  USERS = "Too many users",
  DQUOT = "Disc quota exceeded",
  STALE = "Stale NFS file handle",
  REMOTE = "Too many levels of remote in path",
  BADRPC = "RPC struct is bad",
  RPCMISMATCH = "RPC version wrong",
  PROGUNAVAIL = "RPC prog. not avail",
  PROGMISMATCH = "Program version wrong",
  PROCUNAVAIL = "Bad procedure for program",
  NOLCK = "No locks available",
  NOSYS = "Function not implemented",
  FTYPE = "Inappropriate file type or format",
  AUTH = "Authentication error",
  NEEDAUTH = "Need authenticator",
  IDRM = "Identifier removed",
  NOMSG = "No message of desired type",
  OVERFLOW = "Value too large to be stored in data type",
  CANCELED = "Operation canceled",
  ILSEQ = "Illegal byte sequence",
  NOATTR = "Attribute not found",
  DOOFUS = "Programming error",
  BADMSG = "Bad message",
  MULTIHOP = "Multihop attempted",
  NOLINK = "Link has been severed",
  PROTO = "Protocol error",
  NOTCAPABLE = "Capabilities insufficient",
  CAPMODE = "Not permitted in capability mode",
}

if version >= 10 then
  errors.NOTRECOVERABLE = "State not recoverable"
  errors.OWNERDEAD = "Previous owner died"
end

return errors


text:
//** Introduction
// The functions in this file are designed to support self-test of cryptographic
// functions in the TPM. The TPM allows the user to decide whether to run self-test
// on a demand basis or to run all the self-tests before proceeding.
//
// The self-tests are controlled by a set of bit vectors. The
// 'g_untestedDecryptionAlgorithms' vector has a bit for each decryption algorithm
// that needs to be tested and 'g_untestedEncryptionAlgorithms' has a bit for
// each encryption algorithm that needs to be tested. Before an algorithm
// is used, the appropriate vector is checked (indexed using the algorithm ID).
// If the bit is 1, then the test function should be called.
//
// For more information, see TpmSelfTests.txt

#include "Tpm.h"

//** Functions

//*** RunSelfTest()
// Local function to run self-test
static TPM_RC
CryptRunSelfTests(
    ALGORITHM_VECTOR    *toTest         // IN: the vector of the algorithms to test
    )
{
    TPM_ALG_ID           alg;

    // For each of the algorithms that are in the toTestVecor, need to run a
    // test
    for(alg = TPM_ALG_FIRST; alg <= TPM_ALG_LAST; alg++)
    {
        if(TEST_BIT(alg, *toTest))
        {
            TPM_RC          result = CryptTestAlgorithm(alg, toTest);
            if(result != TPM_RC_SUCCESS)
                return result;
        }
    }
    return TPM_RC_SUCCESS;
}

//*** CryptSelfTest()
// This function is called to start/complete a full self-test.
// If 'fullTest' is NO, then only the untested algorithms will be run. If
// 'fullTest' is YES, then 'g_untestedDecryptionAlgorithms' is reinitialized and then
// all tests are run.
// This implementation of the reference design does not support processing outside
// the framework of a TPM command. As a consequence, this command does not
// complete until all tests are done. Since this can take a long time, the TPM
// will check after each test to see if the command is canceled. If so, then the
// TPM will returned TPM_RC_CANCELLED. To continue with the self-tests, call
// TPM2_SelfTest(fullTest == No) and the TPM will complete the testing.
//  Return Type: TPM_RC
//      TPM_RC_CANCELED        if the command is canceled
LIB_EXPORT
TPM_RC
CryptSelfTest(
    TPMI_YES_NO      fullTest       // IN: if full test is required
    )
{
#if SIMULATION
    if(g_forceFailureMode)
        FAIL(FATAL_ERROR_FORCED);
#endif

    // If the caller requested a full test, then reset the to test vector so that
    // all the tests will be run
    if(fullTest == YES)
    {
        MemoryCopy(g_toTest,
                   g_implementedAlgorithms,
                   sizeof(g_toTest));
    }
    return CryptRunSelfTests(&g_toTest);
}

//*** CryptIncrementalSelfTest()
// This function is used to perform an incremental self-test. This implementation
// will perform the toTest values before returning. That is, it assumes that the
// TPM cannot perform background tasks between commands.
//
// This command may be canceled. If it is, then there is no return result.
// However, this command can be run again and the incremental progress will not
// be lost.
//  Return Type: TPM_RC
//      TPM_RC_CANCELED         processing of this command was canceled
//      TPM_RC_TESTING          if toTest list is not empty
//      TPM_RC_VALUE            an algorithm in the toTest list is not implemented
TPM_RC
CryptIncrementalSelfTest(
    TPML_ALG            *toTest,        // IN: list of algorithms to be tested
    TPML_ALG            *toDoList       // OUT: list of algorithms needing test
    )
{
    ALGORITHM_VECTOR     toTestVector = {0};
    TPM_ALG_ID           alg;
    UINT32               i;

    pAssert(toTest != NULL && toDoList != NULL);
    if(toTest->count > 0)
    {
        // Transcribe the toTest list into the toTestVector
        for(i = 0; i < toTest->count; i++)
        {
            alg = toTest->algorithms[i];

            // make sure that the algorithm value is not out of range
            if((alg > TPM_ALG_LAST) || !TEST_BIT(alg, g_implementedAlgorithms))
                return TPM_RC_VALUE;
            SET_BIT(alg, toTestVector);
        }
        // Run the test
        if(CryptRunSelfTests(&toTestVector) == TPM_RC_CANCELED)
            return TPM_RC_CANCELED;
    }
    // Fill in the toDoList with the algorithms that are still untested
    toDoList->count = 0;

    for(alg = TPM_ALG_FIRST;
    toDoList->count < MAX_ALG_LIST_SIZE && alg <= TPM_ALG_LAST;
        alg++)
    {
        if(TEST_BIT(alg, g_toTest))
            toDoList->algorithms[toDoList->count++] = alg;
    }
    return TPM_RC_SUCCESS;
}

//*** CryptInitializeToTest()
// This function will initialize the data structures for testing all the
// algorithms. This should not be called unless CryptAlgsSetImplemented() has
// been called
void
CryptInitializeToTest(
    void
    )
{
    // Indicate that nothing has been tested
    memset(&g_cryptoSelfTestState, 0, sizeof(g_cryptoSelfTestState));

    // Copy the implemented algorithm vector
    MemoryCopy(g_toTest, g_implementedAlgorithms, sizeof(g_toTest));

    // Setting the algorithm to null causes the test function to just clear
    // out any algorithms for which there is no test.
    CryptTestAlgorithm(TPM_ALG_ERROR, &g_toTest);

    return;
}

//*** CryptTestAlgorithm()
// Only point of contact with the actual self tests. If a self-test fails, there
// is no return and the TPM goes into failure mode.
// The call to TestAlgorithm uses an algorithm selector and a bit vector. When the
// test is run, the corresponding bit in 'toTest' and in 'g_toTest' is CLEAR. If
// 'toTest' is NULL, then only the bit in 'g_toTest' is CLEAR.
// There is a special case for the call to TestAlgorithm(). When 'alg' is
// ALG_ERROR, TestAlgorithm() will CLEAR any bit in 'toTest' for which it has
// no test. This allows the knowledge about which algorithms have test to be
// accessed through the interface that provides the test.
//  Return Type: TPM_RC
//      TPM_RC_CANCELED     test was canceled
LIB_EXPORT
TPM_RC
CryptTestAlgorithm(
    TPM_ALG_ID           alg,
    ALGORITHM_VECTOR    *toTest
    )
{
    TPM_RC                   result;
#if SELF_TEST
    result = TestAlgorithm(alg, toTest);
#else
    // If this is an attempt to determine the algorithms for which there is a
    // self test, pretend that all of them do. We do that by not clearing any
    // of the algorithm bits. When/if this function is called to run tests, it
    // will over report. This can be changed so that any call to check on which
    // algorithms have tests, 'toTest' can be cleared.
    if(alg != TPM_ALG_ERROR)
    {
        CLEAR_BIT(alg, g_toTest);
        if(toTest != NULL)
            CLEAR_BIT(alg, *toTest);
    }
    result = TPM_RC_SUCCESS;
#endif
    return result;
}


text:
var dir_74bd63f98e2db1d13d9096e71e646329 =
[
    [ "AbstractBehaviour.java", "AbstractBehaviour_8java.html", [
      [ "AbstractBehaviour", "classorg_1_1onosproject_1_1net_1_1driver_1_1AbstractBehaviour.html", "classorg_1_1onosproject_1_1net_1_1driver_1_1AbstractBehaviour" ]
    ] ],
    [ "AbstractHandlerBehaviour.java", "AbstractHandlerBehaviour_8java.html", [
      [ "AbstractHandlerBehaviour", "classorg_1_1onosproject_1_1net_1_1driver_1_1AbstractHandlerBehaviour.html", "classorg_1_1onosproject_1_1net_1_1driver_1_1AbstractHandlerBehaviour" ]
    ] ],
    [ "Behaviour.java", "Behaviour_8java.html", [
      [ "Behaviour", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1Behaviour.html", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1Behaviour" ]
    ] ],
    [ "DefaultDriver.java", "DefaultDriver_8java.html", [
      [ "DefaultDriver", "classorg_1_1onosproject_1_1net_1_1driver_1_1DefaultDriver.html", "classorg_1_1onosproject_1_1net_1_1driver_1_1DefaultDriver" ]
    ] ],
    [ "DefaultDriverData.java", "DefaultDriverData_8java.html", [
      [ "DefaultDriverData", "classorg_1_1onosproject_1_1net_1_1driver_1_1DefaultDriverData.html", "classorg_1_1onosproject_1_1net_1_1driver_1_1DefaultDriverData" ]
    ] ],
    [ "DefaultDriverHandler.java", "DefaultDriverHandler_8java.html", [
      [ "DefaultDriverHandler", "classorg_1_1onosproject_1_1net_1_1driver_1_1DefaultDriverHandler.html", "classorg_1_1onosproject_1_1net_1_1driver_1_1DefaultDriverHandler" ]
    ] ],
    [ "DefaultDriverProvider.java", "DefaultDriverProvider_8java.html", [
      [ "DefaultDriverProvider", "classorg_1_1onosproject_1_1net_1_1driver_1_1DefaultDriverProvider.html", "classorg_1_1onosproject_1_1net_1_1driver_1_1DefaultDriverProvider" ]
    ] ],
    [ "DefaultDriverProviderService.java", "DefaultDriverProviderService_8java.html", [
      [ "DefaultDriverProviderService", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DefaultDriverProviderService.html", null ]
    ] ],
    [ "Driver.java", "Driver_8java.html", [
      [ "Driver", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1Driver.html", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1Driver" ]
    ] ],
    [ "DriverAdminService.java", "DriverAdminService_8java.html", [
      [ "DriverAdminService", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverAdminService.html", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverAdminService" ]
    ] ],
    [ "DriverConnect.java", "DriverConnect_8java.html", [
      [ "DriverConnect", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverConnect.html", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverConnect" ]
    ] ],
    [ "DriverData.java", "DriverData_8java.html", [
      [ "DriverData", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverData.html", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverData" ]
    ] ],
    [ "DriverHandler.java", "DriverHandler_8java.html", [
      [ "DriverHandler", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverHandler.html", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverHandler" ]
    ] ],
    [ "DriverProvider.java", "DriverProvider_8java.html", [
      [ "DriverProvider", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverProvider.html", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverProvider" ]
    ] ],
    [ "DriverResolver.java", "DriverResolver_8java.html", [
      [ "DriverResolver", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverResolver.html", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverResolver" ]
    ] ],
    [ "DriverService.java", "DriverService_8java.html", [
      [ "DriverService", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverService.html", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1DriverService" ]
    ] ],
    [ "HandlerBehaviour.java", "HandlerBehaviour_8java.html", [
      [ "HandlerBehaviour", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1HandlerBehaviour.html", "interfaceorg_1_1onosproject_1_1net_1_1driver_1_1HandlerBehaviour" ]
    ] ],
    [ "package-info.java", "core_2api_2src_2main_2java_2org_2onosproject_2net_2driver_2package-info_8java.html", null ],
    [ "XmlDriverLoader.java", "XmlDriverLoader_8java.html", [
      [ "XmlDriverLoader", "classorg_1_1onosproject_1_1net_1_1driver_1_1XmlDriverLoader.html", "classorg_1_1onosproject_1_1net_1_1driver_1_1XmlDriverLoader" ]
    ] ]
];


text:
package alien4cloud.rest.application.model;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class DeployApplicationRequest {
    private String applicationId;
    private String applicationEnvironmentId;
    private Object secretProviderCredentials;
    private String secretProviderPluginName;
}


text:
/**
 * @fileoverview
 * @suppress {uselessCode}
 */
'require util/owns';
'require util/polyfill';
'require util/shouldpolyfill';

/**
 * Equivalent to the Object.assign() method, but guaranteed to be available for use in code
 * generated by the compiler.
 *
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
 *
 * Copies values of all enumerable own properties from one or more
 * sources to the given target object, and returns the target.
 *
 * @final
 * @param {!Object} target The target object onto which to copy.
 * @param {...?Object} var_args The source objects.
 * @return {!Object} The target object is returned.
 */
$jscomp.assign =
    ($jscomp.TRUST_ES6_POLYFILLS && typeof Object.assign == 'function') ?
    Object.assign :
    /**
     * @param {!Object} target
     * @param {...?Object} var_args
     * @return {!Object}
     * @suppress {reportUnknownTypes}
     */
    function(target, var_args) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i];
        if (!source) continue;
        for (var key in source) {
          if ($jscomp.owns(source, key)) target[key] = source[key];
        }
      }
      return target;
    };


text:
/// <reference path="../typings/qs/qs.d.ts" />
/**
 * Created by slanska on 2016-06-17.
 */

///<reference path="qs/qs.d.ts"/>

declare module fsmrouter
{
    namespace events
    {
        const error:string;
        const begin:string;
        const end:string;
        const notfound:string;
        const add:string;
        const remove:string;
        const denied:string;
        const abandoned:string;
    }
    type StateContextPhase = 'canLeave' | 'canEnter' | 'leave' | 'enter' | 'update';
    type EventHandler = (state:FSMState, params?:any) => void;
    interface FSMStateContext
    {
        query:any;
        url:string;
        params:any;
        current:FSMState;
        router:FSMRouter;
        phase:StateContextPhase;
        backwards:boolean;
        $scope:any;
    }
    type FSMCallback = (ctx:FSMStateContext) => any;
    interface FSMStateConfig
    {
        canEnter?:FSMCallback;
        canLeave?:FSMCallback;
        enter?:FSMCallback;
        leave?:FSMCallback;
        update?:FSMCallback;
        url?:string | RegExp;
        title?:string | ((ctx:FSMStateContext) => string);
        destroy?:(state:FSMState) => void;
        alwaysEnter?:boolean;
    }
    interface FSMRouterConfig
    {
        nameSeparator?:string;
        strict?:boolean;
        urlPrefix?:string;
        caseSensitive?:boolean;
        documentTitle?:(ctx:FSMStateContext) => string;
        stateMachineMode?:boolean;
    }
    class FSMState
    {
        name:string;
        private _router;
        cfg:FSMStateConfig;

        constructor(name:string, _router:FSMRouter, cfg:FSMStateConfig);

        $scope:{};
        protected _regExp:RegExp;
        protected _keys:any[];

        private pathToRegexp(path, keys, sensitive, strict);

        parent:FSMState;
        router:FSMRouter;
        fullUrl:string;

        protected _ownName():string;

        segments:string[];

        matchUrl(path:string, params:any):boolean;

        private match(path, params, regex, keys);
    }
    interface IDecodedUrl
    {
        path:string;
        query:any;
    }
    class FSMRouter
    {
        cfg:FSMRouterConfig;

        constructor(cfg?:FSMRouterConfig);

        private getWindowUrl();

        private _findCommonStateSegments(prev, cur);

        private _initCallbacks(calls, phase, state, ctx, depth, leaveMode);

        private _processQueueItem(it);

        private _processUrlChange(url);

        private finalizeProcessing(result, ctx, st, url);

        static encode(url:string, query?:any):string;

        static decode(path:string):IDecodedUrl;

        private _processCurrentUrl();

        _getStateCfgAttr(state:FSMState, attrName:string):any;

        _states:{
            [stateName:string]:FSMState;
        };
        private _names;

        private updateNames();

        private addState(stateName, cfg);

        add(stateName:string, cfg?:FSMStateConfig):FSMRouter;

        addMany(states:{
            [stateName:string]:FSMStateConfig;
        }):this;

        get(stateName:string):FSMState;

        remove(stateName:string):Number;

        names:string[];
        static path:{
            join:(...segments:string[]) => string;
            dirname:(path:string) => string;
        };
        private _stopped;

        start(stateName?:string, params?:any, query?:any):void;

        is(stateName:string, param?:Object, isStrict?:boolean):boolean;

        current:FSMStateContext;

        go(stateName:string, params?:any, query?:any):FSMRouter;

        goUrl(path:string, query?:any):FSMRouter;

        stop():void;

        static Qs:typeof QueryString;
        private _handlers;

        private findEventHandler(hh, handler);

        on(event:string, handler:EventHandler):FSMRouter;

        off(event:string, handler:EventHandler):FSMRouter;

        emit(event:string, param?:any):FSMRouter;
    }
}

declare module "fsmrouter"
{
   export = fsmrouter;
}


text:
import pytest

from awx.api.versioning import reverse

@pytest.mark.django_db
def test_aliased_forward_reverse_field_searches(instance, options, get, admin):
    url = reverse('api:unified_job_template_list')
    response = options(url, None, admin)
    assert 'job_template__search' in response.data['related_search_fields']
    get(reverse("api:unified_job_template_list") + "?job_template__search=anything", user=admin, expect=200)


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\modules\admin\models\OfficeSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', 'Offices');
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a(Yii::t('app', 'Create') . Yii::t('app', 'Office'), ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
//            ['class' => 'yii\grid\SerialColumn'],

            'office_id',
            'name',
            [
                'attribute' => 'hospital_id',
                'value' => function($data){
                    return \app\models\Hospital::getList()[$data->hospital_id];
                },
                'filter' => \app\models\Hospital::getList(),
            ],

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
from futurist._futures import Future  # noqa
from futurist._futures import GreenFuture  # noqa

from futurist._futures import GreenThreadPoolExecutor  # noqa
from futurist._futures import ProcessPoolExecutor  # noqa
from futurist._futures import SynchronousExecutor  # noqa
from futurist._futures import ThreadPoolExecutor  # noqa

from futurist._futures import ExecutorStatistics  # noqa


text:
/* regdef.h -- define register names.  */

/* This is a standard include file for MIPS targets.  Other target
   probably don't define it, and attempts to include this file will
   fail.  */

#include <machine/regdef.h>


text:
import compression = require('compression');
import express = require('express');
import http = require('http');
import {Analytics} from './analytics';
import {BadgeUtils} from './badgeUtils';
import {Database} from './database';
import {View} from './view';

/**
 * Web server management
 */
export class WebServer {
    private analytics: Analytics;
    private app: any;
    private db: Database;
    private env: { [key: string]: any };

    constructor(env: { [key: string]: any }, db: Database, analytics: Analytics) {
        this.analytics = analytics;
        this.db = db;
        this.env = env;
    }

    /**
     * Create the web server and start it
     */
    public start() {
        this.app = express();

        this.useMiddleware();
        this.decodeParams();
        this.route();
        this.startServer();
    }

    /**
     * Define the server routes
     */
    private route(): void {
        let self = this;

        this.app.get('/:extension/:method(total|last-version|week|day).svg', function (req: any, res: any) {
            res.setHeader('Content-Type', 'image/svg+xml');
            let method = req.params['method'];
            let downloads = BadgeUtils.getDownloadsByMethod(req.extension, method);
            res.end(View.getDownloadsBadge(downloads, method));
            self.analytics.track(req, method);
        });

        this.app.get('/:extension/version.svg', function (req: any, res: any) {
            res.setHeader('Content-Type', 'image/svg+xml');
            res.end(View.getVersionBadge(req.extension.version));
            self.analytics.track(req, 'version');
        });

        this.app.get('/:extension/stats.json', function (req: any, res: any) {
            res.setHeader('Content-Type', 'application/json; charset=utf-8');
            let e = req.extension;
            res.end(JSON.stringify({
                /* tslint:disable */
                name: e.name,
                version: e.version,
                total: e.total,
                lastVersion: e.lastVersion,
                week: e.week,
                /* tslint:enable */
            }));
            self.analytics.track(req, 'stats');
        });

        this.app.get('/*.svg', function (req: any, res: any) {
            View.unknownBadge(res);
            self.analytics.track(req);
        });

        this.app.get('/list.json', function (req: any, res: any) {
            let list = self.db.getExtensionList();
            View.extensionList(res, list);
            self.analytics.track(req);
        });

        this.app.get('/', function (req: any, res: any) {
            res.setHeader('Content-Type', 'text/html; charset=utf-8');
            res.end('<script>window.location.replace(\'https://brackets-extension-badges.github.io\');</script>');
            self.analytics.track(req);
        });
    }

    /**
     * Define the server middleware
     */
    private useMiddleware(): void {
        this.app.use(compression());

        this.app.use(function (req: any, res: any, next: any) {
            res.header('Access-Control-Allow-Origin', '*');
            res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
            res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
            res.header('Expires', new Date(Date.now() + 900 * 1000).toUTCString());
            next();
        });
    }

    /**
     * Find the good extension in database from URL
     */
    private decodeParams(): void {
        let self = this;

        this.app.param('extension', function (req: any, res: any, next: any, extensionName: string) {
            let e = self.db.get(extensionName);
            if (!e) {
                return View.unknownBadge(res);
            }
            req.extension = e;
            next();
        });
    }

    /**
     * Start the server
     */
    private startServer(): void {
        http.createServer(this.app).listen(this.env.port, () => {
            console.info('Server listening on port ' + this.env.port + '!');
        });
    }
}


text:
from django.db import models
from base.models import (CRUDModel, CRUDModelWithUrl)
from user.models import UserModel

from django.utils.translation import ugettext as _
import logging

class CountryModel(CRUDModel):
    name = models.CharField(max_length=50, blank=False)

    class Meta:
        verbose_name = _('country')
        verbose_name_plural = _('countries')

    @classmethod
    def fetch_or_create(klass, name):
        return klass.create({'name': name})

class StateModel(CRUDModel):
    name = models.CharField(max_length=50, blank=True)
    fk_country = models.ForeignKey(CountryModel, on_delete=models.CASCADE)

    class Meta:
        verbose_name = _('state')
        verbose_name_plural = _('states')

    @classmethod
    def fetch_or_create(klass, state_name, country):
        print('Amit Dhiman', state_name, country)
        return klass.create({'name': state_name, 'fk_country': country})

class CityModel(CRUDModel):
    name = models.CharField(max_length=50)
    fk_state = models.ForeignKey(StateModel, on_delete=models.CASCADE)
    fk_country = models.ForeignKey(CountryModel, on_delete=models.CASCADE)

    class Meta:
        verbose_name = _('city')
        verbose_name_plural = _('cities')

    @classmethod
    def fetch_or_create(klass, city_name, state, country):
        return klass.create({'name': city_name, 'fk_state': state, 'fk_country': country})

    @classmethod
    def fetch_by_name(klass, city_name, state_name, country_name):
        try:
            return klass.objects.get(name=city_name, fk_state__name=state_name, fk_country__name=country_name)
        except Exception as ex:
            logging.error(ex)
        return None

class AreaModel(CRUDModel):
    name = models.CharField(max_length=50, blank=True)
    pincode = models.CharField(max_length=10, blank=True)
    fk_city = models.ForeignKey(CityModel, on_delete=models.CASCADE)
    fk_state = models.ForeignKey(StateModel, on_delete=models.CASCADE)
    fk_country = models.ForeignKey(CountryModel, on_delete=models.CASCADE)

    class Meta:
        verbose_name = _('area')
        verbose_name_plural = _('areas')

    @classmethod
    def fetch_or_create(klass, area_name, area_pin, city, state, country):
        values = {
            'name': area_name,
            'pincode': area_pin,
            'fk_city': city,
            'fk_state': state,
            'fk_country': country
        }
        return klass.create(values)

    @classmethod
    def fetch_by_pincode(klass, area_pin):
        try:
            return klass.objects.filter(pincode=area_pin)
        except Exception as e:
            logging.error(e)
        return None

    @classmethod
    def fetch_by_city(klass, city):
        try:
            return klass.objects.filter(fk_city__name=city)
        except Exception as e:
            logging.error(e)
        return None

    @classmethod
    def fetch_by_match(klass, keyw):
        print('key is : '+keyw)
        query = klass.objects.annotate(city=models.F('fk_city__name')).filter(name__istartswith=keyw).values('name', 'pin', 'city')[:20]
        # query = klass.objects.annotate(city_name=models.F('fk_city__city_name')).filter(area_name__icontains=keyw).values('area_name', 'area_pin', 'city_name')
        return query

class AddressModel(CRUDModelWithUrl):
    name = models.CharField(max_length=50, blank=False)
    person = models.CharField(max_length=20, blank=True)
    phone = models.CharField(max_length=10, blank=True)
    address = models.CharField(max_length=50, blank=False)
    landmark = models.CharField(max_length=50, blank=True)
    latitude = models.CharField(max_length=10, blank=True)
    longitude = models.CharField(max_length=10, blank=True)
    fk_area = models.ForeignKey(AreaModel, on_delete=models.CASCADE)
    fk_user = models.ForeignKey(UserModel, on_delete=models.CASCADE)
    flags = models.CharField(max_length=10, default='')

    class Meta:
        verbose_name = _('address')
        verbose_name_plural = _('address')

    def url(self):
        return '/locus/address/' + str(self.id) + '/'

    @classmethod
    def queryset(klass):
        # fields = ('id', 'name', 'person', 'phone', 'pincode', 'address', 'area', 'city', 'state', 'country')
        return klass.objects.annotate(
        pincode=models.F('fk_area__pincode'),
        area=models.F('fk_area__name'),
        city=models.F('fk_area__fk_city__name'),
        state=models.F('fk_area__fk_state__name'),
        country=models.F('fk_area__fk_country__name'),
        location=models.functions.Concat('latitude', models.Value(','), 'longitude'))

    @classmethod
    def fetch_all(klass):
        return klass.queryset()

    @classmethod
    def fetch_by_id(klass, id_):
        return klass.queryset().filter(id=id_)

    @classmethod
    def fetch_by_user(klass, user):
        return klass.queryset().filter(fk_user=user)

class Location(CRUDModel):
    name = models.CharField(max_length=50, blank=False)
    latitude = models.CharField(max_length=10)
    longitude = models.CharField(max_length=10)

    @classmethod
    def fetch_by_geo(klass, latitude, longitude):
        obj = klass.objects.get_or_create(latitude=latitude, longitude=longitude)
        return obj

    @classmethod
    def fetch_by_user(klass, user):
        return klass.objects.filter(fk_user=user)


text:
function computeDensitySplitting( obj, iProcCD, nProcCD )
% COMPUTEDENSITYSPLITTING Lag-embed the density in an nlsaModel_den object
%
% Modified 2020/01/28

if nargin == 1
    iProcCD = 1;
    nProcCD = 1;
end

cmp = getDensityKernel( obj );
cmpQ = getDensityKernelQ( obj );
nCD = size( cmp, 1 );

pPartitionCD = nlsaPartition( 'nSample', nCD, 'nBatch', nProcCD );
iCDLim = getBatchLimit( pPartitionCD, iProcCD );

for iC = iCDLim( 1 ) : iCDLim( 2 )
    splitData( cmpQ( iC, : ), cmp( iC ) )
end


text:
bool CIniFile::load(const std::string& file)
{
    d_entries.clear();

    std::ifstream ifs(file);
    if (!ifs.is_open())
    {
        return false;
    }
    std::string line;
    std::string group;
    while (std::getline(ifs, line))
    {
        if (line.empty())
        {
            // Empty line
            continue;
        }
        else if (line.at(0) == '#')  // Comment
        {
            // Ignore
            continue;
        }
        else if (line.at(0) == '[')  // Group
        {
            unsigned int pos = line.find(']');
            if (pos == std::string::npos)
            {
                d_entries.clear();
                ifs.close();
                return false;
            }
            // Set current group
            group = line.substr(1, pos - 1);
        }
        else  // Key/value pair
        {
            unsigned int pos = line.find('=');
            if (pos == std::string::npos)
            {
                d_entries.clear();
                ifs.close();
                return false;
            }
            d_entries[group][line.substr(0, pos)] = line.substr(pos + 1);
        }
    }
    ifs.close();
    return true;
}

bool CIniFile::save(const std::string& file)
{
    // Ini file
    std::ofstream ofs(file);
    if (!ofs.is_open())
    {
        return false;
    }

    // Write groups
    for (const auto& group : d_entries)
    {
        ofs << "[" << group.first << "]" << std::endl;
        // Write entries
        for (const auto& entry : group.second)
        {
            ofs << entry.first << "=" << entry.second << std::endl;
        }
        ofs << std::endl;
    }
    return true;
}

void CIniFile::setValue(const std::string& group, const std::string& key, const std::string& value)
{
    d_entries[group][key] = value;
    return;
}

void CIniFile::setValue(const std::string& group, const std::string& key, int value)
{
    std::stringstream ss;
    ss << value;
    setValue(group, key, ss.str());
}

void CIniFile::setValue(const std::string& group, const std::string& key, float value)
{
    std::stringstream ss;
    ss << value;
    setValue(group, key, ss.str());
}

const std::string& CIniFile::getValue(const std::string& group, const std::string& key,
                                      const std::string& defaultValue) const
{
    if (hasKey(group, key))
    {
        return d_entries.at(group).at(key);
    }
    return defaultValue;
}

int CIniFile::getValue(const std::string& group, const std::string& key, int defaultValue) const
{
    if (hasKey(group, key))
    {
        try
        {
            return std::stoi(d_entries.at(group).at(key));
        }
        catch (const std::exception&)
        {
            // Conversion error
        }
    }
    return defaultValue;
}

float CIniFile::getValue(const std::string& group, const std::string& key, float defaultValue) const
{
    if (hasKey(group, key))
    {
        try
        {
            return std::stof(d_entries.at(group).at(key));
        }
        catch (const std::exception&)
        {
            // Conversion error
        }
    }
    return defaultValue;
}

bool CIniFile::hasGroup(const std::string& group) const { return d_entries.count(group) == 1; }

bool CIniFile::hasKey(const std::string& group, const std::string& key) const
{
    return hasGroup(group) && d_entries.at(group).count(key) == 1;
}


text:
import { AlignBoxTopCenter20 } from "../../";

export = AlignBoxTopCenter20;


text:
var fs = require('fs')
var html = fs.readFileSync(__dirname+'/html/property.html', 'utf8')
var hyperglue = require('hyperglue')
var $ = require('dom-select')
var classes = require('dom-classes')
var events = require('dom-events')
var domify = require('domify')

var BaseProperty = require('../lib/property-data')

//Builds a DOM element from a keytime property
module.exports = function(editor, timelineData, property) {
	var ret = BaseProperty(timelineData, property)

    //the element which holds buttons, name, etc.
    var element = hyperglue(html, {
        '.name': property.name
    })
    ret.element = element

    var easeElement = $('.easing', element)
    ret.easingBox = editor.createEasingSelect({ element: easeElement })
    if (ret.easingBox) {
        ret.easingBox.on('change', function(ev) {
            editor.emit('select-easing', ret)
        })
    }

    var valueEditor = editor.createValueEditor(timelineData.timeline, property)
    var controlPanel = $('.control-editor', element)
    if (valueEditor && valueEditor.element) {
    	controlPanel.appendChild(valueEditor.element)
    	ret.valueEditor = valueEditor

        //set default property
        property.value = valueEditor.value

    	valueEditor.on('change', function() {
    		var current = property.keyframes.get( editor.playhead() )
	        if (current) { //adjust current keyframe
                property.value = valueEditor.value
	            current.value = valueEditor.value
	        }
            // else if (property.keyframes.count === 0) { //no keyframes, adjust constant
            //     property.value = valueEditor.value
            // }
            else {
                console.log("ADD")
                var key = ret._createKeyframe(timelineData.timeline, editor.playhead() )
                ret.addKeyframe(editor, key)
            }
            editor._updateProperties()
    	})
    }

    var toggle = $('.keyframe-toggle', element)
    events.on(toggle, 'click', function(ev) {
        editor.emit('keyframe-toggle', timelineData, ret)
    })

    var next = $('.keyframe-next', element)
    events.on(next, 'click', function(ev) {
        editor.emit('keyframe-next', ret)
    })

    var previous = $('.keyframe-previous', element)
    events.on(previous, 'click', function(ev) {
        editor.emit('keyframe-previous', ret)
    })

    events.on(element, 'click', function(ev) {
    	editor.emit('highlight-property', ret)
    })

    return ret
}


text:
require 'set'
require 'delegate'

require 'json'
require 'active_model'

require 'active_support/core_ext/string/inflections'
require 'active_support/core_ext/object/instance_variables'
require 'active_support/core_ext/hash/indifferent_access'
require 'active_support/core_ext/object/try'

require 'actionable/version'
require 'actionable/exceptions'
require 'actionable/results'
require 'actionable/steps'
require 'actionable/history'
require 'actionable/action_runner'
require 'actionable/registry'
require 'actionable/action'

module Actionable
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EAD = ExamAssessmentDaal;
using DTO = ExamassessmentWCF;
using LMS1701.EA.SOAPAPI;

namespace LMS1701.EA.SOAPAPI
{
    public class QuestionAction
    {
        private EAD.ExamAssessmentEntities db;
        private List<EAD.Question> dbquestion;
        public QuestionAction()
        {
            db = new EAD.ExamAssessmentEntities();
            dbquestion = db.Question.ToList();
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="tempID"></param>
        /// <returns></returns>
        public  Question getQuestion(int tempID)
        {
            List<EAD.Question> Question = dbquestion.Where(s => s.PKID == tempID).ToList();
            Question quest = new Question();
            quest.PKID = Question.ElementAt(0).PKID;
            quest.Description = Question.ElementAt(0).Description;
            return quest;
        }
    }
}


text:
package com.moxun.tagcloud;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class FragmentTestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_test);
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.container, TestFragment.newInstance())
                .commit();
    }
}


text:
var i2c = require('i2c');
var _ = require('underscore')

// Registers
var __HT16K33_REGISTER_DISPLAY_SETUP = 0x80
var __HT16K33_REGISTER_SYSTEM_SETUP = 0x20
var __HT16K33_REGISTER_DIMMING = 0xE0

// Blink rate
var __HT16K33_BLINKRATE_OFF = 0x00
var __HT16K33_BLINKRATE_2HZ = 0x01
var __HT16K33_BLINKRATE_1HZ = 0x02
var __HT16K33_BLINKRATE_HALFHZ = 0x03

function LEDBackpack(address, bus){
  bus = bus || 1
  this.wire = new i2c(address, {device: '/dev/i2c-' + bus})

  // Display buffer (8x16-bits)
  this.buffer = [0, 0, 0, 0, 0, 0, 0, 0]

  // transaction level
  this.transactionLevel = 0;

  // Turn the oscillator on
  this.wire.writeBytes(__HT16K33_REGISTER_SYSTEM_SETUP | 0x01, [0x00])

  // Turn blink off
  this.setBlinkRate(__HT16K33_BLINKRATE_OFF)

  // Set maximum brightness
  this.setBrightness(15)

  // Clear the screen
  this.clear()
}

LEDBackpack.prototype.setBrightness = function(brightness){
  if (brightness > 15) brightness = 15
  this.wire.writeBytes(__HT16K33_REGISTER_DIMMING | brightness, [0x00])
}

LEDBackpack.prototype.setBlinkRate = function(blinkRate){
  if (blinkRate > __HT16K33_BLINKRATE_HALFHZ) blinkRate = __HT16K33_BLINKRATE_OFF
  this.wire.writeBytes(__HT16K33_REGISTER_DISPLAY_SETUP | 0x01 | (blinkRate << 1), [0x00])
}

LEDBackpack.prototype.setBufferRow = function(row, value){
  if (row < 0 || row > 7) return
  this.buffer[row] = value // value # & 0xFFFF
  if (this.transactionLevel === 0) {
    this.writeDisplay()
  }
}

LEDBackpack.prototype.getBuffer = function(){
  return _.clone(this.buffer)
}

LEDBackpack.prototype.getBufferRow = function(row){
  if (row < 0 || row > 7) return
  return this.buffer[row]
}

LEDBackpack.prototype.writeDisplay = function(){
  var bytes = []
  _.each(this.buffer, function(item){
    bytes.push(item & 0xFF)
    bytes.push((item >> 8) & 0xFF)
  })
  this.wire.writeBytes(0x00, bytes)
}

LEDBackpack.prototype.allOn = function(){
  this.buffer = [ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ]
  if (this.transactionLevel === 0) {
    this.writeDisplay()
  }
}

LEDBackpack.prototype.allOff = function(){
  this.buffer = [ 0, 0, 0, 0, 0, 0, 0, 0 ]
  if (this.transactionLevel === 0) {
    this.writeDisplay()
  }
}

LEDBackpack.prototype.clear = LEDBackpack.prototype.allOff

LEDBackpack.prototype.startTransaction = function(){
  this.transactionLevel++;
}

LEDBackpack.prototype.commitTransaction = function(){
  this.transactionLevel--;
  if (this.transactionLevel === 0) {
    this.writeDisplay()
  }
}

module.exports = LEDBackpack


text:
WebAssembly code is represented as an abstract syntax tree
that has a basic division between statements and
expressions. Each function body consists of exactly one statement.
All expressions and operations are typed, with no implicit conversions or
overloading rules.

Verification of WebAssembly code requires only a single pass with constant-time
type checking and well-formedness checking.

Why not a stack-, register- or SSA-based bytecode?
* Trees allow a smaller binary encoding: [JSZap][], [Slim Binaries][].
* [Polyfill prototype][] shows simple and efficient translation to asm.js.

  [JSZap]: https://research.microsoft.com/en-us/projects/jszap/
  [Slim Binaries]: https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.108.1711
  [Polyfill prototype]: https://github.com/WebAssembly/polyfill-prototype-1

WebAssembly offers a set of operations that are language-independent but closely
match operations in many programming languages and are efficiently implementable
on all modern computers.

Some operations may *trap* under some conditions, as noted below. In the MVP,
trapping means that execution in the WebAssembly module is terminated and
abnormal termination is reported to the outside environment. In a JS
environment such as a browser, a trap results in throwing a JS exception.
If developer tools are active, attaching a debugger before the
termination would be sensible.

Callstack space is limited by unspecified and dynamically varying constraints.
If program callstack usage exceeds the available callstack space at any time,
a trap occurs.

## Types

### Local Types

The following types are called the *local types*:

  * `int32`: 32-bit integer
  * `int64`: 64-bit integer
  * `float32`: 32-bit floating point
  * `float64`: 64-bit floating point

Note that the local types `int32` and `int64` are not inherently signed or
unsigned. The interpretation of these types is determined by individual
operations.

Parameters and local variables use local types.

Also note that there is no need for a `void` type; function signatures use
[sequences of types](Calls.md) to describe their return values, so a `void`
return type is represented as an empty sequence.

### Memory Types

*Memory types* are a different superset of the local types, adding the
following:

  * `int8`: 8-bit integer
  * `int16`: 16-bit integer

Global variables and linear memory accesses use memory types.

## Linear Memory

The main storage of a WebAssembly module, called the *linear memory*, is a
contiguous, byte-addressable range of memory spanning from offset `0` and
extending for `memory_size` bytes which can be dynamically adjusted by
[`resize_memory`](Modules.md#resizing). The linear memory can be considered to
be an untyped array of bytes. The linear memory is sandboxed; it does not alias
the execution engine's internal data structures, the execution stack, local
variables, global variables, or other process memory. The initial state of
linear memory is specified by the [module](Modules.md#initial-state-of-linear-memory).

In the MVP, linear memory is not shared between threads of execution. Separate
modules can execute in separate threads but have their own linear memory and can
only communicate through messaging, e.g. in browsers using `postMessage`. It
will be possible to share linear memory between threads of execution when
[threads](PostMVP.md#threads) are added.

### Linear Memory Operations

Linear memory operations are annotated with a memory type and perform a
conversion between that memory type and a local type.

Loads read data from linear memory, convert from their memory type to a basic
type, and return the result:

  * `int32.load_sx[int8]`: sign-extend to int32
  * `int32.load_sx[int16]`: sign-extend to int32
  * `int32.load_zx[int8]`: zero-extend to int32
  * `int32.load_zx[int16]`: zero-extend to int32
  * `int32.load[int32]`: (no conversion)
  * `int64.load_sx[int8]`: sign-extend to int64
  * `int64.load_sx[int16]`: sign-extend to int64
  * `int64.load_sx[int32]`: sign-extend to int64
  * `int64.load_zx[int8]`: zero-extend to int64
  * `int64.load_zx[int16]`: zero-extend to int64
  * `int64.load_zx[int32]`: zero-extend to int64
  * `int64.load[int64]`: (no conversion)
  * `float32.load[float32]`: (no conversion)
  * `float64.load[float64]`: (no conversion)

Stores have an operand providing a value to store. They convert from the value's
local type to their memory type, and write the resulting value to linear memory:

  * `int32.store[int8]`: wrap int32 to int8
  * `int32.store[int16]`: wrap int32 to int16
  * `int32.store[int32]`: (no conversion)
  * `int64.store[int8]`: wrap int64 to int8
  * `int64.store[int16]`: wrap int64 to int16
  * `int64.store[int32]`: wrap int64 to int32
  * `int64.store[int64]`: (no conversion)
  * `float32.store[float32]`: (no conversion)
  * `float64.store[float64]`: (no conversion)

Wrapping of integers simply discards any upper bits; i.e. wrapping does not
perform saturation, trap on overflow, etc.

In addition to storing a value to linear memory, store instructions also
reproduce their value operand, with no conversion applied.

### Addressing

Each linear memory access operation also has an address operand and an immediate
integer byte offset attribute. The infinite-precision sum of the address
operand's value with the byte offset attribute's value is called the
*effective address*, which is interpreted as an unsigned byte index.

Linear memory accesses access the bytes starting at the location in the linear
memory storage indexed by the effective address, and extending for the number
of bytes implied by the memory type attribute of the access.

If any of the accessed bytes are beyond `memory_size`, the access is considered
*out-of-bounds*. A module may optionally define that out-of-bounds includes
small effective addresses close to `0`
(see [discussion](https://github.com/WebAssembly/design/issues/204)).
The semantics of out-of-bounds accesses are discussed
[below](AstSemantics.md#out-of-bounds).

The use of infinite-precision in the effective address computation means that
the addition of the offset to the address does is never wrapped, so if the
address for an access is out-of-bounds, the effective address will always also
be out-of-bounds. This is intended to simplify folding of offsets into complex
address modes in hardware, and to simplify bounds checking optimizations.

In the MVP, address operands and offset attributes have type `int32`, and linear
memory sizes are limited to 4 GiB (of course, actual sizes are further limited
by [available resources](Nondeterminism.md)). In the future, to support
[>4GiB linear memory](FutureFeatures.md#heaps-bigger-than-4gib), support for
indices with type `int64` will be added.

### Alignment

Each linear memory access operation also has an immediate positive integer power
of 2 alignment attribute. An alignment value which is the same as the memory
attribute size is considered to be a *natural* alignment.

If the effective address of a memory access is a multiple of the alignment
attribute value of the memory access, the memory access is considered *aligned*,
otherwise it is considered *misaligned*. Aligned and misaligned accesses have
the same behavior. Alignment affects performance as follows:

 * Aligned accesses with at least natural alignment are fast.
 * Aligned accesses with less than natural alignment may be somewhat slower
   (think: implementation makes multiple accesses, either in software or
    in hardware).
 * Misaligned access of any kind may be *massively* slower
   (think: implementation takes a signal and fixes things up)

Thus, it is recommend that WebAssembly producers align frequently-used data
to permit the use of natural alignment access, and use loads and stores with
the greatest alignment values practical, while always avoiding misaligned
accesses.

Either tooling or an explicit opt-in "debug mode" in the spec should allow
execution of a module in a mode that threw exceptions on misaligned access.
(This mode would incur some runtime cost for branching on most platforms which
is why it isn't the specified default.)

### Out of bounds

The ideal semantics is for out-of-bounds accesses to trap, but the implications
are not yet fully clear.

There are several possible variations on this design being discussed and
experimented with. More measurement is required to understand the associated
tradeoffs.

  * After an out-of-bounds access, the module can no longer execute code and any
    outstanding JS ArrayBuffers aliasing the linear memory are detached.
    * This would primarily allow hoisting bounds checks above effectful
      operations.
    * This can be viewed as a mild security measure under the assumption that
      while the sandbox is still ensuring safety, the module's internal state
      is incoherent and further execution could lead to Bad Things (e.g., XSS
      attacks).
  * To allow for potentially more-efficient memory sandboxing, the semantics could
    allow for a nondeterministic choice between one of the following when an
    out-of-bounds access occurred.
    * The ideal trap semantics.
    * Loads return an unspecified value.
    * Stores are either ignored or store to an unspecified location in the linear memory.
    * Either tooling or an explicit opt-in "debug mode" in the spec should allow
      execution of a module in a mode that threw exceptions on out-of-bounds
      access.

### Resizing

Linear memory can be resized by a `resize_memory` builtin operation. The
`resize_memory` operation requires its operand to be a multiple of the system
page size. To determine page size, a nullary `page_size` operation is provided.

 * `resize_memory` : grow or shrink linear memory by a given delta which
    must be a multiple of `page_size`
 * `page_size` : nullary constant function returning page size

Also as stated [above](AstSemantics.md#linear-memory), linear memory is
contiguous, meaning there are no "holes" in the linear address space. After the
MVP, there are [future features](FutureFeatures.md#finer-grained-control-over-memory)
proposed to allow setting protection and creating mappings within the
contiguous linear memory.

## Local variables

Each function has a fixed, pre-declared number of local variables which occupy a single
index space local to the function. Parameters are addressed as local variables. Local
variables do not have addresses and are not aliased in the globals or memory. Local
variables have local types and are initialized to the appropriate zero value for their
type at the beginning of the function, except parameters which are initialized to the values
of the arguments passed to the function.

  * `get_local`: read the current value of a local variable
  * `set_local`: set the current value of a local variable

The details of index space for local variables and their types will be further clarified,
e.g. whether locals with type `int32` and `int64` must be contiguous and separate from
others, etc.

## Global variables

Global variables are storage locations outside the linear memory.
Every global has exactly one memory type.
Accesses to global variables specify the index as an integer literal.

  * `load_global`: load the value of a given global variable
  * `store_global`: store a given value to a given global variable

The specification will add atomicity annotations in the future. Currently
all global accesses can be considered "non-atomic".

## Control flow structures

WebAssembly offers basic structured control flow. All control flow structures
are statements.

  * `block`: a fixed-length sequence of statements
  * `if`: if statement
  * `do_while`: do while statement, basically a loop with a conditional branch
    (back to the top of the loop)
  * `forever`: infinite loop statement (like `while (1)`), basically an
    unconditional branch (back to the top of the loop)
  * `continue`: continue to start of nested loop
  * `break`: break to end from nested loop or block
  * `return`: return zero or more values from this function
  * `switch`: switch statement with fallthrough

Loops (`do_while` and `forever`) may only be entered via fallthrough at the top.
In particular, loops may not be entered directly via a `break`, `continue`, or
`switch` destination. Break and continue statements can only target blocks or
loops in which they are nested. These rules guarantee that all control flow
graphs are well-structured.

Structured control flow provides simple and size-efficient binary encoding and
compilation. Any control flow—even irreducible—can be transformed into structured
control flow with the
[Relooper](https://github.com/kripken/emscripten/raw/master/docs/paper.pdf)
[algorithm](http://dl.acm.org/citation.cfm?id=2048224&CFID=670868333&CFTOKEN=46181900),
with guaranteed low code size overhead, and typically minimal throughput
overhead (except for pathological cases of irreducible control
flow). Alternative approaches can generate reducible control flow via node
splitting, which can reduce throughput overhead, at the cost of increasing
code size (potentially very significantly in pathological cases).
Also,
[more expressive control flow constructs](FutureFeatures.md#more-expressive-control-flow)
may be added in the future.

## Calls

Each function has a *signature*, which consists of:

  * Return types, which are a sequence of local types
  * Argument types, which are a sequence of local types

Note that WebAssembly itself does not support variable-length argument lists
(aka varargs). C and C++ compilers are expected to implement this functionality
by storing arguments in a buffer in linear memory and passing a pointer to the
buffer.

In the MVP, the length of the return types sequence may only be 0 or 1. This
restriction may be lifted in the future.

Direct calls to a function specify the callee by index into a function table.

  * `call_direct`: call function directly

Calls must match the function signature
exactly. [Imported functions](MVP.md#code-loading-and-imports) also have
signatures and are added to the same function table and are thus also callable
via `call_direct`.

Indirect calls may be made to a value of function-pointer type. A
function-pointer value may be obtained for a given function as specified by its index
in the function table.

  * `call_indirect`: call function indirectly
  * `addressof`: obtain a function pointer value for a given function

Function-pointer values are comparable for equality and the `addressof` operator
is monomorphic. Function-pointer values can be explicitly coerced to and from
integers (which, in particular, is necessary when loading/storing to memory
since memory only provides integer types). For security and safety reasons,
the integer value of a coerced function-pointer value is an abstract index and
does not reveal the actual machine code address of the target function.

In the MVP, function pointer values are local to a single module. The
[dynamic linking](FutureFeatures.md#dynamic-linking) feature is necessary for
two modules to pass function pointers back and forth.

Multiple return value calls will be possible, though possibly not in the
MVP. The details of multiple-return-value calls needs clarification. Calling a
function that returns multiple values will likely have to be a statement that
specifies multiple local variables to which to assign the corresponding return
values.

## Literals

Each local type allows literal values directly in the AST. See the
[binary encoding section](BinaryEncoding.md#constant-pool).

## Expressions with control flow

Expression trees offer significant size reduction by avoiding the need for
`set_local`/`get_local` pairs in the common case of an expression with only one,
immediate use. The following primitives provide AST nodes that express control
flow and thus allow more opportunities to build bigger expression trees and
further reduce `set_local`/`get_local` usage (which constitute 30-40% of total
bytes in the
[polyfill prototype](https://github.com/WebAssembly/polyfill-prototype-1)).
Additionally, these primitives are useful building blocks for
WebAssembly-generators (including the JavaScript polyfill prototype).

  * `comma`: evaluate and ignore the result of the first operand, evaluate and
    return the second operand
  * `conditional`: basically ternary `?:` operator

New operations may be considered which allow measurably greater
expression-tree-building opportunities.

## 32-bit Integer operations

Integer operations are signed, unsigned, or sign-agnostic. Signed operations
use two's complement signed integer representation.

Signed and unsigned operations trap whenever the result cannot be represented
in the result type. This includes division and remainder by zero, and signed
division overflow (`INT32_MIN / -1`). Signed remainder with a non-zero
denominator always returns the correct value, even when the corresponding
division would trap. Sign-agnostic operations silently wrap overflowing
results into the result type.

  * `int32.add`: sign-agnostic addition
  * `int32.sub`: sign-agnostic subtraction
  * `int32.mul`: sign-agnostic multiplication (lower 32-bits)
  * `int32.sdiv`: signed division (result is truncated toward zero)
  * `int32.udiv`: unsigned division
  * `int32.srem`: signed remainder (result has the sign of the dividend)
  * `int32.urem`: unsigned remainder
  * `int32.and`: sign-agnostic logical and
  * `int32.ior`: sign-agnostic inclusive or
  * `int32.xor`: sign-agnostic exclusive or
  * `int32.shl`: sign-agnostic shift left
  * `int32.shr`: sign-agnostic logical shift right
  * `int32.sar`: sign-agnostic arithmetic shift right
  * `int32.eq`: sign-agnostic compare equal
  * `int32.ne`: sign-agnostic compare unequal
  * `int32.slt`: signed less than
  * `int32.sle`: signed less than or equal
  * `int32.ult`: unsigned less than
  * `int32.ule`: unsigned less than or equal
  * `int32.sgt`: signed greater than
  * `int32.sge`: signed greater than or equal
  * `int32.ugt`: unsigned greater than
  * `int32.uge`: unsigned greater than or equal
  * `int32.clz`: sign-agnostic count leading zero bits (defined for all values, including zero)
  * `int32.ctz`: sign-agnostic count trailing zero bits (defined for all values, including zero)
  * `int32.popcnt`: sign-agnostic count number of one bits

Shifts interpret their shift count operand as an unsigned value. When the shift
count is at least the bitwidth of the shift, `shl` and `shr` produce `0`, and
`sar` produces `0` if the value being shifted is non-negative, and `-1`
otherwise.

All comparison operations yield 32-bit integer results with `1` representing
`true` and `0` representing `false`.

## 64-bit integer operations

The same operations are available on 64-bit integers as the those available for
32-bit integers.

## Floating point operations

Floating point arithmetic follows the IEEE-754 standard, except that:
 - The sign bit and significand bit pattern of any NaN value returned from a
   floating point arithmetic operation other than `neg`, `abs`, and `copysign`
   are not specified. In particular, the "NaN propagation"
   section of IEEE-754 is not required. NaNs do propagate through arithmetic
   operations according to IEEE-754 rules, the difference here is that they do
   so without necessarily preserving the specific bit patterns of the original
   NaNs.
 - WebAssembly uses "non-stop" mode, and floating point exceptions are not
   otherwise observable. In particular, neither alternate floating point
   exception handling attributes nor the non-computational operations on status
   flags are supported. There is no observable difference between quiet and
   signalling NaN. However, positive infinity, negative infinity, and NaN are
   still always produced as result values to indicate overflow, invalid, and
   divide-by-zero conditions, as specified by IEEE-754.
 - WebAssembly uses the round-to-nearest ties-to-even rounding attribute, except
   where otherwise specified. Non-default directed rounding attributes are not
   supported.
 - The strategy for gradual underflow (subnormals) is
   [under discussion](https://github.com/WebAssembly/design/issues/148).

In the future, these limitations may be lifted, enabling
[full IEEE-754 support](FutureFeatures.md#full-ieee-754-conformance).

Note that not all operations required by IEEE-754 are provided directly.
However, WebAssembly includes enough functionality to support reasonable library
implementations of the remaining required operations.

  * `float32.add`: addition
  * `float32.sub`: subtraction
  * `float32.mul`: multiplication
  * `float32.div`: division
  * `float32.abs`: absolute value
  * `float32.neg`: negation
  * `float32.copysign`: copysign
  * `float32.ceil`: ceiling operation
  * `float32.floor`: floor operation
  * `float32.trunc`: round to nearest integer towards zero
  * `float32.nearestint`: round to nearest integer, ties to even
  * `float32.eq`: compare ordered and equal
  * `float32.ne`: compare unordered or unequal
  * `float32.lt`: compare ordered and less than
  * `float32.le`: compare ordered and less than or equal
  * `float32.gt`: compare ordered and greater than
  * `float32.ge`: compare ordered and greater than or equal
  * `float32.sqrt`: square root
  * `float32.min`: minimum (binary operator); if either operand is NaN, returns NaN
  * `float32.max`: maximum (binary operator); if either operand is NaN, returns NaN

  * `float64.add`: addition
  * `float64.sub`: subtraction
  * `float64.mul`: multiplication
  * `float64.div`: division
  * `float64.abs`: absolute value
  * `float64.neg`: negation
  * `float64.copysign`: copysign
  * `float64.ceil`: ceiling operation
  * `float64.floor`: floor operation
  * `float64.trunc`: round to nearest integer towards zero
  * `float64.nearestint`: round to nearest integer, ties to even
  * `float64.eq`: compare ordered and equal
  * `float64.ne`: compare unordered or unequal
  * `float64.lt`: compare ordered and less than
  * `float64.le`: compare ordered and less than or equal
  * `float64.gt`: compare ordered and greater than
  * `float64.ge`: compare ordered and greater than or equal
  * `float64.sqrt`: square root
  * `float64.min`: minimum (binary operator); if either operand is NaN, returns NaN
  * `float64.max`: maximum (binary operator); if either operand is NaN, returns NaN

`min` and `max` operations treat `-0.0` as being effectively less than `0.0`.

In floating point comparisons, the operands are *unordered* if either operand
is NaN, and *ordered* otherwise.

## Datatype conversions, truncations, reinterpretations, promotions, and demotions

  * `int32.wrap[int64]`: wrap a 64-bit integer to a 32-bit integer
  * `int32.trunc_signed[float32]`: truncate a 32-bit float to a signed 32-bit integer
  * `int32.trunc_signed[float64]`: truncate a 64-bit float to a signed 32-bit integer
  * `int32.trunc_unsigned[float32]`: truncate a 32-bit float to an unsigned 32-bit integer
  * `int32.trunc_unsigned[float64]`: truncate a 64-bit float to an unsigned 32-bit integer
  * `int32.reinterpret[float32]`: reinterpret the bits of a 32-bit float as a 32-bit integer
  * `int64.extend_signed[int32]`: extend a signed 32-bit integer to a 64-bit integer
  * `int64.extend_unsigned[int32]`: extend an unsigned 32-bit integer to a 64-bit integer
  * `int64.trunc_signed[float32]`: truncate a 32-bit float to a signed 64-bit integer
  * `int64.trunc_signed[float64]`: truncate a 64-bit float to a signed 64-bit integer
  * `int64.trunc_unsigned[float32]`: truncate a 32-bit float to an unsigned 64-bit integer
  * `int64.trunc_unsigned[float64]`: truncate a 64-bit float to an unsigned 64-bit integer
  * `int64.reinterpret[float64]`: reinterpret the bits of a 64-bit float as a 64-bit integer
  * `float32.demote[float64]`: demote a 64-bit float to a 32-bit float
  * `float32.cvt_signed[int32]`: convert a signed 32-bit integer to a 32-bit float
  * `float32.cvt_signed[int64]`: convert a signed 64-bit integer to a 32-bit float
  * `float32.cvt_unsigned[int32]`: convert an unsigned 32-bit integer to a 32-bit float
  * `float32.cvt_unsigned[int64]`: convert an unsigned 64-bit integer to a 32-bit float
  * `float32.reinterpret[int32]`: reinterpret the bits of a 32-bit integer as a 32-bit float
  * `float64.promote[float32]`: promote a 32-bit float to a 64-bit float
  * `float64.cvt_signed[int32]`: convert a signed 32-bit integer to a 64-bit float
  * `float64.cvt_signed[int64]`: convert a signed 64-bit integer to a 64-bit float
  * `float64.cvt_unsigned[int32]`: convert an unsigned 32-bit integer to a 64-bit float
  * `float64.cvt_unsigned[int64]`: convert an unsigned 64-bit integer to a 64-bit float
  * `float64.reinterpret[int64]`: reinterpret the bits of a 64-bit integer as a 64-bit float

Wrapping and extension of integer values always succeed.
Promotion and demotion of floating point values always succeed.
Demotion of floating point values uses round-to-nearest ties-to-even rounding,
and may overflow to infinity or negative infinity as specified by IEEE-754.
If the operand of promotion or demotion is NaN, the sign bit and significand
of the result are not specified.

Reinterpretations always succeed.

Conversions from integer to floating point always succeed, and use
round-to-nearest ties-to-even rounding.

Truncation from floating point to integer where IEEE-754 would specify an
invalid operation exception (e.g. when the floating point value is NaN or
outside the range which rounds to an integer in range) traps.


text:
body { background-color:#fff; color:#000; margin:0px 0px; padding:0px; font:70% arial, helvetica, sans-serif; text-align:center; overflow: hidden; }

td {font-size: 100%;}

img	{ behavior:expression(PNG.fix(this)); }

a				{ background:transparent; }
a:link 			{ color:#000; }
a:visited 		{ color:#000; }
a:visited:hover { color:#000; }
a:hover 		{ color:#000; }
a:active 		{ color:#000; }

#center		{ width:auto; max-width:1200px; margin:0px auto; text-align:left; }

#singleview		{ margin:20px 30px 10px 30px; text-align:center; }
#singleimg		{ overflow: auto; }
#singleview	p	{ font:thin 100% tahoma; margin:4px 0px; width:100%; }
#singleview	h2	{ font:bold 110% tahoma; margin:4px 0px; width:100%; }

#singleview .nav	{ margin:6px 0px 12px 0px; }
#singleview .gallery	{ background:url('../img/gallery.png') no-repeat center; padding:4px 10px 4px 10px; text-decoration: none; behavior:expression(PNG.fix(this)); }
#singleview .prev	{ background:url('../img/left.png') no-repeat left; padding:4px 20px 4px 4px; text-decoration: none; behavior:expression(PNG.fix(this));}
#singleview .next	{ background:url('../img/right.png') no-repeat right; padding:4px 4px 4px 20px;  text-decoration: none; behavior:expression(PNG.fix(this)); }
#singleview #prev.disabled { background:url('../img/left_disabled.png') no-repeat left; }
#singleview #next.disabled { background:url('../img/right_disabled.png') no-repeat right; }

#singleview .editsingle a	{ padding:1px 4px 1px 20px; margin:4px 8px; text-decoration:none; }
#singleview .editsingle a.delete 			{ background:url('../img/im-delete.png') no-repeat; behavior:expression(PNG.fix(this)); }
#singleview .editsingle a.delete:hover	{ background:#e3e0d8 url('../img/im-delete.png') no-repeat; behavior:expression(PNG.fix(this)); }
#singleview .editsingle a.delete_disabled 			{ background:url('../img/im-delete.png') no-repeat; behavior:expression(PNG.fix(this)); }
#singleview .editsingle a.delete_disabled:hover	{ background:url('../img/im-delete.png') no-repeat; behavior:expression(PNG.fix(this)); }
#singleview .editsingle a.edt 			{ background:url('../img/im-edit.png') no-repeat; behavior:expression(PNG.fix(this)); }
#singleview .editsingle a.edt:hover		{ background:#e3e0d8 url('../img/im-edit.png') no-repeat; behavior:expression(PNG.fix(this)); }
#singleview .editsingle a.disabled 			{ color: gray; background:url('../img/im-edit.png') no-repeat; behavior:expression(PNG.fix(this)); }
#singleview .editsingle a.disabled:hover	{ background:url('../img/im-edit.png') no-repeat; behavior:expression(PNG.fix(this)); }


text:
<?php
class Kwc_List_ImagesLinked_Component extends Kwc_List_Images_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['generators']['child']['component'] = 'Kwc_Composite_LinkImage_Component';
        $ret['componentName'] = trlKwfStatic('Linked Images');
        $ret['componentIcon'] = 'images';
        return $ret;
    }
}


text:
r"""
This code was generated by
\ / _    _  _|   _  _
 | (_)\/(_)(_|\/| |(/_  v1.0.0
      /       /
"""

from twilio.base.version import Version
from twilio.rest.preview.marketplace.available_add_on import AvailableAddOnList
from twilio.rest.preview.marketplace.installed_add_on import InstalledAddOnList

class Marketplace(Version):

    def __init__(self, domain):
        """
        Initialize the Marketplace version of Preview

        :returns: Marketplace version of Preview
        :rtype: twilio.rest.preview.marketplace.Marketplace.Marketplace
        """
        super(Marketplace, self).__init__(domain)
        self.version = 'marketplace'
        self._available_add_ons = None
        self._installed_add_ons = None

    @property
    def available_add_ons(self):
        """
        :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnList
        """
        if self._available_add_ons is None:
            self._available_add_ons = AvailableAddOnList(self)
        return self._available_add_ons

    @property
    def installed_add_ons(self):
        """
        :rtype: twilio.rest.preview.marketplace.installed_add_on.InstalledAddOnList
        """
        if self._installed_add_ons is None:
            self._installed_add_ons = InstalledAddOnList(self)
        return self._installed_add_ons

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        return '<Twilio.Preview.Marketplace>'


text:
package net.ljcomputing.ecsr.service.ci.impl;

import net.ljcomputing.ecsr.domain.ci.ConfigurationItem;
import net.ljcomputing.ecsr.repository.ci.ConfigurationItemRepository;
import net.ljcomputing.ecsr.service.ci.ConfigurationItemService;
import net.ljcomputing.ecsr.service.impl.AbstractDomainServiceImpl;

/**
 * Abstract implementation of configuration items services.
 *
 * @author James G. Willmore
 *
 */
public abstract class AbstractConfigurationItemService
    <T extends ConfigurationItem, R extends ConfigurationItemRepository<T>>
    extends AbstractDomainServiceImpl<T, R>
    implements ConfigurationItemService<T, R> {

  /**
   * Instantiates a new abstract configuration item service.
   */
  protected AbstractConfigurationItemService() {
    super();
  }

  /**
   * Find by name.
   *
   * @param name the name
   * @return the database
   */
  @Override
  public abstract T findByName(String name);
}


text:
require 'rails_helper'

RSpec.describe WorkoutsController, type: :controller do

  let(:user) { User.new( name: 'Aaron', email: 'a@a.com',password: 'password') }

  let(:workout) {Workout.new(name: 'bench press', reps: 8, sets: 4, weight: '50', completed: true, phase: 1, rest: 30, user_id: @user.id,day: 1,note: 'note')}

  describe 'Get #index' do
  end

  describe 'Get #show' do

    before(:each) do
    @user = User.create( name: 'Aaron', email: 'b@b.com',password: 'password')
    @workout = Workout.create(name: 'bench press', reps: 8, sets: 4, weight: '50', completed: true, phase: 1, rest: 30, user_id: @user.id,day: 1,note: 'note')
    end

    # need to complete test for this
    # it 'responds with 200' do
    #   get user_workout_path(user_id: @user.id, id: @workout.id)
    #   expect(response).to be true
    # end
  end

  describe 'Get #new' do
  end

  describe 'Get #edit' do
  end

  describe 'Get #update' do
  end

  describe 'Get #destroy' do
  end

end


text:
package de.slackspace.tinkerclock.led;

import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import de.slackspace.tinkerclock.device.Led;

public class LedStripManagerIT {

	@Test
	public void showSingleLed() throws InterruptedException {
		LedStripManager manager = new LedStripManager();
		boolean connect = manager.connect();
		assertTrue(connect);

		List<Led> leds = new ArrayList<Led>();
		leds.add(new Led(110, "#ff0000"));
		leds.add(new Led(111, "#ff0000"));
		leds.add(new Led(112, "#ff0000"));
		leds.add(new Led(113, "#ff0000"));
		manager.getLedStrip().setLeds(leds);

		Thread.sleep(5000);

		manager.disconnect();
	}
}


text:
import {AchievementProps} from "../Achievement/Achievement";
import LoginService from "../../service/LoginService";

export interface TeamProps {
    _id: string;
    name: string;
    botId?: string;
    image?: string;
    unlockedAchievements?: AchievementProps[]
}

export class Team extends React.Component<TeamProps, any> {

    constructor(props: TeamProps) {
        super(props);
        this.getEditButton = this.getEditButton.bind(this);
    }

    getEditButton() {
        if (LoginService.getCurrentTeam() == this.props._id || LoginService.isAdmin()) {
            return <a className="btn btn-primary" href={`teams/${this.props._id}/edit`}>

        }
    }

    render() {
        return (

{this.props.name}

                            <a className="btn btn-primary" href={`teams/${this.props._id}`}>

                            {this.getEditButton()}

        )
    }
}


text:
import { GraphQLInt, GraphQLString, GraphQLID, GraphQLBoolean } from 'graphql';

import PageType from '../types/PageType';
import MessageType from '../types/MessageType';
import Message from '../models/Message';
import MessageTypeEnum from '../types/MessageTypeEnum';
import knex from '../knex';
import CategoryTypeEnum from '../types/CategoryTypeEnum';

const messageObjects = {
  type: PageType(MessageType),
  args: {
    first: {
      type: GraphQLInt,
    },
    isPublished: {
      type: GraphQLBoolean,
    },
    messageType: {
      type: MessageTypeEnum,
    },
    category: {
      type: CategoryTypeEnum,
    },

    after: {
      type: GraphQLString,
    },
    userId: {
      type: GraphQLID,
    },
  },
  resolve: async (
    parent,
    {
      first = 10,
      after = '',
      userId,
      isPublished = true,
      messageType,
      category,
    },
    { viewer, loaders },
  ) => {
    const pagination = Buffer.from(after, 'base64').toString('ascii');
    let [cursor = new Date(), id = 0] = pagination ? pagination.split('$') : []; //eslint-disable-line
    id = Number(id);

    const table = messageType ? `${messageType}s` : 'messages';
    const objectIds = await knex(table)
      .modify(queryBuilder => {
        if (messageType === 'note') {
          queryBuilder.where({
            is_published: isPublished,
            ...(category && { category }),
          });
        } else {
          queryBuilder.where({
            sender_id: userId || viewer.id,
          });
        }
      })
      .whereRaw(`(${table}.created_at, ${table}.id) < (?,?)`, [cursor, id])
      .limit(first)
      .orderBy(`${table}.created_at`, 'desc')
      .orderBy(`${table}.id`, 'desc')
      .select(`${table}.id as id`, `${table}.created_at as time`);

    let queries;
    if (messageType) {
      queries = objectIds.map(oId =>
        Promise.resolve(
          new Message({
            id: `mo${oId.id}`,
            message_type: messageType,
            message_object_id: oId.id,
          }),
        ),
      );
    } else {
      queries = objectIds.map(p => Message.gen(viewer, p.id, loaders));
    }

    const messagesSet = objectIds.reduce((acc, curr) => {
      acc[curr.id] = curr;
      return acc;
    }, {});

    const data = await Promise.all(queries);
    const edges = data.map(p => ({ node: p }));
    let endCursor;
    if (edges.length > 0) {
      const lastNode = edges[edges.length - 1].node;
      const objId = lastNode.id.slice(2);
      Buffer.from(
        `${new Date(messagesSet[objId].time).toJSON()}$${objId}`,
      ).toString('base64');
    } else {
      endCursor = null;
    }

    const hasNextPage = edges.length === first;
    return {
      edges,
      pageInfo: {
        startCursor: null,
        endCursor,
        hasNextPage,
      },
    };
  },
};

export default messageObjects;


text:
package io.sundr.dsl.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * An annotation to specify that the current annotation is using for transition filtering.
 */
@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.SOURCE)
public @interface Option {
}


text:
const Eureka = require('eureka-js-client').Eureka;

/**
 * Connect to Eureka service registry
 *
 * @param  {string} name of the server
 * @param  {string} host of the server
 * @param  {number} port of the server
 * @return {void}
 */
function register(name, host, port) {
  const instance = {
    port: {
      $: port,
      '@enabled': 'true',
    },
    app: name,
    hostName: host,
    vipAddress: process.env.EUREKA_VIP || host,
    statusPageUrl: `http://${host}:${port}/admin/info`,
    healthCheckUrl: `http://${host}:${port}/admin/health`,
    homePageUrl: `http://${host}:${port}/`,
    dataCenterInfo: {
      '@class': 'com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo',
      name: 'MyOwn',
    },
  };

  const eureka = {
    host: process.env.EUREKA_HOST || 'localhost',
    port: process.env.EUREKA_PORT || '8761',
    servicePath: '/eureka/apps/',
  };

  const client = new Eureka({
    instance,
    eureka,
  });

  client.on('started', () => {
    // eslint-disable-next-line no-console
    console.info(`${name} registered to eureka on "${eureka.host}:${eureka.port}"`);
  });

  client.on('deregistered', () => {
    // eslint-disable-next-line no-console
    console.info(`${name} deregistered from eureka`);
  });

  client.start();
}

module.exports = {
  register,
};


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

namespace _0437
{
    /**
 * Definition for a binary tree node. */
    public class TreeNode
    {
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int x) { val = x; }
    }

    public class Solution
    {
        public int PathSum(TreeNode root, int target)
        {
            // key: sum  value: # of ways
            var ways = new Dictionary<int, int>();
            ways[0] = 1;
            return DFS(root, target, 0, ways);
        }

        private int DFS(TreeNode root, int target, int sum, Dictionary<int, int> ways)
        {
            if (root == null)
            {
                return 0;
            }

            sum += root.val;
            var ans = ways.GetValueOrDefault(sum - target);
            ways[sum] = ways.GetValueOrDefault(sum) + 1;

            ans += DFS(root.left, target, sum, ways) + DFS(root.right, target, sum, ways);

            ways[sum]--;
            return ans;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var n1 = new TreeNode(1);
            var n2 = new TreeNode(2);
            var n3 = new TreeNode(3);
            var n4 = new TreeNode(4);
            var n5 = new TreeNode(5);
            n1.right = n2;
            n2.right = n3;
            n3.right = n4;
            n4.right = n5;

            Console.WriteLine(new Solution().PathSum(n1, 3));
        }
    }
}


text:
using base::android::ConvertJavaStringToUTF8;
using base::android::JavaParamRef;

namespace android_webview {

namespace {

// Array of features exposed through the Java ChromeFeatureList API. Entries in
// this array may either refer to features defined in the header of this file or
// in other locations in the code base (e.g. content/, components/, etc).
const base::Feature* kFeaturesExposedToJava[] = {
    &features::kWebViewCollectNonembeddedMetrics,
    &features::kWebViewConnectionlessSafeBrowsing,
};

const base::Feature* FindFeatureExposedToJava(const std::string& feature_name) {
  for (size_t i = 0; i < base::size(kFeaturesExposedToJava); ++i) {
    if (kFeaturesExposedToJava[i]->name == feature_name)
      return kFeaturesExposedToJava[i];
  }
  NOTREACHED() << "Queried feature cannot be found in AwFeatureList: "
               << feature_name;
  return nullptr;
}

}  // namespace

static jboolean JNI_AwFeatureList_IsEnabled(
    JNIEnv* env,
    const JavaParamRef<jstring>& jfeature_name) {
  const base::Feature* feature =
      FindFeatureExposedToJava(ConvertJavaStringToUTF8(env, jfeature_name));
  return base::FeatureList::IsEnabled(*feature);
}

}  // namespace android_webview


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _fs = require('fs');

var _instrumenter = require('../../instrumenter');

var _istanbul = require('istanbul');

var _mkdirp = require('mkdirp');

var _mkdirp2 = _interopRequireDefault(_mkdirp);

var _module = require('module');

var _module2 = _interopRequireDefault(_module);

var _objectAssign = require('object-assign');

var _objectAssign2 = _interopRequireDefault(_objectAssign);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _which = require('which');

var _which2 = _interopRequireDefault(_which);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

//

//

exports.default = coverCmd;

//

function coverCmd(opts) {
  var config = overrideConfigWith(opts);
  var istanbulCoveragePath = _path2.default.resolve(config.reporting.dir());
  var reporter = new _istanbul.Reporter(config, istanbulCoveragePath);

  var cmd = opts.cmd;

  var cmdArgs = opts['--'] || [];

  if (!(0, _fs.existsSync)(cmd)) {
    try {
      cmd = _which2.default.sync(cmd);
    } catch (ex) {
      return processEnding('Unable to resolve file [' + cmd + ']');
    }
  } else {
    cmd = _path2.default.resolve(cmd);
  }

  if (opts.verbose) console.error('Isparta options : \n ', opts);

  var excludes = config.instrumentation.excludes(true);
  enableHooks();

  ////

  function overrideConfigWith(opts) {
    var overrides = {
      verbose: opts.verbose,
      instrumentation: {
        root: opts.root,
        'default-excludes': opts['default-excludes'],
        excludes: opts.excludes,
        'include-all-sources': opts['include-all-sources'],
        // preload-sources is deprecated
        // TODO(douglasduteil): remove this option
        'preload-sources': opts['preload-sources']
      },
      reporting: {
        reports: opts.report,
        print: opts.print,
        dir: opts.dir
      },
      hooks: {
        'hook-run-in-context': opts['hook-run-in-context'],
        'post-require-hook': opts['post-require-hook'],
        'handle-sigint': opts['handle-sigint']
      }
    };

    return _istanbul.config.loadFile(opts.config, overrides);
  }

  function enableHooks() {
    opts.reportingDir = _path2.default.resolve(config.reporting.dir());
    _mkdirp2.default.sync(opts.reportingDir);
    reporter.addAll(config.reporting.reports());

    if (config.reporting.print() !== 'none') {
      switch (config.reporting.print()) {
        case 'detail':
          reporter.add('text');
          break;
        case 'both':
          reporter.add('text');
          reporter.add('text-summary');
          break;
        default:
          reporter.add('text-summary');
          break;
      }
    }

    excludes.push(_path2.default.relative(process.cwd(), _path2.default.join(opts.reportingDir, '**', '*')));

    (0, _istanbul.matcherFor)({
      root: config.instrumentation.root() || process.cwd(),
      includes: opts.include || config.instrumentation.extensions().map(function (ext) {
        return '**/*' + ext;
      }),
      excludes: excludes
    }, function (err, matchFn) {
      if (err) {
        return processEnding(err);
      }

      prepareCoverage(matchFn);
      runCommandFn();
    });
  }

  function prepareCoverage(matchFn) {
    var coverageVar = '$$cov_' + Date.now() + '$$';
    var instrumenter = new _instrumenter.Instrumenter({ coverageVariable: coverageVar });
    var transformer = instrumenter.instrumentSync.bind(instrumenter);

    _istanbul.hook.hookRequire(matchFn, transformer, (0, _objectAssign2.default)({ verbose: opts.verbose }, config.instrumentation.config));

    global[coverageVar] = {};

    if (config.hooks.handleSigint()) {
      process.once('SIGINT', process.exit);
    }

    process.once('exit', function (code) {
      if (code) {
        process.exit(code);
      }
      var file = _path2.default.resolve(opts.reportingDir, 'coverage.json');
      var cov = undefined,
          collector = undefined;

      if (typeof global[coverageVar] === 'undefined' || Object.keys(global[coverageVar]).length === 0) {
        console.error('No coverage information was collected, exit without writing coverage information');
        return;
      } else {
        cov = global[coverageVar];
      }

      _mkdirp2.default.sync(opts.reportingDir);
      if (config.reporting.print() !== 'none') {
        console.error(Array(80 + 1).join('='));
        console.error('Writing coverage object [' + file + ']');
      }
      (0, _fs.writeFileSync)(file, JSON.stringify(cov), 'utf8');
      collector = new _istanbul.Collector();
      collector.add(cov);
      if (config.reporting.print() !== 'none') {
        console.error('Writing coverage reports at [' + opts.reportingDir + ']');
        console.error(Array(80 + 1).join('='));
      }
      reporter.write(collector, true, processEnding);
    });

    if (config.instrumentation.includeAllSources()) {
      matchFn.files.forEach(function (file) {
        if (opts.verbose) {
          console.error('Preload ' + file);
        }
        try {
          require(file);
        } catch (ex) {
          if (opts.verbose) {
            console.error('Unable to preload ' + file);
          }
          // swallow
        }
      });
    }
  }

  function runCommandFn() {
    process.argv = ["node", cmd].concat(cmdArgs);
    if (opts.verbose) {
      console.log('Running: ' + process.argv.join(' '));
    }
    process.env.running_under_istanbul = 1;
    _module2.default.runMain(cmd, null, true);
  }
}

//

function processEnding(err) {
  if (err) {
    console.error(err);
    process.exit(1);
  }
  process.exit(0);
}