text:
<?php

namespace PayPal\Exception;

/**
 * Class PayPalMissingCredentialException
 *
 * @package PayPal\Exception
 */
class PayPalMissingCredentialException extends \Exception
{

    /**
     * Default Constructor
     *
     * @param string $message
     * @param int  $code
     */
    public function __construct($message = null, $code = 0)
    {
        parent::__construct($message, $code);
    }

    /**
     * prints error message
     *
     * @return string
     */
    public function errorMessage()
    {
        $errorMsg = 'Error on line ' . $this->getLine() . ' in ' . $this->getFile()
            . ': <b>' . $this->getMessage() . '</b>';

        return $errorMsg;
    }
}


text:
[![Build Status](https://travis-ci.org/jeffhollan/docdb-connector.svg?branch=master)](https://travis-ci.org/jeffhollan/docdb-connector)

[![Deploy to Azure](http://azuredeploy.net/deploybutton.png)](https://azuredeploy.net/)

This is a REST API Connector for [Azure DocumentDB](https://azure.microsoft.com/en-us/services/documentdb/) built to work with Azure Logic Apps.

## Setup and Configuration

To setup, simply click the [Deploy to Azure]((https://azuredeploy.net/) button.  This will start a deployment script to provision and clone this repository in your Azure subscription.

### Setting a key as an environmental variable

To prevent you from having to reference your key during every action, you can add an Application Setting after deployment for your DocumentDB access key.  Simply open the web site in Azure, click **Settings** -> **Application Settings** and add an applicaiton setting for `masterkey` with the value being your DocumentDB access key.

## Actions

This connector comes with 6 actions:

- Get Document
- Create Document
- Update Document
- Upsert Document
- Delete Document
- Query Documents

## Accessing Data within a Logic App

One piece of note with this connector is if you need to parse the data returned from a document.  Since the nature of DocumentDB and NoSQL is that there isn't a defined schema, the only properties selectable as tokens are the ID.  If you have other properties you want to access, please use the [Logic App Workflow Definition Language](http://aka.ms/logicappsdocs) and the `@body()` command.  For example if I retrieved a document that looked like this from a **Get Document** step:

``` json
{
    "id": "myID",
    "type": "order",
    "placedBy": {
        "name": "Jeff"
    }
    ...
}
```

and I wanted to access the `"name"` property I could use the following workflow language in my logic app: `@body('Get_Document')['placedBy']['name']`

In addition the **Query Documents** action outputs an array of **Documents** so you would need to put **Documents** in a foreach loop and could access each document property with an expression like `@item()['placedBy']['name']`.

Please refer to the [DocumentDB REST API](https://msdn.microsoft.com/en-us/library/azure/mt489082.aspx#Documents) reference for an understanding of the shape of the outputs returned.

redpajama_set_name: RedPajamaGithub


text:
package ru.annin.store.presentation.ui.view;

import android.support.annotation.StringRes;

/**
 *
Представление экрана "Номенклатура".

 *
 * @author Pavel Annin.
 */
public interface DetailNomenclatureView {

    void onFinish();

    String getString(@StringRes int resId);
}


text:
| 正體中文 |

Project template to create as simple as possible implementation of a blockchain with Node.js 4+ and JavaScript.

# Blockchain Starter Kit

An extremely simple blockchain: a project template to create as simple as possible blockchain system.

Block # 0, also known as Genesis Block, is the first block of its blockchain system. This project provides a minimal blockchain implementation for teaching and research, and you can be provided the simplest way to understand the blockchain.

## Features

* Import _Genesis Block_
* An exetremly simple mining algorithm
* A simple and lightweight REST-style RPC system
* A p2p network system over WebSocket
* There is no proof-of-work implementation

## Testing

To start a miner node:

```
git clone https://github.com/jollen/blockchain-starter-kit.git
cd blockchain-starter-kit
npm install
node index.js
```

The server will start at ```localhost:8000``` by default. To start another miner node at port ```8001``` and join an existing network:

```
export PORT=8001
node node1.js
```

After ```index.js``` has been joined, its _successor_ will become ```node1.js```. To fix the default join node, please open ```node1.js``` and modify the ```join``` property:

```
server.start({
    onstart: onstart,
	onmessage: onmessage,
	join: {
		address: 'localhost',
		port: 8000
	}
});
```

## License

Copyright (C) 2016-present Jollen. The source code is licensed under the MIT license found in the [LICENSE](LICENSE) file.


text:
/**
 * @requires SuperMap/ServiceEventArgs.js
 * @requires SuperMap/REST/GetFieldsResult.js
 */

/**
 * Class: SuperMap.REST.GetFieldsEventArgs
 * 字段查询服务事件数据类。
 * 该类包含了从服务端传回的字段查询结果数据。
 *
 * Inherits from:
 *  - <SuperMap.ServiceEventArgs>
 */
SuperMap.REST.GetFieldsEventArgs = SuperMap.Class(SuperMap.ServiceEventArgs, {

    /**
     * APIProperty: result
     * {<SuperMap.REST.GetFieldsResult>} 服务端返回的字段查询结果数据。
     */
    result: null,

    /**
     * Constructor: SuperMap.REST.GetFieldsEventArgs
     * 字段查询服务事件数据类构造函数。
     *
     * Parameters:
     * result - {<SuperMap.REST.GetFieldsResult>} 服务端返回的字段查询结果数据。
     * originResult - {Object} 服务端返回的用 JSON 对象表示的字段查询结果数据。
     */
    initialize: function(result, originResult) {
        SuperMap.ServiceEventArgs.prototype.initialize.apply(this, [originResult]);
        var me = this;
        me.result = result;
    },

    /**
     * APIMethod: destroy
     * 释放资源,将引用资源的属性置空。
     */
    destroy: function() {
        SuperMap.ServiceEventArgs.prototype.destroy.apply(this);
        var me = this;
        if (me.result) {
            me.result.destroy();
            me.result = null;
        }
    },

    CLASS_NAME: "SuperMap.REST.GetFieldsEventArgs"
});


text:
import Play from "./states/Play";
import Preload from "./states/Preload";
import {Output} from "./terminal/output";

export default class Monitor {
	private state: Play;
	private currentImage: Phaser.Sprite;
	private output: Output;

	constructor(state: Play) {
		this.state = state;
	}

	static loadAssets (state: Preload) {
        state.load.image('scenes/rain-forest', 'assets/images/scenes/rain-forest.png');
        state.load.image('scenes/rocky-mountain', 'assets/images/scenes/rocky-mountain.png');
        state.load.image('scenes/grassland', 'assets/images/scenes/grassland.png');
        state.load.image('scenes/sand-desert', 'assets/images/scenes/sand-desert.png');
        state.load.image('scenes/ice-field', 'assets/images/scenes/ice-field.png');
        state.load.image('scenes/sea-shore', 'assets/images/scenes/sea-shore.png');
        state.load.image('scenes/toundra', 'assets/images/scenes/toundra.png');
	}

	showImage (name: string, opacity: number, ratio: number = 1) {
		if (this.currentImage) {
			this.currentImage.kill();
		}
		this.currentImage = this.state.middleground.create(490 * 1.5, 135 * 1.5, name);
		this.currentImage.width = 100 * 1.5 / ratio;
		this.currentImage.height = 73 * 1.5 / ratio;
		this.currentImage.alpha = opacity;
	}

	update() {
	}

	setOutput (output: Output) {
		this.output = output;
		output.monitor = this;
	}
}


text:
// file:	Unsupervised\PCA.cs
//
// summary:	Implements the pca class
using System;
using numl.Model;
using System.Linq;
using numl.Math.LinearAlgebra;
using System.Collections.Generic;

namespace numl.Unsupervised
{
    /// A pca.
    public class PCA
    {
        /// Gets or sets the eigenvalues.
        /// <value>The eigenvalues.</value>
        public Vector Eigenvalues { get; private set; }
        /// Gets or sets the eigenvectors.
        /// <value>The eigenvectors.</value>
        public Matrix Eigenvectors { get; private set; }
        /// Gets or sets the x coordinate.
        /// <value>The x coordinate.</value>
        public Matrix X { get; private set; }
        /// Gets or sets the reduced.
        /// <value>The reduced.</value>
        public Matrix Reduced { get; private set; }
        /// Generates.
        /// <param name="matrix">The matrix.</param>
        public void Generate(Matrix matrix)
        {
            // generate centered matrix
            // (using a copy since centering is in place)
            X = matrix
                    .Copy()
                    .Center(VectorType.Col);

            // compute eigen-decomposition
            // of covariance matrix
            var eigs = X.Covariance().Eigs();
            Eigenvalues = eigs.Item1;
            Eigenvectors = eigs.Item2;
        }
        /// Generates.
        /// <param name="descriptor">The descriptor.</param>
        /// <param name="examples">The examples.</param>
        public void Generate(Descriptor descriptor, IEnumerable<object> examples)
        {
            // generate data matrix
            var x = descriptor.Convert(examples).ToMatrix();
            Generate(x);
        }
        /// Reduces.
        /// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception>
        /// <param name="maxdim">The maxdim.</param>
        /// <returns>A Matrix.</returns>
        public Matrix Reduce(int maxdim)
        {
            if(maxdim < 1) throw new InvalidOperationException("Cannot reduce to less than 1 dimension!");
            if (X == null || Eigenvalues == null || Eigenvectors == null)
                throw new InvalidOperationException("Cannot reduce until pca data has been generated");

            // get columns in reverse order
            // and stuff into matrix
            Matrix reduc = Eigenvectors.GetCols()
                                .Take(maxdim)
                                .ToMatrix();

            Reduced = reduc * X.T;

            return Reduced;
        }
    }
}


text:
package org.apache.druid.indexing.common.actions;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import org.apache.druid.indexing.common.task.Task;
import org.apache.druid.timeline.DataSegment;

import java.util.Set;

/**
 * Insert segments into metadata storage. The segment versions must all be less than or equal to a lock held by
 * your task for the segment intervals.
 * <p/>
 * Word of warning: Very large "segments" sets can cause oversized audit log entries, which is bad because it means
 * that the task cannot actually complete. Callers should avoid this by avoiding inserting too many segments in the
 * same action.
 */
public class SegmentInsertAction implements TaskAction<Set<DataSegment>>
{
  private final Set<DataSegment> segments;

  @JsonCreator
  public SegmentInsertAction(
      @JsonProperty("segments") Set<DataSegment> segments
  )
  {
    this.segments = ImmutableSet.copyOf(segments);
  }

  @JsonProperty
  public Set<DataSegment> getSegments()
  {
    return segments;
  }

  @Override
  public TypeReference<Set<DataSegment>> getReturnTypeReference()
  {
    return new TypeReference<Set<DataSegment>>()
    {
    };
  }

  /**
   * Behaves similarly to
   * {@link org.apache.druid.indexing.overlord.IndexerMetadataStorageCoordinator#announceHistoricalSegments},
   * with startMetadata and endMetadata both null.
   */
  @Override
  public Set<DataSegment> perform(Task task, TaskActionToolbox toolbox)
  {
    return SegmentTransactionalInsertAction.appendAction(segments, null, null).perform(task, toolbox).getSegments();
  }

  @Override
  public boolean isAudited()
  {
    return true;
  }

  @Override
  public String toString()
  {
    return "SegmentInsertAction{" +
           "segments=" + Iterables.transform(segments, DataSegment::getId) +
           '}';
  }
}


text:
package ws.argo.DemoWebClient.Browser;

class ProbeRespondToAddress {
	public String respondToAddress;
	public Integer respondToPort;

	public String toString() {
		return respondToAddress+":"+respondToPort;
	}
}


text:
using System;
using System.IO;

namespace Microsoft.Framework.WebEncoders
{
    /// <summary>
    /// Helpful extension methods for the encoder classes.
    /// </summary>
    internal static class EncoderExtensions
    {
        /// <summary>
        /// HTML-encodes a string and writes the result to the supplied output.
        /// </summary>
        /// <remarks>
        /// The encoded value is also safe for inclusion inside an HTML attribute
        /// as long as the attribute value is surrounded by single or double quotes.
        /// </remarks>
        public static void HtmlEncode(this IHtmlEncoder htmlEncoder, string value, TextWriter output)
        {
            if (htmlEncoder == null)
            {
                throw new ArgumentNullException(nameof(htmlEncoder));
            }

            if (!String.IsNullOrEmpty(value))
            {
                htmlEncoder.HtmlEncode(value, 0, value.Length, output);
            }
        }

        /// <summary>
        /// JavaScript-escapes a string and writes the result to the supplied output.
        /// </summary>
        public static void JavaScriptStringEncode(this IJavaScriptStringEncoder javaScriptStringEncoder, string value, TextWriter output)
        {
            if (javaScriptStringEncoder == null)
            {
                throw new ArgumentNullException(nameof(javaScriptStringEncoder));
            }

            if (!String.IsNullOrEmpty(value))
            {
                javaScriptStringEncoder.JavaScriptStringEncode(value, 0, value.Length, output);
            }
        }

        /// <summary>
        /// URL-encodes a string and writes the result to the supplied output.
        /// </summary>
        /// <remarks>
        /// The encoded value is safe for use in the segment, query, or
        /// fragment portion of a URI.
        /// </remarks>
        public static void UrlEncode(this IUrlEncoder urlEncoder, string value, TextWriter output)
        {
            if (urlEncoder == null)
            {
                throw new ArgumentNullException(nameof(urlEncoder));
            }

            if (!String.IsNullOrEmpty(value))
            {
                urlEncoder.UrlEncode(value, 0, value.Length, output);
            }
        }
    }
}


text:
package test

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"mime"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

// MakeSimpleRequest returns a http.Request. The returned request object can be
// further prepared by adding headers and query string parmaters, for instance.
func MakeSimpleRequest(method string, urlStr string, payload interface{}) *http.Request {
	var s string

	if payload != nil {
		b, err := json.Marshal(payload)
		if err != nil {
			panic(err)
		}
		s = fmt.Sprintf("%s", b)
	}

	r, err := http.NewRequest(method, urlStr, strings.NewReader(s))
	if err != nil {
		panic(err)
	}
	r.Header.Set("Accept-Encoding", "gzip")
	if payload != nil {
		r.Header.Set("Content-Type", "application/json")
	}

	return r
}

// CodeIs compares the rescorded status code
func CodeIs(t *testing.T, r *httptest.ResponseRecorder, expectedCode int) {
	if r.Code != expectedCode {
		t.Errorf("Code %d expected, got: %d", expectedCode, r.Code)
	}
}

// HeaderIs tests the first value for the given headerKey
func HeaderIs(t *testing.T, r *httptest.ResponseRecorder, headerKey, expectedValue string) {
	value := r.HeaderMap.Get(headerKey)
	if value != expectedValue {
		t.Errorf(
			"%s: %s expected, got: %s",
			headerKey,
			expectedValue,
			value,
		)
	}
}

func ContentTypeIsJSON(t *testing.T, r *httptest.ResponseRecorder) {

	mediaType, params, _ := mime.ParseMediaType(r.HeaderMap.Get("Content-Type"))
	charset := params["charset"]

	if mediaType != "application/json" {
		t.Errorf(
			"Content-Type media type: application/json expected, got: %s",
			mediaType,
		)
	}

	if charset != "" && strings.ToUpper(charset) != "UTF-8" {
		t.Errorf(
			"Content-Type charset: must be empty or UTF-8, got: %s",
			charset,
		)
	}
}

func ContentEncodingIsGzip(t *testing.T, r *httptest.ResponseRecorder) {
	HeaderIs(t, r, "Content-Encoding", "gzip")
}

func BodyIs(t *testing.T, r *httptest.ResponseRecorder, expectedBody string) {
	body := r.Body.String()
	if body != expectedBody {
		t.Errorf("Body '%s' expected, got: '%s'", expectedBody, body)
	}
}

func DecodeJSONPayload(r *httptest.ResponseRecorder, v interface{}) error {
	content, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return err
	}
	err = json.Unmarshal(content, v)
	if err != nil {
		return err
	}
	return nil
}

type Recorded struct {
	T        *testing.T
	Recorder *httptest.ResponseRecorder
}

// RunRequest runs a HTTP request through the given handler
func RunRequest(t *testing.T, handler http.Handler, request *http.Request) *Recorded {
	recorder := httptest.NewRecorder()
	handler.ServeHTTP(recorder, request)
	return &Recorded{t, recorder}
}

func (rd *Recorded) CodeIs(expectedCode int) {
	CodeIs(rd.T, rd.Recorder, expectedCode)
}

func (rd *Recorded) HeaderIs(headerKey, expectedValue string) {
	HeaderIs(rd.T, rd.Recorder, headerKey, expectedValue)
}

func (rd *Recorded) ContentTypeIsJSON() {
	ContentTypeIsJSON(rd.T, rd.Recorder)
}

func (rd *Recorded) ContentEncodingIsGzip() {
	rd.HeaderIs("Content-Encoding", "gzip")
}

func (rd *Recorded) BodyIs(expectedBody string) {
	BodyIs(rd.T, rd.Recorder, expectedBody)
}

func (rd *Recorded) DecodeJSONPayload(v interface{}) error {
	return DecodeJSONPayload(rd.Recorder, v)
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

void free_anything(int *p) {
    free(p);
}

int read_element(int *array, int index) {
    int x = array[index];
    return x;
}

int main ()
{
    int never_allocated;
    int *free_twice = malloc (sizeof (int));
    int *use_after_free = malloc (sizeof (int));
    int *never_free = malloc (sizeof (int));
    int array1[100];
    int *array2 = malloc (100 * sizeof (int));

    // valgrind does not bounds-check static arrays
    read_element(array1, 0);
    read_element(array1, 99);

    // but it does bounds-check dynamic arrays
    read_element(array2, 0);
    read_element(array2, 99);

    // and it catches use after free
    free(use_after_free);
    //*use_after_free = 17;

    // never_free is definitely lost
    free_anything(never_free);
    //*never_free = 17;

    free(free_twice);
    free(array2);

    return 0;
}


text:
#include <string.h>
#include "bt_trace.h"
#include "bt_defs.h"
#include "controller.h"
#include "buffer_allocator.h"
#include "hci_internals.h"
#include "hci_layer.h"
#include "packet_fragmenter.h"

#include "hash_map.h"
#include "hash_functions.h"

#define APPLY_CONTINUATION_FLAG(handle) (((handle) & 0xCFFF) | 0x1000)
#define APPLY_START_FLAG(handle) (((handle) & 0xCFFF) | 0x2000)
#define SUB_EVENT(event) ((event) & MSG_SUB_EVT_MASK)
#define GET_BOUNDARY_FLAG(handle) (((handle) >> 12) & 0x0003)

#define HANDLE_MASK 0x0FFF
#define START_PACKET_BOUNDARY 2
#define CONTINUATION_PACKET_BOUNDARY 1
#define L2CAP_HEADER_SIZE       4

// TODO(zachoverflow): find good value for this
#define NUMBER_OF_BUCKETS 42
uint16_t data_len = 0;

// Our interface and callbacks
static const packet_fragmenter_t interface;
static const allocator_t *buffer_allocator;
static const controller_t *controller;
static const packet_fragmenter_callbacks_t *callbacks;
static hash_map_t *partial_packets;
static BT_HDR *current_fragment_packet;

static void init(const packet_fragmenter_callbacks_t *result_callbacks)
{
    current_fragment_packet = NULL;
    callbacks = result_callbacks;
    partial_packets = hash_map_new(NUMBER_OF_BUCKETS, hash_function_naive, NULL, NULL, NULL);
}

static void cleanup()
{
    if (partial_packets) {
        hash_map_free(partial_packets);
    }
}

static BT_HDR *fragment_get_current_packet()
{
    return current_fragment_packet;
}

static void fragment_and_dispatch(BT_HDR *packet)
{
    uint16_t continuation_handle;
    uint16_t max_data_size, max_packet_size, remaining_length;
    uint16_t event = packet->event & MSG_EVT_MASK;
    uint8_t *stream = packet->data + packet->offset;

    assert(packet != NULL);

    // We only fragment ACL packets
    if (event != MSG_STACK_TO_HC_HCI_ACL) {
        callbacks->fragmented(packet, true);
        return;
    }

    max_data_size =
        SUB_EVENT(packet->event) == LOCAL_BR_EDR_CONTROLLER_ID ?
        controller->get_acl_data_size_classic() :
        controller->get_acl_data_size_ble();

    max_packet_size = max_data_size + HCI_ACL_PREAMBLE_SIZE;
    remaining_length = packet->len;

    STREAM_TO_UINT16(continuation_handle, stream);
    continuation_handle = APPLY_CONTINUATION_FLAG(continuation_handle);
    if (remaining_length > max_packet_size) {
        current_fragment_packet = packet;
        UINT16_TO_STREAM(stream, max_packet_size);
        packet->len = max_packet_size;
        callbacks->fragmented(packet, false);
        packet->offset += max_data_size;
        remaining_length -= max_data_size;
        packet->len = remaining_length;

        // Write the ACL header for the next fragment
        stream = packet->data + packet->offset;
        UINT16_TO_STREAM(stream, continuation_handle);
        UINT16_TO_STREAM(stream, remaining_length - HCI_ACL_PREAMBLE_SIZE);

        // Apparently L2CAP can set layer_specific to a max number of segments to transmit
        if (packet->layer_specific) {
            packet->layer_specific--;
            if (packet->layer_specific == 0) {
                packet->event = MSG_HC_TO_STACK_L2C_SEG_XMIT;
                callbacks->transmit_finished(packet, false);
                return;
            }
        }
    } else {
        current_fragment_packet = NULL;
        callbacks->fragmented(packet, true);
    }
}

static void reassemble_and_dispatch(BT_HDR *packet)
{
    LOG_DEBUG("reassemble_and_dispatch\n");

    if ((packet->event & MSG_EVT_MASK) == MSG_HC_TO_STACK_HCI_ACL) {
        uint8_t *stream = packet->data;
        uint16_t handle;
        uint16_t l2cap_length;
        uint16_t acl_length;

        STREAM_TO_UINT16(handle, stream);
        STREAM_TO_UINT16(acl_length, stream);
        STREAM_TO_UINT16(l2cap_length, stream);

        assert(acl_length == packet->len - HCI_ACL_PREAMBLE_SIZE);

        uint8_t boundary_flag = GET_BOUNDARY_FLAG(handle);
        handle = handle & HANDLE_MASK;

        BT_HDR *partial_packet = (BT_HDR *)hash_map_get(partial_packets, (void *)(uintptr_t)handle);

        if (boundary_flag == START_PACKET_BOUNDARY) {
            if (partial_packet) {
                LOG_DEBUG("%s found unfinished packet for handle with start packet. Dropping old.\n", __func__);
                LOG_DEBUG("partial_packet->len = %x, offset = %x\n", partial_packet->len, partial_packet->len);

                hash_map_erase(partial_packets, (void *)(uintptr_t)handle);

            }

            uint16_t full_length = l2cap_length + L2CAP_HEADER_SIZE + HCI_ACL_PREAMBLE_SIZE;
            if (full_length <= packet->len) {
                if (full_length < packet->len) {
                    LOG_WARN("%s found l2cap full length %d less than the hci length %d.\n", __func__, l2cap_length, packet->len);
                }

                callbacks->reassembled(packet);
                return;
            }

            partial_packet = (BT_HDR *)buffer_allocator->alloc(full_length + sizeof(BT_HDR));
            partial_packet->event = packet->event;
            partial_packet->len = full_length;
            partial_packet->offset = packet->len;

            memcpy(partial_packet->data, packet->data, packet->len);

            // Update the ACL data size to indicate the full expected length
            stream = partial_packet->data;
            STREAM_SKIP_UINT16(stream); // skip the handle
            UINT16_TO_STREAM(stream, full_length - HCI_ACL_PREAMBLE_SIZE);

            hash_map_set(partial_packets, (void *)(uintptr_t)handle, partial_packet);
            // Free the old packet buffer, since we don't need it anymore
            buffer_allocator->free(packet);
        } else {
            if (!partial_packet) {
                LOG_ERROR("%s got continuation for unknown packet. Dropping it.\n", __func__);
                buffer_allocator->free(packet);
                return;
            }

            packet->offset = HCI_ACL_PREAMBLE_SIZE;
            uint16_t projected_offset = partial_packet->offset + (packet->len - HCI_ACL_PREAMBLE_SIZE);
            if (projected_offset > partial_packet->len) { // len stores the expected length
                LOG_ERROR("%s got packet which would exceed expected length of %d. Truncating.\n", __func__, partial_packet->len);
                packet->len = partial_packet->len - partial_packet->offset;
                projected_offset = partial_packet->len;
            }

            memcpy(
                partial_packet->data + partial_packet->offset,
                packet->data + packet->offset,
                packet->len - packet->offset
            );

            // Free the old packet buffer, since we don't need it anymore
            buffer_allocator->free(packet);
            partial_packet->offset = projected_offset;

            if (partial_packet->offset == partial_packet->len) {
                stream = partial_packet->data;
                STREAM_TO_UINT16(handle, stream);
                STREAM_TO_UINT16(acl_length, stream);
                STREAM_TO_UINT16(l2cap_length, stream);
                LOG_DEBUG("partial_packet->offset = %x\n", partial_packet->offset);
                hash_map_erase(partial_packets, (void *)(uintptr_t)handle);
                partial_packet->offset = 0;

                callbacks->reassembled(partial_packet);
            }
        }
    } else {
        callbacks->reassembled(packet);
    }
}

static const packet_fragmenter_t interface = {
    init,
    cleanup,

    fragment_get_current_packet,
    fragment_and_dispatch,
    reassemble_and_dispatch
};

const packet_fragmenter_t *packet_fragmenter_get_interface()
{
    controller = controller_get_interface();
    buffer_allocator = buffer_allocator_get_interface();
    return &interface;
}


text:
#include "DRAMSim2/Callback.h"
#include "base/callback.hh"
#include "base/trace.hh"
#include "debug/DRAMSim2.hh"
#include "debug/Drain.hh"
#include "mem/dramsim2.hh"
#include "sim/system.hh"

DRAMSim2::DRAMSim2(const Params* p) :
    AbstractMemory(p),
    port(name() + ".port", *this),
    wrapper(p->deviceConfigFile, p->systemConfigFile, p->filePath,
            p->traceFile, p->range.size() / 1024 / 1024, p->enableDebug),
    retryReq(false), retryResp(false), startTick(0),
    nbrOutstandingReads(0), nbrOutstandingWrites(0),
    sendResponseEvent(this), tickEvent(this)
{
    DPRINTF(DRAMSim2,
            "Instantiated DRAMSim2 with clock %d ns and queue size %d\n",
            wrapper.clockPeriod(), wrapper.queueSize());

    DRAMSim::TransactionCompleteCB* read_cb =
        new DRAMSim::Callback<DRAMSim2, void, unsigned, uint64_t, uint64_t>(
            this, &DRAMSim2::readComplete);
    DRAMSim::TransactionCompleteCB* write_cb =
        new DRAMSim::Callback<DRAMSim2, void, unsigned, uint64_t, uint64_t>(
            this, &DRAMSim2::writeComplete);
    wrapper.setCallbacks(read_cb, write_cb);

    // Register a callback to compensate for the destructor not
    // being called. The callback prints the DRAMSim2 stats.
    Callback* cb = new MakeCallback<DRAMSim2Wrapper,
        &DRAMSim2Wrapper::printStats>(wrapper);
    registerExitCallback(cb);
}

void
DRAMSim2::init()
{
    AbstractMemory::init();

    if (!port.isConnected()) {
        fatal("DRAMSim2 %s is unconnected!\n", name());
    } else {
        port.sendRangeChange();
    }

    if (system()->cacheLineSize() != wrapper.burstSize())
        fatal("DRAMSim2 burst size %d does not match cache line size %d\n",
              wrapper.burstSize(), system()->cacheLineSize());
}

void
DRAMSim2::startup()
{
    startTick = curTick();

    // kick off the clock ticks
    schedule(tickEvent, clockEdge());
}

void
DRAMSim2::sendResponse()
{
    assert(!retryResp);
    assert(!responseQueue.empty());

    DPRINTF(DRAMSim2, "Attempting to send response\n");

    bool success = port.sendTimingResp(responseQueue.front());
    if (success) {
        responseQueue.pop_front();

        DPRINTF(DRAMSim2, "Have %d read, %d write, %d responses outstanding\n",
                nbrOutstandingReads, nbrOutstandingWrites,
                responseQueue.size());

        if (!responseQueue.empty() && !sendResponseEvent.scheduled())
            schedule(sendResponseEvent, curTick());

        if (nbrOutstanding() == 0)
            signalDrainDone();
    } else {
        retryResp = true;

        DPRINTF(DRAMSim2, "Waiting for response retry\n");

        assert(!sendResponseEvent.scheduled());
    }
}

unsigned int
DRAMSim2::nbrOutstanding() const
{
    return nbrOutstandingReads + nbrOutstandingWrites + responseQueue.size();
}

void
DRAMSim2::tick()
{
    wrapper.tick();

    // is the connected port waiting for a retry, if so check the
    // state and send a retry if conditions have changed
    if (retryReq && nbrOutstanding() < wrapper.queueSize()) {
        retryReq = false;
        port.sendRetryReq();
    }

    schedule(tickEvent, curTick() + wrapper.clockPeriod() * SimClock::Int::ns);
}

Tick
DRAMSim2::recvAtomic(PacketPtr pkt)
{
    access(pkt);

    // 50 ns is just an arbitrary value at this point
    return pkt->cacheResponding() ? 0 : 50000;
}

void
DRAMSim2::recvFunctional(PacketPtr pkt)
{
    pkt->pushLabel(name());

    functionalAccess(pkt);

    // potentially update the packets in our response queue as well
    for (auto i = responseQueue.begin(); i != responseQueue.end(); ++i)
        pkt->checkFunctional(*i);

    pkt->popLabel();
}

bool
DRAMSim2::recvTimingReq(PacketPtr pkt)
{
    // if a cache is responding, sink the packet without further action
    if (pkt->cacheResponding()) {
        pendingDelete.reset(pkt);
        return true;
    }

    // we should not get a new request after committing to retry the
    // current one, but unfortunately the CPU violates this rule, so
    // simply ignore it for now
    if (retryReq)
        return false;

    // if we cannot accept we need to send a retry once progress can
    // be made
    bool can_accept = nbrOutstanding() < wrapper.queueSize();

    // keep track of the transaction
    if (pkt->isRead()) {
        if (can_accept) {
            outstandingReads[pkt->getAddr()].push(pkt);

            // we count a transaction as outstanding until it has left the
            // queue in the controller, and the response has been sent
            // back, note that this will differ for reads and writes
            ++nbrOutstandingReads;
        }
    } else if (pkt->isWrite()) {
        if (can_accept) {
            outstandingWrites[pkt->getAddr()].push(pkt);

            ++nbrOutstandingWrites;

            // perform the access for writes
            accessAndRespond(pkt);
        }
    } else {
        // keep it simple and just respond if necessary
        accessAndRespond(pkt);
        return true;
    }

    if (can_accept) {
        // we should never have a situation when we think there is space,
        // and there isn't
        assert(wrapper.canAccept());

        DPRINTF(DRAMSim2, "Enqueueing address %lld\n", pkt->getAddr());

        // @todo what about the granularity here, implicit assumption that
        // a transaction matches the burst size of the memory (which we
        // cannot determine without parsing the ini file ourselves)
        wrapper.enqueue(pkt->isWrite(), pkt->getAddr());

        return true;
    } else {
        retryReq = true;
        return false;
    }
}

void
DRAMSim2::recvRespRetry()
{
    DPRINTF(DRAMSim2, "Retrying\n");

    assert(retryResp);
    retryResp = false;
    sendResponse();
}

void
DRAMSim2::accessAndRespond(PacketPtr pkt)
{
    DPRINTF(DRAMSim2, "Access for address %lld\n", pkt->getAddr());

    bool needsResponse = pkt->needsResponse();

    // do the actual memory access which also turns the packet into a
    // response
    access(pkt);

    // turn packet around to go back to requester if response expected
    if (needsResponse) {
        // access already turned the packet into a response
        assert(pkt->isResponse());
        // Here we pay for xbar additional delay and to process the payload
        // of the packet.
        Tick time = curTick() + pkt->headerDelay + pkt->payloadDelay;
        // Reset the timings of the packet
        pkt->headerDelay = pkt->payloadDelay = 0;

        DPRINTF(DRAMSim2, "Queuing response for address %lld\n",
                pkt->getAddr());

        // queue it to be sent back
        responseQueue.push_back(pkt);

        // if we are not already waiting for a retry, or are scheduled
        // to send a response, schedule an event
        if (!retryResp && !sendResponseEvent.scheduled())
            schedule(sendResponseEvent, time);
    } else {
        // queue the packet for deletion
        pendingDelete.reset(pkt);
    }
}

void DRAMSim2::readComplete(unsigned id, uint64_t addr, uint64_t cycle)
{
    assert(cycle == divCeil(curTick() - startTick,
                            wrapper.clockPeriod() * SimClock::Int::ns));

    DPRINTF(DRAMSim2, "Read to address %lld complete\n", addr);

    // get the outstanding reads for the address in question
    auto p = outstandingReads.find(addr);
    assert(p != outstandingReads.end());

    // first in first out, which is not necessarily true, but it is
    // the best we can do at this point
    PacketPtr pkt = p->second.front();
    p->second.pop();

    if (p->second.empty())
        outstandingReads.erase(p);

    // no need to check for drain here as the next call will add a
    // response to the response queue straight away
    assert(nbrOutstandingReads != 0);
    --nbrOutstandingReads;

    // perform the actual memory access
    accessAndRespond(pkt);
}

void DRAMSim2::writeComplete(unsigned id, uint64_t addr, uint64_t cycle)
{
    assert(cycle == divCeil(curTick() - startTick,
                            wrapper.clockPeriod() * SimClock::Int::ns));

    DPRINTF(DRAMSim2, "Write to address %lld complete\n", addr);

    // get the outstanding reads for the address in question
    auto p = outstandingWrites.find(addr);
    assert(p != outstandingWrites.end());

    // we have already responded, and this is only to keep track of
    // what is outstanding
    p->second.pop();
    if (p->second.empty())
        outstandingWrites.erase(p);

    assert(nbrOutstandingWrites != 0);
    --nbrOutstandingWrites;

    if (nbrOutstanding() == 0)
        signalDrainDone();
}

BaseSlavePort&
DRAMSim2::getSlavePort(const std::string &if_name, PortID idx)
{
    if (if_name != "port") {
        return MemObject::getSlavePort(if_name, idx);
    } else {
        return port;
    }
}

DrainState
DRAMSim2::drain()
{
    // check our outstanding reads and writes and if any they need to
    // drain
    return nbrOutstanding() != 0 ? DrainState::Draining : DrainState::Drained;
}

DRAMSim2::MemoryPort::MemoryPort(const std::string& _name,
                                 DRAMSim2& _memory)
    : SlavePort(_name, &_memory), memory(_memory)
{ }

AddrRangeList
DRAMSim2::MemoryPort::getAddrRanges() const
{
    AddrRangeList ranges;
    ranges.push_back(memory.getAddrRange());
    return ranges;
}

Tick
DRAMSim2::MemoryPort::recvAtomic(PacketPtr pkt)
{
    return memory.recvAtomic(pkt);
}

void
DRAMSim2::MemoryPort::recvFunctional(PacketPtr pkt)
{
    memory.recvFunctional(pkt);
}

bool
DRAMSim2::MemoryPort::recvTimingReq(PacketPtr pkt)
{
    // pass it to the memory controller
    return memory.recvTimingReq(pkt);
}

void
DRAMSim2::MemoryPort::recvRespRetry()
{
    memory.recvRespRetry();
}

DRAMSim2*
DRAMSim2Params::create()
{
    return new DRAMSim2(this);
}


text:
package com.google.cloud.talent.v4beta1.stub;

import com.google.api.core.BetaApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.talent.v4beta1.CompleteQueryRequest;
import com.google.cloud.talent.v4beta1.CompleteQueryResponse;
import io.grpc.MethodDescriptor;
import io.grpc.protobuf.ProtoUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;

// AUTO-GENERATED DOCUMENTATION AND CLASS
/**
 * gRPC stub implementation for Cloud Talent Solution API.
 *
 * <p>This class is for advanced usage and reflects the underlying API directly.
 */
@Generated("by gapic-generator")
@BetaApi("A restructuring of stub classes is planned, so this may break in the future")
public class GrpcCompletionStub extends CompletionStub {

  private static final MethodDescriptor<CompleteQueryRequest, CompleteQueryResponse>
      completeQueryMethodDescriptor =
          MethodDescriptor.<CompleteQueryRequest, CompleteQueryResponse>newBuilder()
              .setType(MethodDescriptor.MethodType.UNARY)
              .setFullMethodName("google.cloud.talent.v4beta1.Completion/CompleteQuery")
              .setRequestMarshaller(
                  ProtoUtils.marshaller(CompleteQueryRequest.getDefaultInstance()))
              .setResponseMarshaller(
                  ProtoUtils.marshaller(CompleteQueryResponse.getDefaultInstance()))
              .build();

  private final BackgroundResource backgroundResources;

  private final UnaryCallable<CompleteQueryRequest, CompleteQueryResponse> completeQueryCallable;

  private final GrpcStubCallableFactory callableFactory;

  public static final GrpcCompletionStub create(CompletionStubSettings settings)
      throws IOException {
    return new GrpcCompletionStub(settings, ClientContext.create(settings));
  }

  public static final GrpcCompletionStub create(ClientContext clientContext) throws IOException {
    return new GrpcCompletionStub(CompletionStubSettings.newBuilder().build(), clientContext);
  }

  public static final GrpcCompletionStub create(
      ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException {
    return new GrpcCompletionStub(
        CompletionStubSettings.newBuilder().build(), clientContext, callableFactory);
  }

  /**
   * Constructs an instance of GrpcCompletionStub, using the given settings. This is protected so
   * that it is easy to make a subclass, but otherwise, the static factory methods should be
   * preferred.
   */
  protected GrpcCompletionStub(CompletionStubSettings settings, ClientContext clientContext)
      throws IOException {
    this(settings, clientContext, new GrpcCompletionCallableFactory());
  }

  /**
   * Constructs an instance of GrpcCompletionStub, using the given settings. This is protected so
   * that it is easy to make a subclass, but otherwise, the static factory methods should be
   * preferred.
   */
  protected GrpcCompletionStub(
      CompletionStubSettings settings,
      ClientContext clientContext,
      GrpcStubCallableFactory callableFactory)
      throws IOException {
    this.callableFactory = callableFactory;

    GrpcCallSettings<CompleteQueryRequest, CompleteQueryResponse> completeQueryTransportSettings =
        GrpcCallSettings.<CompleteQueryRequest, CompleteQueryResponse>newBuilder()
            .setMethodDescriptor(completeQueryMethodDescriptor)
            .build();

    this.completeQueryCallable =
        callableFactory.createUnaryCallable(
            completeQueryTransportSettings, settings.completeQuerySettings(), clientContext);

    backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources());
  }

  public UnaryCallable<CompleteQueryRequest, CompleteQueryResponse> completeQueryCallable() {
    return completeQueryCallable;
  }

  @Override
  public final void close() {
    shutdown();
  }

  @Override
  public void shutdown() {
    backgroundResources.shutdown();
  }

  @Override
  public boolean isShutdown() {
    return backgroundResources.isShutdown();
  }

  @Override
  public boolean isTerminated() {
    return backgroundResources.isTerminated();
  }

  @Override
  public void shutdownNow() {
    backgroundResources.shutdownNow();
  }

  @Override
  public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
    return backgroundResources.awaitTermination(duration, unit);
  }
}


text:
'''setup for GameOfLife

'''

from setuptools import setup, find_packages
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

long_description = '''
GameOfLife is a python3 package that provides two classes
that together implement Conway's Game of Life.

Install the GameOfLife package using pip::

   $ sudo pip3 install GameOfLife

Or clone the git repository::

   $ git clone https://github.com/JnyJny/GameOfLife.git
   $ cd GameOfLife
   $ sudo python3 setup.py install

Also included in the package are several demos:

- [N]CGameOfLife: displays the simulation in a terminal window using curses.
- [N]PGameOfLife: displays the simulation in a PyGame window.

The 'N' variants use a Numpy based World and may be more performant.
'''

try:
    with open(path.join(here, 'VERSION'), encoding='utf-8') as f:
        version = f.read()[:-1]
except FileNotFoundError:
    version = '0.0.0'

download_url = 'https://github.com/JnyJny/GameOfLife/archive/{}.tar.gz'

setup(name='GameOfLife',
      version=version,
      description="Conway's Game of Life - Cellular Automata.",
      long_description=long_description,
      url='https://github.com/JnyJny/GameOfLife',
      download_url=download_url.format(version),
      author="Erik O'Shaughnessy",
      author_email="erik.oshaughnessy@gmail.com",
      license='MIT',
      classifiers=['Development Status :: 3 - Alpha',
                   'Intended Audience :: Developers',
                   'Operating System :: POSIX',
                   'Environment :: Console :: Curses',
                   'Topic :: Software Development :: Libraries :: Python Modules',
                   'Topic :: Scientific/Engineering :: Mathematics',
                   'Topic :: Scientific/Engineering :: Artificial Life',
                   'Topic :: Games/Entertainment :: Simulation',
                   'License :: OSI Approved :: MIT License',
                   'Programming Language :: Python :: 3',
                   'Programming Language :: Python :: 3.4'],
      keywords='conway game life cellular automata simulation',
      packages=find_packages(exclude=['contrib']),
      test_suite='GameOfLife.tests',
      scripts=['contrib/CGameOfLife.py', 'contrib/PGameOfLife.py'],
      install_requires=[],
      extras_require={},
      package_data={},
      data_files=[],
      )


text:
default:
	$(MAKE) -C Arkanoid

clean:
	$(MAKE) -C Arkanoid clean


text:
Cache Stats

            <button class="btn btn-default" title="Refresh" ng-click="refresh()"></button>

                Profile
                Host
                Cache Group
                Healthy
                Status
                Connections
                Mbps Out

                {{::cs.profile}}
                {{::cs.hostname}}
                {{::cs.cachegroup}}
                {{::cs.healthy}}
                {{::cs.status}}
                {{::connections(cs.connections)}}
                {{::bandwidth(cs.kbps, 'Mb')}}


text:
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where

import Irreverent.Bitbucket.Cli.Main (bitbMain)

import Preamble

main :: IO ()
main = bitbMain


text:
package asw.intro.client.context;

import asw.intro.client.Client;
import asw.intro.service.Service;
import asw.intro.client.connector.ServiceClientProxy;

import java.net.InetAddress;

import java.util.logging.Logger;

/* Application context per il servizio Service e il client Client. */
public class ApplicationContext {

	/* logger */
	private Logger logger = Logger.getLogger("asw.intro.client.context");

	/* posizione di default del server */
	private static final String DEFAULT_SERVER_ADDRESS = "localhost";

	/* porta del server */
	private static int SERVER_PORT = 6789;

    /* il singleton per l'application context */
	private static ApplicationContext instance = null;

	/* il riferimento al servizio */
	private Service service = null;

	/* Costruttore dell'application context (privato per singleton). */
	private ApplicationContext() {
		logger.info("Creazione dell'Application Context");
	}

    public static synchronized ApplicationContext getInstance() {
        if (instance==null) {
        	instance = new ApplicationContext();
        }
        return instance;
    }

    /* Factory method per il servizio Service.
     * Se possibile viene restituito uno stesso servizio. */
    public synchronized Service getService() {
		logger.info("ApplicationContext: getService()");
    	Service proxy = null;
    	try {
    		InetAddress address = InetAddress.getByName(DEFAULT_SERVER_ADDRESS);
    		int port = SERVER_PORT;
    		proxy = new ServiceClientProxy(address, port);
    	} catch(Exception e) {
    		e.printStackTrace();
    	}
    	return proxy;
	}

    public synchronized Service getService(String serverHost) {
		logger.info("ApplicationContext: getService(" + serverHost + ")");
    	Service proxy = null;
    	try {
    		InetAddress address = InetAddress.getByName(serverHost);
    		int port = SERVER_PORT;
    		proxy = new ServiceClientProxy(address, port);
    	} catch(Exception e) {
    		e.printStackTrace();
    	}
    	return proxy;
	}

    /* Factory method per il client Client.
     * Ogni volta viene restituito un nuovo client. */
    public Client getClient() {
		logger.info("ApplicationContext: getClient()");
		Client client = new Client();
    	client.setService( this.getService() );
        return client;
    }

    public Client getClient(String serverHost) {
		logger.info("ApplicationContext: getClient(" + serverHost + ")");
		Client client = new Client();
    	client.setService( this.getService(serverHost) );
        return client;
    }
}


text:
classdef nsoltSubbandDeserialization3dLayerTestCase < matlab.unittest.TestCase
    %NSOLTCHANNELSEPARATION3DLAYERTESTCASE
    %
    %   1コンポーネント入力(SSSCB):
    %      nElements x 1 x 1 x 1 x nSamples
    %
    %   複数コンポーネント出力 (SSSCB):(ツリーレベル数)
    %      nRowsLv1 x nColsLv1 x nLaysLv1 x (nChsTotal-1) x nSamples
    %      nRowsLv2 x nColsLv2 x nLaysLv2 x (nChsTotal-1) x nSamples
    %       :
    %      nRowsLvN x nColsLvN x nLaysLvN x (nChsTotal-1) x nSamples
    %      nRowsLvN x nColsLvN x nLaysLvN x 1 x nSamples
    %
    % Requirements: MATLAB R2020a
    %
    % Copyright (c) 2020, Shogo MURAMATSU
    %
    % All rights reserved.
    %
    % Contact address: Shogo MURAMATSU,
    %                Faculty of Engineering, Niigata University,
    %                8050 2-no-cho Ikarashi, Nishi-ku,
    %                Niigata, 950-2181, JAPAN
    %
    % http://msiplab.eng.niigata-u.ac.jp/

    properties (TestParameter)
        nlevels = { 1, 2, 3 };
        stride = { [2 2 2], [1 2 2], [2 1 2], [2 2 1] };
        nchs = { [5 5], [6 6] };
        datatype = { 'single', 'double' };
        nrows = struct('small', 4,'medium', 8, 'large', 16);
        ncols = struct('small', 4,'medium', 8, 'large', 16);
        nlays = struct('small', 4,'medium', 8, 'large', 16);
    end

    methods (TestClassTeardown)
        function finalCheck(~)
            import saivdr.dcnn.*
            layer = nsoltSubbandDeserialization3dLayer(...
                'OriginalDimension',[16 16 16],...
                'NumberOfChannels',[5 5],...
                'DecimationFactor',[2 2 2],...
                'NumberOfLevels',3);
            fprintf("\n --- Check layer for 3-D images ---\n");
            checkLayer(layer,[5264 1 1 1],'ObservationDimension',5)
        end
    end

    methods (Test)

        function testConstructor(testCase,...
                nrows,ncols,nlays,nchs,stride,nlevels)

            % Expected values
            height = nrows*(stride(1)^nlevels);
            width = ncols*(stride(2)^nlevels);
            depth = nlays*(stride(3)^nlevels);
            expctdName = 'Sb_Dsz';
            expctdDescription = "Subband deserialization " ...
                + "(h,w,d) = (" ...
                + height + "," + width + "," + depth + "), "  ...
                + "lv = " ...
                + nlevels + ", " ...
                + "(ps,pa) = (" ...
                + nchs(1) + "," + nchs(2) + "), "  ...
                + "(mv,mh,md) = (" ...
                + stride(1) + "," + stride(2) + "," + stride(3) + ")";

            % Instantiation of target class
            import saivdr.dcnn.*
            layer = nsoltSubbandDeserialization3dLayer(...
                'Name',expctdName,...
                'OriginalDimension',[height width depth],...
                'NumberOfChannels',nchs,...
                'DecimationFactor',stride,...
                'NumberOfLevels',nlevels);

            % Actual values
            actualName = layer.Name;
            actualDescription = layer.Description;

            % Evaluation
            testCase.verifyEqual(actualName,expctdName);
            testCase.verifyEqual(actualDescription,expctdDescription);
        end

        function testSetOriginalDimension(testCase,...
                nrows,ncols,nlays,nchs,stride,nlevels)

            % Expected values
            height = nrows*(stride(1)^nlevels);
            width = ncols*(stride(2)^nlevels);
            depth = nlays*(stride(3)^nlevels);

            % Instantiation of target class
            import saivdr.dcnn.*
            layer = nsoltSubbandDeserialization3dLayer(...
                'Name','Sb_Dsz',...
                'OriginalDimension',[height width depth],...
                'NumberOfChannels',nchs,...
                'DecimationFactor',stride,...
                'NumberOfLevels',nlevels);
            expctdOriginalDimension = 2*[height width depth];
            expctdInputSize = [2^3 1 1 1].*layer.InputSize;

            % Actual values
            layer = layer.setOriginalDimension(expctdOriginalDimension);
            actualOriginalDimension = layer.OriginalDimension;
            actualInputSize = layer.InputSize;

            % Evaluation
            testCase.verifyEqual(actualOriginalDimension,expctdOriginalDimension);
            testCase.verifyEqual(actualInputSize,expctdInputSize);

        end

        function testPredict(testCase,...
                nchs,nrows,ncols,nlays,stride,nlevels,datatype)

            import matlab.unittest.constraints.IsEqualTo
            import matlab.unittest.constraints.AbsoluteTolerance
            tolObj = AbsoluteTolerance(1e-6,single(1e-6));

            height = nrows*(stride(1)^nlevels);
            width = ncols*(stride(2)^nlevels);
            depth = nlays*(stride(3)^nlevels);

            % Parameters
            nSamples = 8;
            nChsTotal = sum(nchs);

            % Expected values
            %expctdZ = cell(nlevels,1);
            expctdZ = cell(nlevels+1,1);
            for iLv = 1:nlevels %-1
                subHeight = nrows * stride(1)^(nlevels-iLv);
                subWidth = ncols * stride(2)^(nlevels-iLv);
                subDepth = nlays * stride(3)^(nlevels-iLv);
                expctdZ{iLv} = randn(subHeight,subWidth,subDepth,...
                    nChsTotal-1,...
                    nSamples,datatype);
            end
            expctdZ{nlevels+1} = randn(nrows,ncols,nlays,1,...
                nSamples,datatype); %

            %expctdScales = zeros(nlevels,4);
            expctdScales = zeros(nlevels+1,4);
            %expctdScales(1,:) = [nrows ncols nlays nChsTotal];
            expctdScales(1,:) = [nrows ncols nlays 1];
            for iRevLv = 1:nlevels %2:nlevels
                %expctdScales(iRevLv,:) = ...
                expctdScales(iRevLv+1,:) = ...
                    [nrows*stride(1)^(iRevLv-1) ncols*stride(2)^(iRevLv-1) nlays*stride(3)^(iRevLv-1) nChsTotal-1];
            end
            expctdInputSize = [sum(prod(expctdScales,2)) 1 1 1 ];

            % Input
            nElements = sum(prod(expctdScales,2));
            X = zeros(nElements,1,1,1,nSamples,datatype);
            for iSample = 1:nSamples
                x = zeros(nElements,1,datatype);
                sidx = 0;
                nSubElements = prod(expctdScales(1,:));
                a = expctdZ{nlevels+1}(:,:,:,:,iSample);
                x(1:nSubElements) = a(:);
                sidx = sidx+nSubElements;
                for iRevLv = 1:nlevels
                    %nSubElements = prod(expctdScales(iRevLv,:));
                    nSubElements = prod(expctdScales(iRevLv+1,:));
                    a = expctdZ{nlevels-iRevLv+1}(:,:,:,:,iSample);
                    x(sidx+1:sidx+nSubElements) = a(:);
                    sidx = sidx+nSubElements;
                end
                X(:,1,1,1,iSample) = x;
            end

            % Instantiation of target class
            import saivdr.dcnn.*
            layer = nsoltSubbandDeserialization3dLayer(...
                'Name','Sb_Dsz',...
                'OriginalDimension',[height width depth],...
                'NumberOfChannels',nchs,...
                'DecimationFactor',stride,...
                'NumberOfLevels',nlevels);

            % Actual values
            %[actualZ{1:nlevels}] = layer.predict(X);
            [actualZ{1:nlevels+1}] = layer.predict(X);
            actualScales = layer.Scales;
            actualInputSize = layer.InputSize;

            % Evaluation
            for iLv = 1:nlevels+1 %1:nlevels
                testCase.verifyInstanceOf(actualZ{iLv},datatype);
                testCase.verifyThat(actualZ{iLv},...
                    IsEqualTo(expctdZ{iLv},'Within',tolObj));
            end
            testCase.verifyThat(actualScales,...
                IsEqualTo(expctdScales,'Within',tolObj));
            testCase.verifyThat(actualInputSize,...
                IsEqualTo(expctdInputSize,'Within',tolObj));

        end

        function testBackward(testCase,...
                nchs,nrows,ncols,nlays,stride,nlevels,datatype)

            import matlab.unittest.constraints.IsEqualTo
            import matlab.unittest.constraints.AbsoluteTolerance
            tolObj = AbsoluteTolerance(1e-6,single(1e-6));

            height = nrows*(stride(1)^nlevels);
            width = ncols*(stride(2)^nlevels);
            depth = nlays*(stride(3)^nlevels);

            % Parameters
            nSamples = 8;
            nChsTotal = sum(nchs);
            %dLdZ = cell(nlevels,1);
            dLdZ = cell(nlevels+1,1);
            for iLv = 1:nlevels %-1
                subHeight = nrows * stride(1)^(nlevels-iLv);
                subWidth = ncols * stride(2)^(nlevels-iLv);
                subDepth = nlays * stride(3)^(nlevels-iLv);
                dLdZ{iLv} = randn(subHeight,subWidth,subDepth,...
                    nChsTotal-1,...
                    nSamples,datatype);
            end
            dLdZ{nlevels+1} = randn(nrows,ncols,nlays,1,...nChsTotal,...
                nSamples,datatype); %

            % Expected values
            %expctdScales = zeros(nlevels,4);
            expctdScales = zeros(nlevels+1,4);
            %expctdScales(1,:) = [nrows ncols nlays nChsTotal];
            expctdScales(1,:) = [nrows ncols nlays 1];
            for iRevLv = 1:nlevels %2:nlevels
                expctdScales(iRevLv+1,:) = ...
                    [nrows*stride(1)^(iRevLv-1) ncols*stride(2)^(iRevLv-1) nlays*stride(3)^(iRevLv-1) nChsTotal-1];
            end
            nElements = sum(prod(expctdScales,2));
            expctddLdX = zeros(nElements,1,1,1,nSamples,datatype);
            for iSample = 1:nSamples
                x = zeros(nElements,1,datatype);
                sidx = 0;
                nSubElements = prod(expctdScales(1,:));
                a = dLdZ{nlevels+1}(:,:,:,:,iSample);
                x(1:nSubElements) = a(:);
                sidx = sidx+nSubElements;
                for iRevLv = 1:nlevels
                    nSubElements = prod(expctdScales(iRevLv+1,:));
                    a = dLdZ{nlevels-iRevLv+1}(:,:,:,:,iSample);
                    x(sidx+1:sidx+nSubElements) = a(:);
                    sidx = sidx+nSubElements;
                end
                expctddLdX(:,1,1,1,iSample) = x;
            end

            % Instantiation of target class
            import saivdr.dcnn.*
            layer = nsoltSubbandDeserialization3dLayer(...
                'Name','Sb_Srz',...
                'OriginalDimension',[height width depth],...
                'NumberOfChannels',nchs,...
                'DecimationFactor',stride,...
                'NumberOfLevels',nlevels);

            % Actual values
            %args = cell(1,1+nlevels+nlevels+1);
            args = cell(1,1+nlevels+1+nlevels+1+1);
            for iLv = 1:nlevels+1 % 1:nlevels
                %args{1+nlevels+iLv} = dLdZ{iLv};
                args{1+nlevels+1+iLv} = dLdZ{iLv};
            end
            actualdLdX = layer.backward(args{:});

            % Evaluation
            testCase.verifyInstanceOf(actualdLdX,datatype);
            testCase.verifyThat(actualdLdX,...
                IsEqualTo(expctddLdX,'Within',tolObj));

        end
    end

end


text:
package bankapp.atm;

import java.util.Comparator;

import bankapp.account.Account;

/**
 * The class AccountComparator is used to compare bank accounts.
 * @author Samuel Pulfer
 *
 */
public class AccountComparator implements Comparator<Account> {

	/**
	 * Compares two bank accounts regarding their balance.
	 * @param account1 the first account
	 * @param account2 the second account
	 * @return negative integer, zero, or a positive integer as the balance of the first account is less than, equal to, or greater than the balance of the second account
	 */
	@Override
	public int compare(Account account1, Account account2) {
		return Double.compare(account1.getBalance(), account2.getBalance());
	}

}


text:
<action>
    <field name="view">multi_view</field>
    <field name="string">Chart of Accounts</field>
    <field name="model">account.account</field>
    <field name="tabs">[["All",[]],["Archived",[["active","=",false]]]]</field>
    <field name="menu">account_menu</field>
</action>


text:
import {CdkTextareaAutosize} from '@angular/cdk/text-field';
import {Directive, Input} from '@angular/core';

/**
 * Directive to automatically resize a textarea to fit its content.
 * @deletion-target 7.0.0 deprecate in favor of `cdkTextareaAutosize`.
 */
@Directive({
  selector: 'textarea[mat-autosize], textarea[matTextareaAutosize]',
  exportAs: 'matTextareaAutosize',
  inputs: ['cdkAutosizeMinRows', 'cdkAutosizeMaxRows'],
  host: {
    'class': 'cdk-textarea-autosize mat-autosize',
    // Textarea elements that have the directive applied should have a single row by default.
    // Browsers normally show two rows by default and therefore this limits the minRows binding.
    'rows': '1',
    '(input)': '_noopInputHandler()',
  },
})
export class MatTextareaAutosize extends CdkTextareaAutosize {
  @Input()
  get matAutosizeMinRows(): number { return this.minRows; }
  set matAutosizeMinRows(value: number) { this.minRows = value; }

  @Input()
  get matAutosizeMaxRows(): number { return this.maxRows; }
  set matAutosizeMaxRows(value: number) { this.maxRows = value; }
}


text:
from telemetry.core import web_contents
from telemetry.core.backends.chrome import inspector_backend_list

class MiscWebContentsBackend(inspector_backend_list.InspectorBackendList):
  """A dynamic sequence of web contents not related to tabs and extensions.

  Provides acccess to chrome://oobe/login page.
  """

  def __init__(self, browser_backend):
    super(MiscWebContentsBackend, self).__init__(
        browser_backend, backend_wrapper=web_contents.WebContents)

  @property
  def oobe_exists(self):
    """Lightweight property to determine if the oobe webui is visible."""
    return bool(len(self))

  def GetOobe(self):
    if not len(self):
      return None
    return self[0]

  def ShouldIncludeContext(self, context):
    return context.get('url').startswith('chrome://oobe')


text:
function createLinearGauge(selector) {
    // initialization options - validated in typescript
    // jqwidgets.LinearGaugeOptions has generated TS definition
    var options = {
        orientation: 'vertical',
        width: 100,
        height: 350,
        ticksMajor: { size: '10%', interval: 10 },
        ticksMinor: { size: '5%', interval: 2.5, style: { 'stroke-width': 1, stroke: '#aaaaaa' } },
        max: 60,
        pointer: { size: '5%' },
        colorScheme: 'scheme05',
        labels: {
            interval: 20,
            formatValue: function (value, position) {
                if (position === 'far') {
                    value = (9 / 5) * value + 32;
                    if (value === -76) {
                        return '°F';
                    }
                    return value + '°';
                }
                if (value === -60) {
                    return '°C';
                }
                return value + '°';
            }
        },
        ranges: [
            { startValue: -10, endValue: 10, style: { fill: '#FFF157', stroke: '#FFF157' } },
            { startValue: 10, endValue: 35, style: { fill: '#FFA200', stroke: '#FFA200' } },
            { startValue: 35, endValue: 60, style: { fill: '#FF4800', stroke: '#FF4800' } }],
        animationDuration: 1500
    };
    // Creates an instance of the LinearGauge
    var myLinearGauge = jqwidgets.createInstance(selector, 'jqxLinearGauge', options);
    options.value = 40;
    myLinearGauge.setOptions(options);
}
//# sourceMappingURL=typescript-lineargauge.js.map


text:
import { MARIO_PATH } from '../../../../constants';

const fse = require('fs-extra');
const { ipcMain } = require('electron');
const GoogleAuth = require('google-auth-library');
const APP = require('../../constants');
const credentials = require('./.credentials/google.json');

// const TOKEN_DIR = `${__dirname}/lib/mario/apps/google/.credentials`;
const TOKEN_PATH = `${MARIO_PATH}/google-token.json`;

const SCOPE = {
  [APP.GMAIL]: ['https://mail.google.com/'],
  [APP.DRIVE]: ['https://www.googleapis.com/auth/drive'],
};

class Auth {
  constructor() {
    this.scope = [];
    this.oauth2Client = {};
    this.mainWindow = null;
    this.pipeName = '';
  }

  initializeListenerOnce(resolve, reject) {
    ipcMain.once('google-auth-token', (event, code) => {
      this.oauth2Client.getToken(code, (err, token) => {
        if (err) {
          console.log('Error while trying to retrieve access token', err);
          if (this.mainWindow) {
            this.mainWindow.webContents.send(
              'auth-fail',
              JSON.stringify({ err: err.message, pipeName: this.pipeName, type: 'google' })
            );
            reject(err);
          }
        } else {
          this.oauth2Client.credentials = token;
          this.storeToken(token);
          resolve(this.oauth2Client);
          if (this.mainWindow) {
            this.mainWindow.webContents.send(
              'auth-success',
              JSON.stringify({ pipeName: this.pipeName, type: 'google' })
            );
          }
        }
      });
    });

    ipcMain.once('stop-auth', () => {
      reject('stop google auth');
    });

    ipcMain.once('google-auth-fail', () => {
      reject('google auth fail');
      if (this.mainWindow) {
        this.mainWindow.webContents.send(
          'auth-fail',
          JSON.stringify({ err: 'google auth fail', pipeName: this.pipeName, type: 'google' })
        );
      }
    });
  }

  addScope(appType) {
    if (SCOPE[appType]) {
      this.scope = this.scope.concat(SCOPE[appType]);
    }
  }

  getNewToken(scope) {
    const authUrl = this.oauth2Client.generateAuthUrl({
      access_type: 'offline',
      scope
    });
    this.mainWindow.webContents.send(
      'need-auth',
      JSON.stringify({ authUrl, pipeName: this.pipeName, type: 'google' })
    );
    return new Promise((resolve, reject) => {
      this.initializeListenerOnce(resolve, reject);
    });
  }

  storeToken(token) {
    fse.writeFile(TOKEN_PATH, JSON.stringify(token));
    console.log(`Token stored to ${TOKEN_PATH}`);
  }

  authorize(pipeName, win) {
    const clientSecret = credentials.client_secret;
    const clientId = credentials.client_id;
    const redirectUrl = credentials.redirect_uris[0];
    const auth = new GoogleAuth();
    this.oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

    this.mainWindow = win;
    this.pipeName = pipeName;

    return new Promise((resolve, reject) => {
      fse.readFile(TOKEN_PATH, (error, token) => {
        if (error) {
          this.getNewToken(this.scope)
            .then((client) => {
              this.oauth2Client = client;
              resolve(this.oauth2Client);
            })
            .catch((err) => {
              reject(err);
            });
        } else {
          this.oauth2Client.credentials = JSON.parse(token);
          resolve(this.oauth2Client);
        }
      });
    });
  }

  getClient() {
    return this.oauth2Client;
  }
}

module.exports = new Auth();


text:
require 'spec_helper'

describe ChannelPostObserver do
  let(:channel_post) { create(:channel_post, visible: false) }
  let(:user) { create(:user) }

  describe 'after_save' do
    before do
      channel_post.channel.subscribers << user
      Notification.unstub(:notify)
      Notification.unstub(:notify_once)
      ActionMailer::Base.deliveries = []
    end

    context "when post is not published" do
      before do
        Notification.should_receive(:notify_once).with(
          :channel_post,
          user,
          {channel_post_id: channel_post.id, channel_id: channel_post.channel_id},
          {
            channel_post_id: channel_post.id,
            channel_id: channel_post.channel_id,
            origin_email: channel_post.channel.email,
            origin_name: channel_post.channel.name
          }
        ).never
      end

      it 'should not fill published at field' do
        channel_post.published_at.should be_nil
      end

      it 'should not call Notification.notify once' do
        channel_post.update_attributes(visible: false)
      end
    end

    context "when post is published" do
      before do
        Notification.should_receive(:notify_once).with(
          :channel_post,
          user,
          {channel_post_id: channel_post.id, channel_id: channel_post.channel_id},
          {
            channel_post_id: channel_post.id,
            channel_id: channel_post.channel_id,
            origin_email: channel_post.channel.email,
            origin_name: channel_post.channel.name
          }
        ).once.and_call_original
      end

      it 'should call Notification.notify once' do
        channel_post.update_attributes(visible: true)
      end

      it 'should fill published at field' do
        channel_post.update_attributes(visible: true)
        channel_post.published_at.should_not be_nil
      end
    end
  end
end


text:
<?php

namespace Camspiers\LoggerBridge\ErrorReporter;

/**
 * Class ErrorReporter
 */
interface ErrorReporter
{
    public function reportError($exception, \SS_HTTPRequest $request = null);
}


text:
var React = require('react');
var Router = require('react-router');

var VisitorList = React.createClass({

	_getData: function(){
		return {
			data: {
				visitors: this.refs.list.getDOMNode().value.split(",")
			}
		}
	},

	componentDidMount: function(){
		if(this.props.registerCallback){
			this.props.registerCallback(this._getData);
		}
	},

	render: function(){

		return (

			Other Visitors (Separate name by comma)

						<input ref="list" type="list" className="form-control" defaultValue=""/>

		);
	}
});

module.exports = VisitorList;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Kitbag.HackWebApplication.Controllers
{
    public class DashboardController : Controller
    {
        // GET: Dashboard
        public ActionResult Index()
        {
            return View();
        }
    }
}


text:
(function () {
   'use strict';

   angular.module('mobile-angular-ui.gestures.drag', [
     'mobile-angular-ui.gestures.swipe',
     'mobile-angular-ui.gestures.transform'
   ])

   //
   // $drag
   //
   // A provider to create touch & drag components.
   //
   // $drag Service wraps ngTouch $swipe to extend its behavior moving one or more
   // target element throug css transform according to the $swipe coords thus creating
   // a drag effect.
   //
   // $drag interface is similar to $swipe:
   //
   // app.controller('MyController', function($drag, $element){
   //   $drag.bind($element, {
   //    start: function(coords, cancel, markers, e){},
   //    move: function(coords, cancel, markers, e){},
   //    end: function(coords, cancel, markers, e){},
   //    cancel: function(coords, markers, e){},
   //    transform: function(x, y, transform) {},
   //    adaptTransform: function(x, y, transform) {},
   //    constraint: fn or {top: y1, left: x1, bottom: y2, right: x2}
   //   });
   // });
   //
   // Main differences from $swipe are:
   //  - coords param take into account css transform so you can easily detect collision with other elements.
   //  - start, move, end callback receive a cancel funcion that can be used to cancel the motion and reset
   //    the transform.
   //  - you can configure the transform behavior passing a transform function to options.
   //  - you can constraint the motion through the constraint option (setting relative movement limits)
   //    or through the track option (setting absolute coords);
   //  - you can setup collision markers being watched and passed to callbacks.
   //
   // Example (drag to dismiss):
   //  $drag.bind(e, {
   //    move: function(c, cancel, markers){
   //      if(c.left > markers.m1.left) {
   //        e.addClass('willBeDeleted');
   //      } else {
   //        e.removeClass('willBeDeleted');
   //      }
   //    },
   //    end: function(coords, cancel){
   //      if(c.left > markers.m1.left) {
   //        e.addClass('deleting');
   //        delete($scope.myModel).then(function(){
   //          e.remove();
   //        }, function(){
   //          cancel();
   //        });
   //      } else {
   //        cancel();
   //      }
   //    },
   //    cancel: function(){
   //      e.removeClass('willBeDeleted');
   //      e.removeClass('deleting');
   //    },
   //    constraint: {
   //        minX: 0,
   //        minY: 0,
   //        maxY: 0
   //     },
   //   });

  .provider('$drag', function() {
    this.$get = ['$swipe', '$document', 'Transform', function($swipe, $document, Transform) {

      var style = document.createElement('style');
      style.appendChild(document.createTextNode(''));
      document.head.appendChild(style);
      var sheet = style.sheet;
      // Makes z-index 99999
      sheet.insertRule('html .ui-drag-move{z-index: 99999 !important;}');
      // Disable transitions
      sheet.insertRule('html .ui-drag-move{-webkit-transition: none !important;-moz-transition: none !important;-o-transition: none !important;-ms-transition: none !important;transition: none !important;}');
      // Makes text unselectable
      sheet.insertRule('html .ui-drag-move, html .ui-drag-move *{-webkit-touch-callout: none !important;-webkit-user-select: none !important;-khtml-user-select: none !important;-moz-user-select: none !important;-ms-user-select: none !important;user-select: none !important;}');

      return {
        Transform: Transform,
        bind: function(elem, options) {
          var defaults = {
            constraint: {}
          };

          options = angular.extend({}, defaults, options || {});

          var
            e = angular.element(elem)[0],
            moving = false,
            deltaXTot = 0, // total movement since elem is bound
            deltaYTot = 0,
            x0, y0, // touch coords on start
            t0, // transform on start
            tOrig = Transform.fromElement(e),
            x, y, // current touch coords
            t, // current transform
            minX = options.constraint.minX !== undefined ? options.constraint.minX : Number.NEGATIVE_INFINITY,
            maxX = options.constraint.maxX !== undefined ? options.constraint.maxX : Number.POSITIVE_INFINITY,
            minY = options.constraint.minY !== undefined ? options.constraint.minY : Number.NEGATIVE_INFINITY,
            maxY = options.constraint.maxY !== undefined ? options.constraint.maxY : Number.POSITIVE_INFINITY,

            preventedWhileMoving = ['click', 'tap', 'mouseup', 'touchend'],

            captureClicks = function(e) {
              e.stopPropagation();
            },

            cancelFn = function(){
              elem.triggerHandler('touchcancel');
            },

            resetFn = function(){
              elem.triggerHandler('touchcancel');
              deltaXTot = 0;
              deltaYTot = 0;
              tOrig.set(e);
            },

            callbacks = {
              move: function(c) {
                if (elem[0].addEventListener) {
                  for (var i = 0; i < preventedWhileMoving.length; i++) {

                    // Sorry.. for IE8 we are not capturing clicks
                    // for inner elements, hope it wont cause too
                    // much problems
                    elem[0].addEventListener(preventedWhileMoving[i], captureClicks, true);
                  }
                }

                if (!moving) {    // $swipe calls start at the first touch
                                  // to ensure $drag start is called only while actually
                                  // dragging and not for touches we will bind $drag.start
                                  // to the first time move is called.

                  t0 = Transform.fromElement(e);
                  x  = x0 = c.x;
                  y  = y0 = c.y;

                  elem.addClass('ui-drag-move');

                  if (options.start) {
                    options.start(e.getBoundingClientRect(), cancelFn, resetFn, c);
                  }

                  moving = true;
                }

                // total movement shoud match constraints
                var dx, dy,
                deltaX, deltaY, r,
                rectBefore = e.getBoundingClientRect(),
                _maxX = angular.isFunction(maxX) ? maxX() : maxX,
                _maxY = angular.isFunction(maxY) ? maxY() : maxY,
                _minX = angular.isFunction(minX) ? minX() : minX,
                _minY = angular.isFunction(minY) ? minY() : minY;

                deltaX = Math.max(Math.min(_maxX - deltaXTot, c.x - x0), _minX - deltaXTot);
                deltaY = Math.max(Math.min(_maxY - deltaYTot, c.y - y0), _minY - deltaYTot);

                dx = deltaX - (x - x0);
                dy = deltaY - (y - y0);

                t = Transform.fromElement(e);

                if (options.transform) {
                  r = options.transform(t, dx, dy, c.x, c.y, x0, y0);
                  t = r || t;
                } else {
                  t.translate(dx, dy);
                }

                if (options.adaptTransform) {
                  r = options.adaptTransform(t, dx, dy, c.x, c.y, x0, y0);
                  t = r || t;
                }

                x = deltaX + x0;
                y = deltaY + y0;

                t.set(e);

                if (options.move) {
                  options.move(e.getBoundingClientRect(), cancelFn, resetFn, c);
                }

              },

              end: function(c) {
                moving = false;
                if (elem[0].removeEventListener) {
                  for (var i = 0; i < preventedWhileMoving.length; i++) {
                    elem[0].removeEventListener(preventedWhileMoving[i], captureClicks);
                  }
                }

                var deltaXTotOld = deltaXTot;
                var deltaYTotOld = deltaYTot;

                var undoFn = function() {
                  deltaXTot = deltaXTotOld;
                  deltaYTot = deltaYTotOld;
                  t0.set(e);
                };

                deltaXTot = deltaXTot + x - x0;
                deltaYTot = deltaYTot + y - y0;

                if (options.end) {
                  options.end(e.getBoundingClientRect(), undoFn, resetFn, c);
                }

                elem.removeClass('ui-drag-move');
              },

              cancel: function() {
                if (elem[0].removeEventListener) {
                  for (var i = 0; i < preventedWhileMoving.length; i++) {
                    elem[0].removeEventListener(preventedWhileMoving[i], captureClicks);
                  }
                }

                if (moving) {
                  t0.set(e);
                  if (options.cancel) {
                    options.cancel(e.getBoundingClientRect(), resetFn);
                  }
                  moving = false;
                  elem.removeClass('ui-drag-move');
                }
              }
            };

          elem.on('$destroy', function() {
            $document.unbind('mouseout', cancelFn);
            callbacks = options = e = moving = deltaXTot = deltaYTot = x0 = y0 = t0 = tOrig = x = y = t = minX = maxX = minY = maxY = null;
          });

          var unbind = $swipe.bind(elem, callbacks);
          $document.on('mouseout', cancelFn);
          return unbind;
        }
      };
    }];
  });

}());

(function() {
  'use strict';

  // An adaptation of ngTouch.$swipe
  // basically the same despite of:
  // 1) It does not require ngTouch thus is better compatible with fastclick.js
  // 2) It allows to unbind
  angular.module('mobile-angular-ui.gestures.swipe', [])

  .factory('$swipe', [function() {
    var MOVE_BUFFER_RADIUS = 10;

    var POINTER_EVENTS = {
      'mouse': {
        start: 'mousedown',
        move: 'mousemove',
        end: 'mouseup'
      },
      'touch': {
        start: 'touchstart',
        move: 'touchmove',
        end: 'touchend',
        cancel: 'touchcancel'
      }
    };

    function getCoordinates(event) {
      var touches = event.touches && event.touches.length ? event.touches : [event];
      var e = (event.changedTouches && event.changedTouches[0]) ||
          (event.originalEvent && event.originalEvent.changedTouches &&
              event.originalEvent.changedTouches[0]) ||
          touches[0].originalEvent || touches[0];

      return {
        x: e.clientX,
        y: e.clientY
      };
    }

    function getEvents(pointerTypes, eventType) {
      var res = [];
      angular.forEach(pointerTypes, function(pointerType) {
        var eventName = POINTER_EVENTS[pointerType][eventType];
        if (eventName) {
          res.push(eventName);
        }
      });
      return res.join(' ');
    }

    return {
      bind: function(element, eventHandlers, pointerTypes) {
        // Absolute total movement, used to control swipe vs. scroll.
        var totalX, totalY;
        // Coordinates of the start position.
        var startCoords;
        // Last event's position.
        var lastPos;
        // Whether a swipe is active.
        var active = false;

        pointerTypes = pointerTypes || ['mouse', 'touch'];

        var cancelEvents = getEvents(pointerTypes, 'cancel');
        var startEvents = getEvents(pointerTypes, 'start');
        var endEvents = getEvents(pointerTypes, 'end');
        var moveEvents = getEvents(pointerTypes, 'move');

        var startCb = function(event) {
          startCoords = getCoordinates(event);
          active = true;
          totalX = 0;
          totalY = 0;
          lastPos = startCoords;
          if (eventHandlers.start) {
            eventHandlers.start(startCoords, event);
          }
        };

        var moveCb = function(event) {
          if (!active) return;

          // Android will send a touchcancel if it thinks we're starting to scroll.
          // So when the total distance (+ or - or both) exceeds 10px in either direction,
          // we either:
          // - On totalX > totalY, we send preventDefault() and treat this as a swipe.
          // - On totalY > totalX, we let the browser handle it as a scroll.

          if (!startCoords) return;
          var coords = getCoordinates(event);

          totalX += Math.abs(coords.x - lastPos.x);
          totalY += Math.abs(coords.y - lastPos.y);

          lastPos = coords;

          if (totalX < MOVE_BUFFER_RADIUS && totalY < MOVE_BUFFER_RADIUS) {
            return;
          }

          // One of totalX or totalY has exceeded the buffer, so decide on swipe vs. scroll.
          if (totalY > totalX) {
            // Allow native scrolling to take over.
            active = false;
            if (eventHandlers.cancel) {
              eventHandlers.cancel(event);
            }
            return;
          } else {
            // Prevent the browser from scrolling.
            event.preventDefault();
            if (eventHandlers.move) {
              eventHandlers.move(coords, event);
            }
          }
        };

        var cancelCb = function(event) {
          active = false;
          if (eventHandlers.cancel) {
            eventHandlers.cancel(event);
          }
        };

        var endCb = function(event) {
          if (!active) return;
          active = false;
          if(eventHandlers.end) {
            eventHandlers.end(getCoordinates(event), event);
          }
        };

        element.on(startEvents, startCb);
        if (cancelEvents) { element.on(cancelEvents, cancelCb); }
        element.on(moveEvents, moveCb);
        element.on(endEvents, endCb);

        return function unbind() {
          element.off(startEvents, startCb);
          if (cancelEvents) { element.off(cancelEvents, cancelCb); }
          element.off(moveEvents, moveCb);
          element.off(endEvents, endCb);
          element = startEvents = startCb = moveEvents = moveCb = endEvents = endCb = cancelEvents = cancelCb = null;
        };
      }
    };
  }]);
}());

(function() {
  'use strict';
  angular.module('mobile-angular-ui.gestures.transform', [])

  .factory('Transform', [
    '$window',
    function($window){

      function matrixHeight(m) {
        return m.length;
      }

      function matrixWidth(m) {
        return m[0] ? m[0].length : 0;
      }

      function matrixMult(m1, m2) {
        var width1  = matrixWidth(m1),
            width2  = matrixWidth(m2),
            height1 = matrixHeight(m1),
            height2 = matrixHeight(m2);

        if (width1 != height2) {
          throw new Error("error: incompatible sizes");
        }

        var result = [];
        for (var i = 0; i < height1; i++) {
            result[i] = [];
            for (var j = 0; j < width2; j++) {
                var sum = 0;
                for (var k = 0; k < width1; k++) {
                    sum += m1[i][k] * m2[k][j];
                }
                result[i][j] = sum;
            }
        }
        return result;
      }

      //
      // Cross-Browser stuffs
      //
      var vendorPrefix,
          cssPrefix,
          transformProperty,
          prefixes = ['', 'webkit', 'Moz', 'O', 'ms'],
          d = $window.document.createElement('div');

      for (var i = 0; i < prefixes.length; i++) {
        var prefix = prefixes[i];
        if ( (prefix + 'Perspective') in d.style ) {
          vendorPrefix = prefix;
          cssPrefix = (prefix === '' ? '' : '-' + prefix.toLowerCase() + '-');
          transformProperty = cssPrefix + 'transform';
          break;
        }
      }

      d = null;

      //
      // Represents a 2d transform,
      // behind the scene is a transform matrix exposing methods to get/set
      // meaningfull primitives like rotation, translation and scale.
      //
      // Allows to apply multiple transforms through #merge.
      //
      function Transform(matrix) {
        this.mtx = matrix || [
          [1,0,0],
          [0,1,0],
          [0,0,1]
        ];
      }

      Transform.getElementTransformProperty = function(e) {
        e = e.length ? e[0] : e;
        var tr = $window
                .getComputedStyle(e, null)
                .getPropertyValue(transformProperty);
      };

      Transform.setElementTransformProperty = function(e, value) {
        e = e.length ? e[0] : e;
        e.style[transformProperty] = value;
      };

      Transform.fromElement = function(e) {
        e = e.length ? e[0] : e;
        var tr = $window
                .getComputedStyle(e, null)
                .getPropertyValue(transformProperty);

        if (!tr || tr === 'none') {
          return new Transform();
        }

        if (tr.match('matrix3d')) {
          throw new Error('Handling 3d transform is not supported yet');
        }

        var values =
          tr.split('(')[1]
            .split(')')[0]
            .split(',')
            .map(Number);

        var mtx = [
          [values[0], values[2], values[4]],
          [values[1], values[3], values[5]],
          [        0,         0,        1 ],
        ];

        return new Transform(mtx);
      };

      Transform.prototype.apply = function(e, options) {
        e = e.length ? e[0] : e;
        var mtx = Transform.fromElement(e).merge(this).mtx;
        e.style[transformProperty] = 'matrix(' + [ mtx[0][0], mtx[1][0], mtx[0][1], mtx[1][1], mtx[0][2], mtx[1][2] ].join(',') + ')';
        return this;
      };

      Transform.prototype.set = function(e) {
        e = e.length ? e[0] : e;
        var mtx = this.mtx;
        e.style[transformProperty] = 'matrix(' + [ mtx[0][0], mtx[1][0], mtx[0][1], mtx[1][1], mtx[0][2], mtx[1][2] ].join(',') + ')';
        return this;
      };

      Transform.prototype.rotate = function(a) {
        a = a * (Math.PI / 180); // deg2rad
        var t = [
          [Math.cos(a), -Math.sin(a),  0],
          [Math.sin(a),  Math.cos(a),  0],
          [          0,            0,  1]
        ];

        this.mtx = matrixMult(t, this.mtx);
        return this;
      };

      Transform.prototype.translate = function(x, y) {
        y = (y === null || y === undefined) ? x : y;
        var t = [
          [1,0,x],
          [0,1,y],
          [0,0,1]
        ];
        this.mtx = matrixMult(t, this.mtx);
        return this;
      };

      Transform.prototype.scale = function(a) {
        var t = [
          [a,0,0],
          [0,a,0],
          [0,0,1]
        ];
        this.mtx = matrixMult(t, this.mtx);
        return this;
      };

      Transform.prototype.merge = function(t) {
        this.mtx = matrixMult(this.mtx, t.mtx);
        return this;
      };

      Transform.prototype.getRotation = function() {
        var mtx = this.mtx;
        return Math.round(Math.atan2(mtx[1][0], mtx[0][0]) * (180/Math.PI)); // rad2deg
      };

      Transform.prototype.getTranslation = function() {
        var mtx = this.mtx;
        return {
          x: mtx[0][2],
          y: mtx[1][2]
        };
      };

      Transform.prototype.getScale = function() {
        var mtx = this.mtx, a = mtx[0][0], b = mtx[1][0], d = 10;
        return Math.round( Math.sqrt( a*a + b*b ) * d ) / d;
      };

      Transform.prototype.matrixToString = function() {
        var mtx = this.mtx;
        var res = "";
        for (var i = 0; i < mtx.length; i++) {
          for (var j = 0; j < mtx[i].length; j++) {
            var n = '' + mtx[i][j];
            res += n;
            for (var k = 0; k < 5 - n.length; k++) {
              res += ' ';
            }
          }
          res += '\n';
        }
        return res;
      };

      return Transform;
    }
  ]);
}());
(function () {
   'use strict';

   angular.module('mobile-angular-ui.gestures', [
     'mobile-angular-ui.gestures.drag',
     'mobile-angular-ui.gestures.swipe',
     'mobile-angular-ui.gestures.transform'
   ]);

}());


text:
      Posted on

      by


text:
opera.isReady(function(){
    window.addEventListener( "load", function( event ){
      if( opera.extension ){
        if( opera.extension.tabs ){opera.extension.tabs.create({url:"http://www.opera.com/"});}
        opera.extension.onmessage = function( event ){
          MANUAL( "Event received by the helper from " + event.origin );

          if( event.ports ){
            MANUAL( "Responding to port. Ports are:\n" + getProperties( event.ports, 2 ) );
            event.ports[0].postMessage( "Hi" );
          } else if(event.source){
            MANUAL( "Responding to source" );
            event.source.postMessage( "Hi" );
          } else {
            MANUAL( "Unable to use event.source, trying opera.extension.postMessage." );
            opera.extension.postMessage("heyhey");
          }
        }
      } else {
        FAIL( "Couldn't find an extension or opera.extension object." );
      }
    }, false);
});


text:
FROM apache-hadoop-hdfs-precise:1.2.1

MAINTAINER luckysahaf lgsahaf@gmail.com

RUN apt-get install -y curl python-pip; \
pip install json; \
apt-get remove -y python-pip

ENV SCALA_VERSION 2.10.3
ENV SPARK_VERSION 1.1.0
ENV SCALA_HOME /opt/scala-$SCALA_VERSION
ENV SPARK_HOME /opt/spark-$SPARK_VERSION
ENV PATH $SPARK_HOME:$SCALA_HOME/bin:$PATH

# Install Scala
ADD http://www.scala-lang.org/files/archive/scala-$SCALA_VERSION.tgz /
RUN (cd / && gunzip < scala-$SCALA_VERSION.tgz)|(cd /opt && tar -xvf -); \
rm /scala-$SCALA_VERSION.tgz

# Install Spark
ADD http://d3kbcqa49mib13.cloudfront.net/spark-$SPARK_VERSION-bin-hadoop1.tgz /
RUN (cd / && gunzip < spark-$SPARK_VERSION-bin-hadoop1.tgz)|(cd /opt && tar -xvf -)
RUN (ln -s /opt/spark-$SPARK_VERSION-bin-hadoop1 /opt/spark-$SPARK_VERSION && rm /spark-$SPARK_VERSION-bin-hadoop1.tgz)

# Add Shark config files and configure script
ADD files /root/spark_files


text:
const { pick, pickBy } = require('lodash')

const { QUERY_DATE_FIELDS } = require('../../constants')

function setRequestBody(req, res, next) {
  const selectedSortBy = req.query.sortby ? { sortby: req.query.sortby } : null
  const selectedFiltersQuery = pick(req.query, [
    'status',
    'company_name',
    'contact_name',
    'primary_market',
    'uk_region',
    'reference',
    ...QUERY_DATE_FIELDS,
    'total_cost',
    'net_cost',
    'sector_descends',
  ])

  req.body = pickBy({
    ...req.body,
    ...selectedSortBy,
    ...pickBy(selectedFiltersQuery),
  })

  const currencyFields = ['total_cost', 'net_cost']
  currencyFields.forEach((field) => {
    if (req.body[field]) {
      req.body[field] = parseFloat(req.query[field]) * 100
    }
  })

  next()
}

module.exports = {
  setRequestBody,
}


text:
module FacebookSession
  module Generators
    class InstallGenerator < ::Rails::Generators::Base
      source_root File.expand_path '../templates', __FILE__

      desc "Create facebook_session config and prepare application.js"

      def create_initializer
        template 'initializer.rb', File.join('config', 'initializers', 'facebook_session.rb')
      end

      def inject_js
        require_js = "//= require facebook_session\n"

        if manifest.exist?
          manifest_contents = File.read(manifest)

          if manifest_contents.include? 'require_tree'
            inject_into_file manifest, require_js, {before: '//= require_tree'}
          else
            append_file manifest, require_js
          end
        else
          create_file manifest, require_js
        end
      end

      private

      def manifest
        Pathname.new(destination_root).join('app/assets/javascripts', 'application.js')
      end
    end
  end
end


text:
import { TypedArray } from '../types';
import { NDArray } from './';
/**
 * @static
 * @memberof module:Globals
 * @function map
 * @description Equivalent to `TypedArray.prototype.map`.
 * @param {NDArray} x
 * @returns {NDArray}
 * @example
 * import { map } from 'vectorious/core/map';
 *
 * map([1, 2, 3], value => -value); // => array([-1, -2, -3])
 */
export declare const map: (x: NDArray | ArrayLike<any>, f: (value: number, i: number, src: TypedArray) => number) => NDArray;
/**
 * @function map
 * @memberof NDArray.prototype
 * @description Equivalent to `TypedArray.prototype.map`.
 * @returns {this}
 * @example
 * import { array } from 'vectorious/core/array';
 *
 * array([1, 2, 3]).map(value => -value); // => array([-1, -2, -3])
 */
export default function (this: NDArray, f: (value: number, i: number, src: TypedArray) => number): NDArray;


text:
@implementation WDActivityController

@synthesize table;
@synthesize activityManager;

- (id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (!self) {
        return nil;
    }

    self.title = NSLocalizedString(@"Activity", @"Activity");

    return self;
}

- (void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void) loadView
{
    table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 374) style:UITableViewStylePlain];
    self.view = table;

    table.delegate = self;
    table.dataSource = activityManager;
    table.allowsSelection = NO;

    self.preferredContentSize = table.frame.size;
}

- (void) setActivityManager:(WDActivityManager *)am
{
    activityManager = am;
    table.dataSource = am;

    // stop observing any previous activity managers that were set
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(activityAdded:) name:WDActivityAddedNotification object:am];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(activityRemoved:) name:WDActivityRemovedNotification object:am];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(activityProgressChanged:) name:WDActivityProgressChangedNotification object:am];
}

- (void) activityAdded:(NSNotification *)aNotification
{
    NSNumber    *index = (aNotification.userInfo)[@"index"];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index.integerValue inSection:0];

    [table beginUpdates];
    [table insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [table endUpdates];
}

- (void) activityRemoved:(NSNotification *)aNotification
{
    NSNumber    *index = (aNotification.userInfo)[@"index"];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index.integerValue inSection:0];

    [table beginUpdates];
    [table deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [table endUpdates];
}

- (void) activityProgressChanged:(NSNotification *)aNotification
{
    NSNumber    *index = (aNotification.userInfo)[@"index"];
    WDActivity  *activity = (aNotification.userInfo)[@"activity"];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index.integerValue inSection:0];

    UITableViewCell *layerCell = (UITableViewCell *) [table cellForRowAtIndexPath:indexPath];
    UIProgressView *progress = (UIProgressView *) [layerCell viewWithTag:2];
    progress.progress = activity.progress;
}

@end


text:
var vows = require('vows')
var assert = require('assert')
var pitchClass = require('../../lib/note/pitchClass')

vows.describe('note.pitchClass').addBatch({
  'note pitch class': function () {
    assert.equal(pitchClass('c#2'), 'C#')
    assert.equal(pitchClass('fx/4'), 'F##')
  },
  'array notation': function () {
    assert.deepEqual(pitchClass([1, 2, 0]), [1])
  }
}).export(module)