text:
package com.azure.resourcemanager.appcontainers.implementation;

import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.appcontainers.fluent.BillingMetersClient;
import com.azure.resourcemanager.appcontainers.fluent.models.BillingMeterCollectionInner;
import com.azure.resourcemanager.appcontainers.models.BillingMeterCollection;
import com.azure.resourcemanager.appcontainers.models.BillingMeters;

public final class BillingMetersImpl implements BillingMeters {
    private static final ClientLogger LOGGER = new ClientLogger(BillingMetersImpl.class);

    private final BillingMetersClient innerClient;

    private final com.azure.resourcemanager.appcontainers.ContainerAppsApiManager serviceManager;

    public BillingMetersImpl(
        BillingMetersClient innerClient,
        com.azure.resourcemanager.appcontainers.ContainerAppsApiManager serviceManager) {
        this.innerClient = innerClient;
        this.serviceManager = serviceManager;
    }

    public Response<BillingMeterCollection> getWithResponse(String location, Context context) {
        Response<BillingMeterCollectionInner> inner = this.serviceClient().getWithResponse(location, context);
        if (inner != null) {
            return new SimpleResponse<>(
                inner.getRequest(),
                inner.getStatusCode(),
                inner.getHeaders(),
                new BillingMeterCollectionImpl(inner.getValue(), this.manager()));
        } else {
            return null;
        }
    }

    public BillingMeterCollection get(String location) {
        BillingMeterCollectionInner inner = this.serviceClient().get(location);
        if (inner != null) {
            return new BillingMeterCollectionImpl(inner, this.manager());
        } else {
            return null;
        }
    }

    private BillingMetersClient serviceClient() {
        return this.innerClient;
    }

    private com.azure.resourcemanager.appcontainers.ContainerAppsApiManager manager() {
        return this.serviceManager;
    }
}


text:
class Gun;

class Player : public Human
{
public:
    Player();
    ~Player();

    void init(float speed, glm::vec2 pos, Bengine::InputManager* inputManager, Bengine::Camera2D* camera, std::vector<Bullet>* bullets);

    void addGun(Gun* gun);

    void update(const std::vector<std::string>& levelData,
                std::vector<Human*>& humans,
                std::vector<Zombie*>& zombies,
                float deltaTime) override;
private:
    Bengine::InputManager* _inputManager;

    std::vector<Gun*> _guns;
    int _currentGunIndex;

    Bengine::Camera2D* _camera;
    std::vector<Bullet>* _bullets;

};

redpajama_set_name: RedPajamaGithub


text:
import { gql } from '@apollo/client'

import channelMetadataFragment from 'v2/components/ChannelMetadata/fragments/channelMetadata'
import { channelPageMetaTagsFragment } from 'v2/pages/channel/components/ChannelPageMetaTags/fragments/channelPageMetaTags'
import { channelEmptyMessageFragment } from 'v2/components/ChannelEmptyMessage/fragments/channelEmptyMessage'
import { channelContentsFilterFragment } from 'v2/components/ChannelContentsFilter/fragments/channelContentsFilter'

export default gql`
  query ChannelPage($id: ID!) {
    channel(id: $id) {
      ...ChannelMetadata
      ...ChannelPageMetaTags
      ...ChannelEmptyMessage
      ...ChannelContentsFilter
    }
  }
  ${channelMetadataFragment}
  ${channelPageMetaTagsFragment}
  ${channelEmptyMessageFragment}
  ${channelContentsFilterFragment}
`


text:
/**
 * GUIWebSocket
 * ------------
 * Manages a WebSocket for sending data to the GUI.
 */
var WebSocketLib = require('ws');
var WebSocketServer = WebSocketLib.Server;
var Logger = require('./Logger');

/**
 * @constructor
 */
function GUIWebSocket(port) {
    // We store the port...
    this._port = port;
}

/**
 * connect
 * -------
 * Connects and calls onConnect when we have received a message from a client.
 */
GUIWebSocket.prototype.connect = function(onConnect) {
    // We create the server...
    this.server = new WebSocketServer({port:this._port});

    // We call back when we get a connection...
    Logger.log("Waiting for GUI connection...", Logger.LogLevel.INFO);
    this.server.on('connection', function(ws) {
        // We've received a connection...
        Logger.log("Got a GUI connection!", Logger.LogLevel.INFO);
        onConnect();
    });
};

/**
 * broadcast
 * ---------
 * Sends the data to all clients attached to the WebSocket.
 */
GUIWebSocket.prototype.broadcast = function(jsonData) {
    for(var i in this.server.clients) {
        this.server.clients[i].send(jsonData);
    }
};

// Exports...
module.exports = GUIWebSocket;


text:
/* Tabulator v4.7.0 (c) Oliver Folkerd */

var ReactiveData = function ReactiveData(table) {
	this.table = table; //hold Tabulator object
	this.data = false;
	this.blocked = false; //block reactivity while performing update
	this.origFuncs = {}; // hold original data array functions to allow replacement after data is done with
	this.currentVersion = 0;
};

ReactiveData.prototype.watchData = function (data) {
	var self = this,
	    pushFunc,
	    version;

	this.currentVersion++;

	version = this.currentVersion;

	self.unwatchData();

	self.data = data;

	//override array push function
	self.origFuncs.push = data.push;

	Object.defineProperty(self.data, "push", {
		enumerable: false,
		configurable: true,
		value: function value() {
			var args = Array.from(arguments);

			if (!self.blocked && version === self.currentVersion) {
				args.forEach(function (arg) {
					self.table.rowManager.addRowActual(arg, false);
				});
			}

			return self.origFuncs.push.apply(data, arguments);
		}
	});

	//override array unshift function
	self.origFuncs.unshift = data.unshift;

	Object.defineProperty(self.data, "unshift", {
		enumerable: false,
		configurable: true,
		value: function value() {
			var args = Array.from(arguments);

			if (!self.blocked && version === self.currentVersion) {
				args.forEach(function (arg) {
					self.table.rowManager.addRowActual(arg, true);
				});
			}

			return self.origFuncs.unshift.apply(data, arguments);
		}
	});

	//override array shift function
	self.origFuncs.shift = data.shift;

	Object.defineProperty(self.data, "shift", {
		enumerable: false,
		configurable: true,
		value: function value() {
			var row;

			if (!self.blocked && version === self.currentVersion) {
				if (self.data.length) {
					row = self.table.rowManager.getRowFromDataObject(self.data[0]);

					if (row) {
						row.deleteActual();
					}
				}
			}

			return self.origFuncs.shift.call(data);
		}
	});

	//override array pop function
	self.origFuncs.pop = data.pop;

	Object.defineProperty(self.data, "pop", {
		enumerable: false,
		configurable: true,
		value: function value() {
			var row;
			if (!self.blocked && version === self.currentVersion) {
				if (self.data.length) {
					row = self.table.rowManager.getRowFromDataObject(self.data[self.data.length - 1]);

					if (row) {
						row.deleteActual();
					}
				}
			}
			return self.origFuncs.pop.call(data);
		}
	});

	//override array splice function
	self.origFuncs.splice = data.splice;

	Object.defineProperty(self.data, "splice", {
		enumerable: false,
		configurable: true,
		value: function value() {
			var args = Array.from(arguments),
			    start = args[0] < 0 ? data.length + args[0] : args[0],
			    end = args[1],
			    newRows = args[2] ? args.slice(2) : false,
			    startRow;

			if (!self.blocked && version === self.currentVersion) {

				//add new rows
				if (newRows) {
					startRow = data[start] ? self.table.rowManager.getRowFromDataObject(data[start]) : false;

					if (startRow) {
						newRows.forEach(function (rowData) {
							self.table.rowManager.addRowActual(rowData, true, startRow, true);
						});
					} else {
						newRows = newRows.slice().reverse();

						newRows.forEach(function (rowData) {
							self.table.rowManager.addRowActual(rowData, true, false, true);
						});
					}
				}

				//delete removed rows
				if (end !== 0) {
					var oldRows = data.slice(start, typeof args[1] === "undefined" ? args[1] : start + end);

					oldRows.forEach(function (rowData, i) {
						var row = self.table.rowManager.getRowFromDataObject(rowData);

						if (row) {
							row.deleteActual(i !== oldRows.length - 1);
						}
					});
				}

				if (newRows || end !== 0) {
					self.table.rowManager.reRenderInPosition();
				}
			}

			return self.origFuncs.splice.apply(data, arguments);
		}
	});
};

ReactiveData.prototype.unwatchData = function () {
	if (this.data !== false) {
		for (var key in this.origFuncs) {
			Object.defineProperty(this.data, key, {
				enumerable: true,
				configurable: true,
				writable: true,
				value: this.origFuncs.key
			});
		}
	}
};

ReactiveData.prototype.watchRow = function (row) {
	var self = this,
	    data = row.getData();

	this.blocked = true;

	for (var key in data) {
		this.watchKey(row, data, key);
	}

	this.blocked = false;
};

ReactiveData.prototype.watchKey = function (row, data, key) {
	var self = this,
	    props = Object.getOwnPropertyDescriptor(data, key),
	    value = data[key],
	    version = this.currentVersion;

	Object.defineProperty(data, key, {
		set: function set(newValue) {
			value = newValue;
			if (!self.blocked && version === self.currentVersion) {
				var update = {};
				update[key] = newValue;
				row.updateData(update);
			}

			if (props.set) {
				props.set(newValue);
			}
		},
		get: function get() {

			if (props.get) {
				props.get();
			}

			return value;
		}
	});
};

ReactiveData.prototype.unwatchRow = function (row) {
	var data = row.getData();

	for (var key in data) {
		Object.defineProperty(data, key, {
			value: data[key]
		});
	}
};

ReactiveData.prototype.block = function () {
	this.blocked = true;
};

ReactiveData.prototype.unblock = function () {
	this.blocked = false;
};

Tabulator.prototype.registerModule("reactiveData", ReactiveData);


text:
from __future__ import division, print_function

from functools import partial

import numpy as np

from pandas.core.common import isnull
import pandas.core.nanops as nanops
import pandas.util.testing as tm

nanops._USE_BOTTLENECK = False

class TestnanopsDataFrame(tm.TestCase):
    def setUp(self):
        np.random.seed(11235)

        self.arr_shape = (11, 7, 5)

        self.arr_float = np.random.randn(*self.arr_shape)
        self.arr_float1 = np.random.randn(*self.arr_shape)
        self.arr_complex = self.arr_float + self.arr_float1*1j
        self.arr_int = np.random.randint(-10, 10, self.arr_shape)
        self.arr_bool = np.random.randint(0, 2, self.arr_shape) == 0
        self.arr_str = np.abs(self.arr_float).astype('S')
        self.arr_utf = np.abs(self.arr_float).astype('U')
        self.arr_date = np.random.randint(0, 20000,
                                          self.arr_shape).astype('M8[ns]')
        self.arr_tdelta = np.random.randint(0, 20000,
                                            self.arr_shape).astype('m8[ns]')

        self.arr_nan = np.tile(np.nan, self.arr_shape)
        self.arr_float_nan = np.vstack([self.arr_float, self.arr_nan])
        self.arr_float1_nan = np.vstack([self.arr_float1, self.arr_nan])
        self.arr_nan_float1 = np.vstack([self.arr_nan, self.arr_float1])
        self.arr_nan_nan = np.vstack([self.arr_nan, self.arr_nan])

        self.arr_inf = self.arr_float*np.inf
        self.arr_float_inf = np.vstack([self.arr_float, self.arr_inf])
        self.arr_float1_inf = np.vstack([self.arr_float1, self.arr_inf])
        self.arr_inf_float1 = np.vstack([self.arr_inf, self.arr_float1])
        self.arr_inf_inf = np.vstack([self.arr_inf, self.arr_inf])

        self.arr_nan_inf = np.vstack([self.arr_nan, self.arr_inf])
        self.arr_float_nan_inf = np.vstack([self.arr_float,
                                            self.arr_nan,
                                            self.arr_inf])
        self.arr_nan_float1_inf = np.vstack([self.arr_float,
                                             self.arr_inf,
                                             self.arr_nan])
        self.arr_nan_nan_inf = np.vstack([self.arr_nan,
                                          self.arr_nan,
                                          self.arr_inf])
        self.arr_obj = np.vstack([self.arr_float.astype('O'),
                                  self.arr_int.astype('O'),
                                  self.arr_bool.astype('O'),
                                  self.arr_complex.astype('O'),
                                  self.arr_str.astype('O'),
                                  self.arr_utf.astype('O'),
                                  self.arr_date.astype('O'),
                                  self.arr_tdelta.astype('O')])

        self.arr_nan_nanj = self.arr_nan + self.arr_nan*1j
        self.arr_complex_nan = np.vstack([self.arr_complex, self.arr_nan_nanj])

        self.arr_nan_infj = self.arr_inf*1j
        self.arr_complex_nan_infj = np.vstack([self.arr_complex,
                                              self.arr_nan_infj])

        self.arr_float_2d = self.arr_float[:, :, 0]
        self.arr_float1_2d = self.arr_float1[:, :, 0]
        self.arr_complex_2d = self.arr_complex[:, :, 0]
        self.arr_int_2d = self.arr_int[:, :, 0]
        self.arr_bool_2d = self.arr_bool[:, :, 0]
        self.arr_str_2d = self.arr_str[:, :, 0]
        self.arr_utf_2d = self.arr_utf[:, :, 0]
        self.arr_date_2d = self.arr_date[:, :, 0]
        self.arr_tdelta_2d = self.arr_tdelta[:, :, 0]

        self.arr_nan_2d = self.arr_nan[:, :, 0]
        self.arr_float_nan_2d = self.arr_float_nan[:, :, 0]
        self.arr_float1_nan_2d = self.arr_float1_nan[:, :, 0]
        self.arr_nan_float1_2d = self.arr_nan_float1[:, :, 0]
        self.arr_nan_nan_2d = self.arr_nan_nan[:, :, 0]
        self.arr_nan_nanj_2d = self.arr_nan_nanj[:, :, 0]
        self.arr_complex_nan_2d = self.arr_complex_nan[:, :, 0]

        self.arr_inf_2d = self.arr_inf[:, :, 0]
        self.arr_float_inf_2d = self.arr_float_inf[:, :, 0]
        self.arr_nan_inf_2d = self.arr_nan_inf[:, :, 0]
        self.arr_float_nan_inf_2d = self.arr_float_nan_inf[:, :, 0]
        self.arr_nan_nan_inf_2d = self.arr_nan_nan_inf[:, :, 0]

        self.arr_float_1d = self.arr_float[:, 0, 0]
        self.arr_float1_1d = self.arr_float1[:, 0, 0]
        self.arr_complex_1d = self.arr_complex[:, 0, 0]
        self.arr_int_1d = self.arr_int[:, 0, 0]
        self.arr_bool_1d = self.arr_bool[:, 0, 0]
        self.arr_str_1d = self.arr_str[:, 0, 0]
        self.arr_utf_1d = self.arr_utf[:, 0, 0]
        self.arr_date_1d = self.arr_date[:, 0, 0]
        self.arr_tdelta_1d = self.arr_tdelta[:, 0, 0]

        self.arr_nan_1d = self.arr_nan[:, 0, 0]
        self.arr_float_nan_1d = self.arr_float_nan[:, 0, 0]
        self.arr_float1_nan_1d = self.arr_float1_nan[:, 0, 0]
        self.arr_nan_float1_1d = self.arr_nan_float1[:, 0, 0]
        self.arr_nan_nan_1d = self.arr_nan_nan[:, 0, 0]
        self.arr_nan_nanj_1d = self.arr_nan_nanj[:, 0, 0]
        self.arr_complex_nan_1d = self.arr_complex_nan[:, 0, 0]

        self.arr_inf_1d = self.arr_inf.ravel()
        self.arr_float_inf_1d = self.arr_float_inf[:, 0, 0]
        self.arr_nan_inf_1d = self.arr_nan_inf[:, 0, 0]
        self.arr_float_nan_inf_1d = self.arr_float_nan_inf[:, 0, 0]
        self.arr_nan_nan_inf_1d = self.arr_nan_nan_inf[:, 0, 0]

    def check_results(self, targ, res, axis):
        res = getattr(res, 'asm8', res)
        res = getattr(res, 'values', res)

        # timedeltas are a beast here
        def _coerce_tds(targ, res):
            if targ.dtype == 'm8[ns]':
                if len(targ) == 1:
                    targ = targ[0].item()
                    res = res.item()
                else:
                    targ = targ.view('i8')
            return targ, res

        try:
            if axis != 0 and hasattr(targ, 'shape') and targ.ndim:
                res = np.split(res, [targ.shape[0]], axis=0)[0]
        except:
            targ, res = _coerce_tds(targ, res)

        try:
            tm.assert_almost_equal(targ, res)
        except:

            if targ.dtype == 'm8[ns]':
                targ, res = _coerce_tds(targ, res)
                tm.assert_almost_equal(targ, res)
                return

            # There are sometimes rounding errors with
            # complex and object dtypes.
            # If it isn't one of those, re-raise the error.
            if not hasattr(res, 'dtype') or res.dtype.kind not in ['c', 'O']:
                raise
            # convert object dtypes to something that can be split into
            # real and imaginary parts
            if res.dtype.kind == 'O':
                if targ.dtype.kind != 'O':
                    res = res.astype(targ.dtype)
                else:
                    try:
                        res = res.astype('c16')
                    except:
                        res = res.astype('f8')
                    try:
                        targ = targ.astype('c16')
                    except:
                        targ = targ.astype('f8')
            # there should never be a case where numpy returns an object
            # but nanops doesn't, so make that an exception
            elif targ.dtype.kind == 'O':
                raise
            tm.assert_almost_equal(targ.real, res.real)
            tm.assert_almost_equal(targ.imag, res.imag)

    def check_fun_data(self, testfunc, targfunc,
                       testarval, targarval, targarnanval, **kwargs):
        for axis in list(range(targarval.ndim))+[None]:
            for skipna in [False, True]:
                targartempval = targarval if skipna else targarnanval
                try:
                    targ = targfunc(targartempval, axis=axis, **kwargs)
                    res = testfunc(testarval, axis=axis, skipna=skipna,
                                   **kwargs)
                    self.check_results(targ, res, axis)
                    if skipna:
                        res = testfunc(testarval, axis=axis)
                        self.check_results(targ, res, axis)
                    if axis is None:
                        res = testfunc(testarval, skipna=skipna)
                        self.check_results(targ, res, axis)
                    if skipna and axis is None:
                        res = testfunc(testarval)
                        self.check_results(targ, res, axis)
                except BaseException as exc:
                    exc.args += ('axis: %s of %s' % (axis, testarval.ndim-1),
                                 'skipna: %s' % skipna,
                                 'kwargs: %s' % kwargs)
                    raise

        if testarval.ndim <= 1:
            return

        try:
            testarval2 = np.take(testarval, 0, axis=-1)
            targarval2 = np.take(targarval, 0, axis=-1)
            targarnanval2 = np.take(targarnanval, 0, axis=-1)
        except ValueError:
            return
        self.check_fun_data(testfunc, targfunc,
                            testarval2, targarval2, targarnanval2,
                            **kwargs)

    def check_fun(self, testfunc, targfunc,
                  testar, targar=None, targarnan=None,
                  **kwargs):
        if targar is None:
            targar = testar
        if targarnan is None:
            targarnan = testar
        testarval = getattr(self, testar)
        targarval = getattr(self, targar)
        targarnanval = getattr(self, targarnan)
        try:
            self.check_fun_data(testfunc, targfunc,
                                testarval, targarval, targarnanval, **kwargs)
        except BaseException as exc:
            exc.args += ('testar: %s' % testar,
                         'targar: %s' % targar,
                         'targarnan: %s' % targarnan)
            raise

    def check_funs(self, testfunc, targfunc,
                   allow_complex=True, allow_all_nan=True, allow_str=True,
                   allow_date=True, allow_tdelta=True, allow_obj=True,
                   **kwargs):
        self.check_fun(testfunc, targfunc, 'arr_float', **kwargs)
        self.check_fun(testfunc, targfunc, 'arr_float_nan', 'arr_float',
                       **kwargs)
        self.check_fun(testfunc, targfunc, 'arr_int', **kwargs)
        self.check_fun(testfunc, targfunc, 'arr_bool', **kwargs)
        objs = [self.arr_float.astype('O'),
                self.arr_int.astype('O'),
                self.arr_bool.astype('O')]

        if allow_all_nan:
            self.check_fun(testfunc, targfunc, 'arr_nan', **kwargs)

        if allow_complex:
            self.check_fun(testfunc, targfunc, 'arr_complex', **kwargs)
            self.check_fun(testfunc, targfunc,
                           'arr_complex_nan', 'arr_complex', **kwargs)
            if allow_all_nan:
                self.check_fun(testfunc, targfunc, 'arr_nan_nanj', **kwargs)
            objs += [self.arr_complex.astype('O')]

        if allow_str:
            self.check_fun(testfunc, targfunc, 'arr_str', **kwargs)
            self.check_fun(testfunc, targfunc, 'arr_utf', **kwargs)
            objs += [self.arr_str.astype('O'),
                     self.arr_utf.astype('O')]

        if allow_date:
            try:
                targfunc(self.arr_date)
            except TypeError:
                pass
            else:
                self.check_fun(testfunc, targfunc, 'arr_date', **kwargs)
                objs += [self.arr_date.astype('O')]

        if allow_tdelta:
            try:
                targfunc(self.arr_tdelta)
            except TypeError:
                pass
            else:
                self.check_fun(testfunc, targfunc, 'arr_tdelta', **kwargs)
                objs += [self.arr_tdelta.astype('O')]

        if allow_obj:
            self.arr_obj = np.vstack(objs)
            # some nanops handle object dtypes better than their numpy
            # counterparts, so the numpy functions need to be given something
            # else
            if allow_obj == 'convert':
                targfunc = partial(self._badobj_wrap,
                                   func=targfunc, allow_complex=allow_complex)
            self.check_fun(testfunc, targfunc, 'arr_obj', **kwargs)

    def check_funs_ddof(self, testfunc, targfunc,
                        allow_complex=True, allow_all_nan=True, allow_str=True,
                        allow_date=False, allow_tdelta=False, allow_obj=True,):
        for ddof in range(3):
            try:
                self.check_funs(self, testfunc, targfunc,
                                allow_complex, allow_all_nan, allow_str,
                                allow_date, allow_tdelta, allow_obj,
                                ddof=ddof)
            except BaseException as exc:
                exc.args += ('ddof %s' % ddof,)

    def _badobj_wrap(self, value, func, allow_complex=True, **kwargs):
        if value.dtype.kind == 'O':
            if allow_complex:
                value = value.astype('c16')
            else:
                value = value.astype('f8')
        return func(value, **kwargs)

    def test_nanany(self):
        self.check_funs(nanops.nanany, np.any,
                        allow_all_nan=False, allow_str=False, allow_date=False, allow_tdelta=False)

    def test_nanall(self):
        self.check_funs(nanops.nanall, np.all,
                        allow_all_nan=False, allow_str=False, allow_date=False, allow_tdelta=False)

    def test_nansum(self):
        self.check_funs(nanops.nansum, np.sum,
                        allow_str=False, allow_date=False, allow_tdelta=True)

    def test_nanmean(self):
        self.check_funs(nanops.nanmean, np.mean,
                        allow_complex=False, allow_obj=False,
                        allow_str=False, allow_date=False, allow_tdelta=True)

    def test_nanmedian(self):
        self.check_funs(nanops.nanmedian, np.median,
                        allow_complex=False, allow_str=False, allow_date=False,
                        allow_tdelta=True,
                        allow_obj='convert')

    def test_nanvar(self):
        self.check_funs_ddof(nanops.nanvar, np.var,
                             allow_complex=False, allow_date=False, allow_tdelta=False)

    def test_nanstd(self):
        self.check_funs_ddof(nanops.nanstd, np.std,
                             allow_complex=False, allow_date=False, allow_tdelta=True)

    def test_nansem(self):
        tm.skip_if_no_package('scipy.stats')
        self.check_funs_ddof(nanops.nansem, np.var,
                             allow_complex=False, allow_date=False, allow_tdelta=False)

    def _minmax_wrap(self, value, axis=None, func=None):
        res = func(value, axis)
        if res.dtype.kind == 'm':
            res = np.atleast_1d(res)
        return res

    def test_nanmin(self):
        func = partial(self._minmax_wrap, func=np.min)
        self.check_funs(nanops.nanmin, func,
                        allow_str=False, allow_obj=False)

    def test_nanmax(self):
        func = partial(self._minmax_wrap, func=np.max)
        self.check_funs(nanops.nanmax, func,
                        allow_str=False, allow_obj=False)

    def _argminmax_wrap(self, value, axis=None, func=None):
        res = func(value, axis)
        nans = np.min(value, axis)
        nullnan = isnull(nans)
        if res.ndim:
            res[nullnan] = -1
        elif (hasattr(nullnan, 'all') and nullnan.all() or
              not hasattr(nullnan, 'all') and nullnan):
            res = -1
        return res

    def test_nanargmax(self):
        func = partial(self._argminmax_wrap, func=np.argmax)
        self.check_funs(nanops.nanargmax, func,
                        allow_str=False, allow_obj=False,
                        allow_date=True,
                        allow_tdelta=True)

    def test_nanargmin(self):
        func = partial(self._argminmax_wrap, func=np.argmin)
        if tm.sys.version_info[0:2] == (2, 6):
            self.check_funs(nanops.nanargmin, func,
                            allow_date=True,
                            allow_tdelta=True,
                            allow_str=False, allow_obj=False)
        else:
            self.check_funs(nanops.nanargmin, func,
                            allow_str=False, allow_obj=False)

    def _skew_kurt_wrap(self, values, axis=None, func=None):
        if not isinstance(values.dtype.type, np.floating):
            values = values.astype('f8')
        result = func(values, axis=axis, bias=False)
        # fix for handling cases where all elements in an axis are the same
        if isinstance(result, np.ndarray):
            result[np.max(values, axis=axis) == np.min(values, axis=axis)] = 0
            return result
        elif np.max(values) == np.min(values):
            return 0.
        return result

    def test_nanskew(self):
        tm.skip_if_no_package('scipy.stats')
        from scipy.stats import skew
        func = partial(self._skew_kurt_wrap, func=skew)
        self.check_funs(nanops.nanskew, func,
                        allow_complex=False, allow_str=False, allow_date=False, allow_tdelta=False)

    def test_nankurt(self):
        tm.skip_if_no_package('scipy.stats')
        from scipy.stats import kurtosis
        func1 = partial(kurtosis, fisher=True)
        func = partial(self._skew_kurt_wrap, func=func1)
        self.check_funs(nanops.nankurt, func,
                        allow_complex=False, allow_str=False, allow_date=False, allow_tdelta=False)

    def test_nanprod(self):
        self.check_funs(nanops.nanprod, np.prod,
                        allow_str=False, allow_date=False, allow_tdelta=False)

    def check_nancorr_nancov_2d(self, checkfun, targ0, targ1, **kwargs):
        res00 = checkfun(self.arr_float_2d, self.arr_float1_2d,
                         **kwargs)
        res01 = checkfun(self.arr_float_2d, self.arr_float1_2d,
                         min_periods=len(self.arr_float_2d)-1,
                         **kwargs)
        tm.assert_almost_equal(targ0, res00)
        tm.assert_almost_equal(targ0, res01)

        res10 = checkfun(self.arr_float_nan_2d, self.arr_float1_nan_2d,
                         **kwargs)
        res11 = checkfun(self.arr_float_nan_2d, self.arr_float1_nan_2d,
                         min_periods=len(self.arr_float_2d)-1,
                         **kwargs)
        tm.assert_almost_equal(targ1, res10)
        tm.assert_almost_equal(targ1, res11)

        targ2 = np.nan
        res20 = checkfun(self.arr_nan_2d, self.arr_float1_2d,
                         **kwargs)
        res21 = checkfun(self.arr_float_2d, self.arr_nan_2d,
                         **kwargs)
        res22 = checkfun(self.arr_nan_2d, self.arr_nan_2d,
                         **kwargs)
        res23 = checkfun(self.arr_float_nan_2d, self.arr_nan_float1_2d,
                         **kwargs)
        res24 = checkfun(self.arr_float_nan_2d, self.arr_nan_float1_2d,
                         min_periods=len(self.arr_float_2d)-1,
                         **kwargs)
        res25 = checkfun(self.arr_float_2d, self.arr_float1_2d,
                         min_periods=len(self.arr_float_2d)+1,
                         **kwargs)
        tm.assert_almost_equal(targ2, res20)
        tm.assert_almost_equal(targ2, res21)
        tm.assert_almost_equal(targ2, res22)
        tm.assert_almost_equal(targ2, res23)
        tm.assert_almost_equal(targ2, res24)
        tm.assert_almost_equal(targ2, res25)

    def check_nancorr_nancov_1d(self, checkfun, targ0, targ1, **kwargs):
        res00 = checkfun(self.arr_float_1d, self.arr_float1_1d,
                         **kwargs)
        res01 = checkfun(self.arr_float_1d, self.arr_float1_1d,
                         min_periods=len(self.arr_float_1d)-1,
                         **kwargs)
        tm.assert_almost_equal(targ0, res00)
        tm.assert_almost_equal(targ0, res01)

        res10 = checkfun(self.arr_float_nan_1d,
                         self.arr_float1_nan_1d,
                         **kwargs)
        res11 = checkfun(self.arr_float_nan_1d,
                         self.arr_float1_nan_1d,
                         min_periods=len(self.arr_float_1d)-1,
                         **kwargs)
        tm.assert_almost_equal(targ1, res10)
        tm.assert_almost_equal(targ1, res11)

        targ2 = np.nan
        res20 = checkfun(self.arr_nan_1d, self.arr_float1_1d,
                         **kwargs)
        res21 = checkfun(self.arr_float_1d, self.arr_nan_1d,
                         **kwargs)
        res22 = checkfun(self.arr_nan_1d, self.arr_nan_1d,
                         **kwargs)
        res23 = checkfun(self.arr_float_nan_1d,
                         self.arr_nan_float1_1d,
                         **kwargs)
        res24 = checkfun(self.arr_float_nan_1d,
                         self.arr_nan_float1_1d,
                         min_periods=len(self.arr_float_1d)-1,
                         **kwargs)
        res25 = checkfun(self.arr_float_1d,
                         self.arr_float1_1d,
                         min_periods=len(self.arr_float_1d)+1,
                         **kwargs)
        tm.assert_almost_equal(targ2, res20)
        tm.assert_almost_equal(targ2, res21)
        tm.assert_almost_equal(targ2, res22)
        tm.assert_almost_equal(targ2, res23)
        tm.assert_almost_equal(targ2, res24)
        tm.assert_almost_equal(targ2, res25)

    def test_nancorr(self):
        targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1]
        targ1 = np.corrcoef(self.arr_float_2d.flat,
                            self.arr_float1_2d.flat)[0, 1]
        self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1)
        targ0 = np.corrcoef(self.arr_float_1d, self.arr_float1_1d)[0, 1]
        targ1 = np.corrcoef(self.arr_float_1d.flat,
                            self.arr_float1_1d.flat)[0, 1]
        self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1,
                                     method='pearson')

    def test_nancorr_pearson(self):
        targ0 = np.corrcoef(self.arr_float_2d, self.arr_float1_2d)[0, 1]
        targ1 = np.corrcoef(self.arr_float_2d.flat,
                            self.arr_float1_2d.flat)[0, 1]
        self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1,
                                     method='pearson')
        targ0 = np.corrcoef(self.arr_float_1d, self.arr_float1_1d)[0, 1]
        targ1 = np.corrcoef(self.arr_float_1d.flat,
                            self.arr_float1_1d.flat)[0, 1]
        self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1,
                                     method='pearson')

    def test_nancorr_kendall(self):
        tm.skip_if_no_package('scipy.stats')
        from scipy.stats import kendalltau
        targ0 = kendalltau(self.arr_float_2d, self.arr_float1_2d)[0]
        targ1 = kendalltau(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0]
        self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1,
                                     method='kendall')
        targ0 = kendalltau(self.arr_float_1d, self.arr_float1_1d)[0]
        targ1 = kendalltau(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0]
        self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1,
                                     method='kendall')

    def test_nancorr_spearman(self):
        tm.skip_if_no_package('scipy.stats')
        from scipy.stats import spearmanr
        targ0 = spearmanr(self.arr_float_2d, self.arr_float1_2d)[0]
        targ1 = spearmanr(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0]
        self.check_nancorr_nancov_2d(nanops.nancorr, targ0, targ1,
                                     method='spearman')
        targ0 = spearmanr(self.arr_float_1d, self.arr_float1_1d)[0]
        targ1 = spearmanr(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0]
        self.check_nancorr_nancov_1d(nanops.nancorr, targ0, targ1,
                                     method='spearman')

    def test_nancov(self):
        targ0 = np.cov(self.arr_float_2d, self.arr_float1_2d)[0, 1]
        targ1 = np.cov(self.arr_float_2d.flat, self.arr_float1_2d.flat)[0, 1]
        self.check_nancorr_nancov_2d(nanops.nancov, targ0, targ1)
        targ0 = np.cov(self.arr_float_1d, self.arr_float1_1d)[0, 1]
        targ1 = np.cov(self.arr_float_1d.flat, self.arr_float1_1d.flat)[0, 1]
        self.check_nancorr_nancov_1d(nanops.nancov, targ0, targ1)

    def check_nancomp(self, checkfun, targ0):
        arr_float = self.arr_float
        arr_float1 = self.arr_float1
        arr_nan = self.arr_nan
        arr_nan_nan = self.arr_nan_nan
        arr_float_nan = self.arr_float_nan
        arr_float1_nan = self.arr_float1_nan
        arr_nan_float1 = self.arr_nan_float1

        while targ0.ndim:
            try:
                res0 = checkfun(arr_float, arr_float1)
                tm.assert_almost_equal(targ0, res0)

                if targ0.ndim > 1:
                    targ1 = np.vstack([targ0, arr_nan])
                else:
                    targ1 = np.hstack([targ0, arr_nan])
                res1 = checkfun(arr_float_nan, arr_float1_nan)
                tm.assert_almost_equal(targ1, res1)

                targ2 = arr_nan_nan
                res2 = checkfun(arr_float_nan, arr_nan_float1)
                tm.assert_almost_equal(targ2, res2)
            except Exception as exc:
                exc.args += ('ndim: %s' % arr_float.ndim,)
                raise

            try:
                arr_float = np.take(arr_float, 0, axis=-1)
                arr_float1 = np.take(arr_float1, 0, axis=-1)
                arr_nan = np.take(arr_nan, 0, axis=-1)
                arr_nan_nan = np.take(arr_nan_nan, 0, axis=-1)
                arr_float_nan = np.take(arr_float_nan, 0, axis=-1)
                arr_float1_nan = np.take(arr_float1_nan, 0, axis=-1)
                arr_nan_float1 = np.take(arr_nan_float1, 0, axis=-1)
                targ0 = np.take(targ0, 0, axis=-1)
            except ValueError:
                break

    def test_nangt(self):
        targ0 = self.arr_float > self.arr_float1
        self.check_nancomp(nanops.nangt, targ0)

    def test_nange(self):
        targ0 = self.arr_float >= self.arr_float1
        self.check_nancomp(nanops.nange, targ0)

    def test_nanlt(self):
        targ0 = self.arr_float < self.arr_float1
        self.check_nancomp(nanops.nanlt, targ0)

    def test_nanle(self):
        targ0 = self.arr_float <= self.arr_float1
        self.check_nancomp(nanops.nanle, targ0)

    def test_naneq(self):
        targ0 = self.arr_float == self.arr_float1
        self.check_nancomp(nanops.naneq, targ0)

    def test_nanne(self):
        targ0 = self.arr_float != self.arr_float1
        self.check_nancomp(nanops.nanne, targ0)

    def check_bool(self, func, value, correct, *args, **kwargs):
        while getattr(value, 'ndim', True):
            try:
                res0 = func(value, *args, **kwargs)
                if correct:
                    self.assertTrue(res0)
                else:
                    self.assertFalse(res0)
            except BaseException as exc:
                exc.args += ('dim: %s' % getattr(value, 'ndim', value),)
                raise
            if not hasattr(value, 'ndim'):
                break
            try:
                value = np.take(value, 0, axis=-1)
            except ValueError:
                break

    def test__has_infs(self):
        pairs = [('arr_complex', False),
                 ('arr_int', False),
                 ('arr_bool', False),
                 ('arr_str', False),
                 ('arr_utf', False),
                 ('arr_complex', False),
                 ('arr_complex_nan', False),

                 ('arr_nan_nanj', False),
                 ('arr_nan_infj', True),
                 ('arr_complex_nan_infj', True)]
        pairs_float = [('arr_float', False),
                       ('arr_nan', False),
                       ('arr_float_nan', False),
                       ('arr_nan_nan', False),

                       ('arr_float_inf', True),
                       ('arr_inf', True),
                       ('arr_nan_inf', True),
                       ('arr_float_nan_inf', True),
                       ('arr_nan_nan_inf', True)]

        for arr, correct in pairs:
            val = getattr(self, arr)
            try:
                self.check_bool(nanops._has_infs, val, correct)
            except BaseException as exc:
                exc.args += (arr,)
                raise

        for arr, correct in pairs_float:
            val = getattr(self, arr)
            try:
                self.check_bool(nanops._has_infs, val, correct)
                self.check_bool(nanops._has_infs, val.astype('f4'), correct)
                self.check_bool(nanops._has_infs, val.astype('f2'), correct)
            except BaseException as exc:
                exc.args += (arr,)
                raise

    def test__isfinite(self):
        pairs = [('arr_complex', False),
                 ('arr_int', False),
                 ('arr_bool', False),
                 ('arr_str', False),
                 ('arr_utf', False),
                 ('arr_complex', False),
                 ('arr_complex_nan', True),

                 ('arr_nan_nanj', True),
                 ('arr_nan_infj', True),
                 ('arr_complex_nan_infj', True)]
        pairs_float = [('arr_float', False),
                       ('arr_nan', True),
                       ('arr_float_nan', True),
                       ('arr_nan_nan', True),

                       ('arr_float_inf', True),
                       ('arr_inf', True),
                       ('arr_nan_inf', True),
                       ('arr_float_nan_inf', True),
                       ('arr_nan_nan_inf', True)]

        func1 = lambda x: np.any(nanops._isfinite(x).ravel())
        func2 = lambda x: np.any(nanops._isfinite(x).values.ravel())
        for arr, correct in pairs:
            val = getattr(self, arr)
            try:
                self.check_bool(func1, val, correct)
            except BaseException as exc:
                exc.args += (arr,)
                raise

        for arr, correct in pairs_float:
            val = getattr(self, arr)
            try:
                self.check_bool(func1, val, correct)
                self.check_bool(func1, val.astype('f4'), correct)
                self.check_bool(func1, val.astype('f2'), correct)
            except BaseException as exc:
                exc.args += (arr,)
                raise

    def test__bn_ok_dtype(self):
        self.assertTrue(nanops._bn_ok_dtype(self.arr_float.dtype, 'test'))
        self.assertTrue(nanops._bn_ok_dtype(self.arr_complex.dtype, 'test'))
        self.assertTrue(nanops._bn_ok_dtype(self.arr_int.dtype, 'test'))
        self.assertTrue(nanops._bn_ok_dtype(self.arr_bool.dtype, 'test'))
        self.assertTrue(nanops._bn_ok_dtype(self.arr_str.dtype, 'test'))
        self.assertTrue(nanops._bn_ok_dtype(self.arr_utf.dtype, 'test'))
        self.assertFalse(nanops._bn_ok_dtype(self.arr_date.dtype, 'test'))
        self.assertFalse(nanops._bn_ok_dtype(self.arr_tdelta.dtype, 'test'))
        self.assertFalse(nanops._bn_ok_dtype(self.arr_obj.dtype, 'test'))

class TestEnsureNumeric(tm.TestCase):
    def test_numeric_values(self):
        # Test integer
        self.assertEqual(nanops._ensure_numeric(1), 1, 'Failed for int')
        # Test float
        self.assertEqual(nanops._ensure_numeric(1.1), 1.1, 'Failed for float')
        # Test complex
        self.assertEqual(nanops._ensure_numeric(1 + 2j), 1 + 2j,
                         'Failed for complex')

    def test_ndarray(self):
        # Test numeric ndarray
        values = np.array([1, 2, 3])
        self.assertTrue(np.allclose(nanops._ensure_numeric(values), values),
                        'Failed for numeric ndarray')

        # Test object ndarray
        o_values = values.astype(object)
        self.assertTrue(np.allclose(nanops._ensure_numeric(o_values), values),
                        'Failed for object ndarray')

        # Test convertible string ndarray
        s_values = np.array(['1', '2', '3'], dtype=object)
        self.assertTrue(np.allclose(nanops._ensure_numeric(s_values), values),
                        'Failed for convertible string ndarray')

        # Test non-convertible string ndarray
        s_values = np.array(['foo', 'bar', 'baz'], dtype=object)
        self.assertRaises(ValueError,
                          lambda: nanops._ensure_numeric(s_values))

    def test_convertable_values(self):
        self.assertTrue(np.allclose(nanops._ensure_numeric('1'), 1.0),
                        'Failed for convertible integer string')
        self.assertTrue(np.allclose(nanops._ensure_numeric('1.1'), 1.1),
                        'Failed for convertible float string')
        self.assertTrue(np.allclose(nanops._ensure_numeric('1+1j'), 1 + 1j),
                        'Failed for convertible complex string')

    def test_non_convertable_values(self):
        self.assertRaises(TypeError,
                          lambda: nanops._ensure_numeric('foo'))
        self.assertRaises(TypeError,
                          lambda: nanops._ensure_numeric({}))
        self.assertRaises(TypeError,
                          lambda: nanops._ensure_numeric([]))

if __name__ == '__main__':
    import nose
    nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure',
                         '-s'], exit=False)


text:
goog.provide('ol.test.style.IconImageCache');

goog.require('ol');
goog.require('ol.events');
goog.require('ol.style');
goog.require('ol.style.IconImage');

describe('ol.style.IconImageCache', function() {
  var originalMaxCacheSize;

  beforeEach(function() {
    var cache = ol.style.iconImageCache;
    cache.clear();
    originalMaxCacheSize = cache.maxCacheSize;
    cache.maxCacheSize_ = 4;
  });

  afterEach(function() {
    var cache = ol.style.iconImageCache;
    cache.maxCacheSize_ = originalMaxCacheSize;
    cache.clear();
  });

  describe('#expire', function() {
    it('expires images when expected', function() {
      var cache = ol.style.iconImageCache;

      var i, src, iconImage;

      for (i = 0; i < 4; ++i) {
        src = i + '';
        iconImage = new ol.style.IconImage(src, null);
        cache.set(src, null, null, iconImage);
      }

      expect(cache.cacheSize_).to.eql(4);

      cache.expire();
      expect(cache.cacheSize_).to.eql(4);

      src = '4';
      iconImage = new ol.style.IconImage(src, null);
      cache.set(src, null, null, iconImage);
      expect(cache.cacheSize_).to.eql(5);

      cache.expire(); // remove '0' and '4'
      expect(cache.cacheSize_).to.eql(3);

      src = '0';
      iconImage = new ol.style.IconImage(src, null);
      ol.events.listen(iconImage, 'change',
          ol.nullFunction, false);
      cache.set(src, null, null, iconImage);
      expect(cache.cacheSize_).to.eql(4);

      src = '4';
      iconImage = new ol.style.IconImage(src, null);
      ol.events.listen(iconImage, 'change',
          ol.nullFunction, false);
      cache.set(src, null, null, iconImage);
      expect(cache.cacheSize_).to.eql(5);

      // check that '0' and '4' are not removed from the cache
      cache.expire();
      expect(cache.get('0', null, null)).to.not.be(null);
      expect(cache.get('4', null, null)).to.not.be(null);
    });
  });
});


text:
/* global gb */

gb.texture_configuration = function()
{
    gb.configuration_base.call(this);
    this.json = null;

    Object.defineProperty(this, 'filename', {
        get: function()
        {
            return this.json.filename;
        }
    });

    Object.defineProperty(this, 'technique_name', {
        get: function()
        {
            return this.json.technique_name;
        }
    });

    Object.defineProperty(this, 'sampler_index', {
        get: function()
        {
            return this.json.sampler_index;
        }
    });

    Object.defineProperty(this, 'wrap_mode', {
        get: function()
        {
            return gb.configuration_base.string_to_glenum()[this.json.wrap_mode];
        }
    });

    Object.defineProperty(this, 'mag_filter', {
        get: function()
        {
            return gb.configuration_base.string_to_glenum()[this.json.mag_filter];
        }
    });

    Object.defineProperty(this, 'min_filter', {
        get: function()
        {
            return gb.configuration_base.string_to_glenum()[this.json.min_filter];
        }
    });
};

gb.texture_configuration.prototype = Object.create(gb.configuration_base.prototype);
gb.texture_configuration.prototype.constructor = gb.texture_configuration;

gb.texture_configuration.prototype.serialize = function(value)
{
    this.json = value;
};


text:
'use strict';

function getDescProp(obj, prop) {
   var parts = prop.split('.');
   while(parts.length) obj = obj[parts.shift()];
   return obj;
}

angular.module('gomApp.formUtil', [
   'ngMaterial'
])

.directive('gomAttrSelect', [
function() {
   return {
      restrict: 'E',
      templateUrl: 'components/formUtil/gomAttrSelect.html',
      scope: {
         attr: '=',
         model: '=',
      },
   };
}])

.directive('gomBlurSave', [
'$mdToast',
function($mdToast) {
   return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attr, ngModelCtrl) {
         var targetId = attr.gomBlurSave;
         element.on('blur', function(event) {
            if(ngModelCtrl.$pristine) return; // Hasn't changed
            ngModelCtrl.$validate(); // Run validator before check we're valid
            if(ngModelCtrl.$invalid) return; // Don't commit, is wrong
            var label = (attr.gomSaveLabel || ngModelCtrl.$name);
            var target = getDescProp(scope,targetId);
            target.$save(function() {
               $mdToast.show($mdToast.simple()
                  .content('Saved ' + label)
                  .hideDelay(500)
               );
            });
            ngModelCtrl.$setPristine();
         });
      }
   };
}])

.directive('gomChangeSave', [
'$mdToast',
function($mdToast) {
   return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attr, ngModelCtrl) {
         var targetId = attr.gomChangeSave;
         ngModelCtrl.$viewChangeListeners.push(function() {
            if(ngModelCtrl.$pristine) return; // Hasn't changed
            ngModelCtrl.$validate(); // Run validator before check we're valid
            if(ngModelCtrl.$invalid) return; // Don't commit, is wrong
            var label = (attr.gomSaveLabel || ngModelCtrl.$name);
            var target = getDescProp(scope,targetId);
            target.$save(function() {
               $mdToast.show($mdToast.simple()
                  .content('Saved ' + label)
                  .hideDelay(500)
               );
            });
            ngModelCtrl.$setPristine();
         });
      }
   };
}]);


text:
using System.Reflection;
using System.Runtime.InteropServices;
using Xamarin.Forms;
using Xamarin.Forms.Platform.UWP;

[assembly: AssemblyTitle("Xamarin.Forms.Platform.UAP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Dependency(typeof(WindowsSerializer))]

// Views

[assembly: ExportRenderer(typeof(Layout), typeof(LayoutRenderer))]
[assembly: ExportRenderer(typeof(BoxView), typeof(BoxViewRenderer))]
[assembly: ExportRenderer(typeof(Image), typeof(ImageRenderer))]
[assembly: ExportRenderer(typeof(Label), typeof(LabelRenderer))]
[assembly: ExportRenderer(typeof(Button), typeof(ButtonRenderer))]
[assembly: ExportRenderer(typeof(ListView), typeof(ListViewRenderer))]
[assembly: ExportRenderer(typeof(ScrollView), typeof(ScrollViewRenderer))]
[assembly: ExportRenderer(typeof(ProgressBar), typeof(ProgressBarRenderer))]
[assembly: ExportRenderer(typeof(Slider), typeof(SliderRenderer))]
[assembly: ExportRenderer(typeof(Switch), typeof(SwitchRenderer))]
[assembly: ExportRenderer(typeof(WebView), typeof(WebViewRenderer))]
[assembly: ExportRenderer(typeof(Frame), typeof(FrameRenderer))]
[assembly: ExportRenderer(typeof(ActivityIndicator), typeof(ActivityIndicatorRenderer))]
[assembly: ExportRenderer(typeof(Editor), typeof(EditorRenderer))]
[assembly: ExportRenderer(typeof(Picker), typeof(PickerRenderer))]
[assembly: ExportRenderer(typeof(TimePicker), typeof(TimePickerRenderer))]
[assembly: ExportRenderer(typeof(DatePicker), typeof(DatePickerRenderer))]
[assembly: ExportRenderer(typeof(Stepper), typeof(StepperRenderer))]
[assembly: ExportRenderer(typeof(Entry), typeof(EntryRenderer))]
[assembly: ExportRenderer(typeof(TableView), typeof(TableViewRenderer))]
[assembly: ExportRenderer(typeof(NativeViewWrapper), typeof(NativeViewWrapperRenderer))]

//ImageSources

[assembly: ExportImageSourceHandler(typeof(FileImageSource), typeof(FileImageSourceHandler))]
[assembly: ExportImageSourceHandler(typeof(StreamImageSource), typeof(StreamImageSourceHandler))]
[assembly: ExportImageSourceHandler(typeof(UriImageSource), typeof(UriImageSourceHandler))]

// Pages

[assembly: ExportRenderer(typeof(Page), typeof(PageRenderer))]
[assembly: ExportRenderer(typeof(NavigationPage), typeof(NavigationPageRenderer))]
[assembly: ExportRenderer(typeof(MasterDetailPage), typeof(MasterDetailPageRenderer))]
[assembly: ExportRenderer(typeof(CarouselPage), typeof(CarouselPageRenderer))]

// Cells

[assembly: ExportCell(typeof(Cell), typeof(TextCellRenderer))]
[assembly: ExportCell(typeof(ImageCell), typeof(ImageCellRenderer))]
[assembly: ExportCell(typeof(EntryCell), typeof(EntryCellRenderer))]
[assembly: ExportCell(typeof(SwitchCell), typeof(SwitchCellRenderer))]
[assembly: ExportCell(typeof(ViewCell), typeof(ViewCellRenderer))]
[assembly: Dependency(typeof(WindowsResourcesProvider))]
[assembly: ExportRenderer(typeof(SearchBar), typeof(SearchBarRenderer))]
[assembly: ExportRenderer(typeof(TabbedPage), typeof(TabbedPageRenderer))]


text:
                 {{ artist.name }}

Music

Biography

Related Artists

            {{ artist.name }} Top tracks

                Start station

                {{ (followingArtist) ? 'Unfollow' : 'follow' }} artist

                <mopify-track track="track" surrounding="toptracks" currentplayingtrack="currentPlayingTrack" type="type"> </mopify-track>

            {{ artist.name }} {{ currentview.name }}

                Start station

                <mopify-album album="album" class="single-tile col-lg-2 col-md-3 col-sm-4 col-xs-6"></mopify-album>

            {{ artist.bio.text }}

                <mopify-artist artist="relatedartist" class="single-tile col-lg-2 col-md-3 col-sm-4 col-xs-6"></mopify-artist>


text:
package jsky.image.gui;

import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;

import javax.media.jai.Interpolation;
import javax.media.jai.InterpolationNearest;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;

import jsky.coords.CoordinateConverter;
import jsky.coords.WorldCoordinateConverter;
import jsky.image.EmptyRenderedImage;
import jsky.image.ImageProcessor;
import jsky.image.operator.ImageOps;
import jsky.util.gui.BasicWindowMonitor;

/**
 * Implements a JAI (Java Advanced Imaging) based image
 * display window. Any JAI PlanarImage can be displayed. Grayscale
 * images may be displayed with false colors, depending on the
 * ImageProcessor options specified.  Coordinate conversion is
 * supported, although, since this class is not intended to be the
 * main image class, world coordinates are only supported if setWCS()
 * is called to set the world coordinates information.
 *
 * @see MainImageDisplay
 * @see ImageZoom
 * @see ImagePanner
 *
 * @version $Revision: 5923 $
 * @author Allan Brighton
 */
public class ImageDisplay extends JComponent
        implements BasicImageDisplay, ChangeListener {

    /** Image to use when there is no image to display */
    private static final PlanarImage _EMPTY_IMAGE = PlanarImage.wrapRenderedImage(new EmptyRenderedImage());

    /** Object used to prepare image for display. */
    private ImageProcessor _imageProcessor;

    /** The image being displayed, after processing. */
    private PlanarImage _displayImage;

    /** Used to delay image loading until window is visible. */
    private PlanarImage _pendingImage;

    /** The image's SampleModel. */
    private SampleModel _sampleModel;

    /** The image's ColorModel or one we supply. */
    private ColorModel _colorModel;

    /** Object used to convert coordinates */
    private CoordinateConverter _coordinateConverter;

    /** Zoom factor */
    private float _scale = 1.0f;

    /** The actual Zoom factor (used when zooming a prescaled image to lie about the scale factor) */
    private float _actualScale = 1.0f;

    /** Set to true if the image has been prescaled (pan window, thumbnail image). */
    private boolean _prescaled = false;

    /** Optional rendering hint for the scale operation. */
    private RenderingHints _scaleHints;

    /** The image display origin in canvas coords */
    private Point2D.Double _origin = new Point2D.Double(0, 0);

    /** true if image was centered in the window */
    private boolean _centered = false;

    /** Set to true (default) to automatically center the image, if it is smaller than the window. */
    private boolean _autoCenterImage = true;

    /** type of _interpolation to use for scaling */
    private Interpolation _interpolation = new InterpolationNearest();

    /** The image's min X tile. */
    private int _minTileX;

    /** The image's max X tile. */
    private int _maxTileX;

    /** The image's min Y tile. */
    private int _minTileY;

    /** The image's max Y tile. */
    private int _maxTileY;

    /** The image's tile width. */
    private int _tileWidth;

    /** The image's tile height. */
    private int _tileHeight;

    /** The image's tile grid X offset. */
    private int _tileGridXOffset;

    /** The image's tile grid Y offset. */
    private int _tileGridYOffset;

    /** if true, update image immediately for scrolling and other operations, otherwise on button release */
    private boolean _immediateMode = false;

    /** Object used to convert between image and world coordinates, when supported */
    private WorldCoordinateConverter _wcs;

    /** list of event listeners (ImageGraphicsHandlers) */
    private EventListenerList _listenerList = new EventListenerList();

    /**
     * Construct an image display widget with the given name to display
     * the output of the given image processor.
     *
     * @param imageProcessor Object managing the image
     * @param name name to associate with this instance
     */
    public ImageDisplay(ImageProcessor imageProcessor, String name) {
        setName(name);
        setImageProcessor(imageProcessor);
        _imageProcessor.setName(name);
        _coordinateConverter = new ImageCoordinateConverter(this);

        setBackground(Color.black);
        setPreferredSize(new Dimension(255, 255));	// default size

        // handle resize events
        addComponentListener(new ComponentAdapter() {

            public void componentResized(ComponentEvent e) {
                if (_pendingImage != null) {
                    setImage(_pendingImage);
                    _pendingImage = null;
                }
                updateImage();
            }
        });
    }

    /**
     * Construct an image display widget with the given name.
     *
     * @param name name to associate with this instance
     */
    public ImageDisplay(String name) {
        this(new ImageProcessor(), name);
    }

    /**
     * Construct an image display widget.
     */
    public ImageDisplay() {
        this("Image Display");
    }

    /**
     * Set the image processor to use to get the image to display.
     */
    public void setImageProcessor(ImageProcessor imageProcessor) {
        _imageProcessor = imageProcessor;

        // register to receive notification when the image changes
        _imageProcessor.removeChangeListener(this);
        _imageProcessor.addChangeListener(this);
    }

    /** Called for changes in the image processor settings */
    public void stateChanged(ChangeEvent ce) {
        updateImage();
    }

    /** Return the image processor object. */
    public ImageProcessor getImageProcessor() {
        return _imageProcessor;
    }

    /** Return the source image (before processing). */
    public PlanarImage getImage() {
        return _imageProcessor.getSourceImage();
    }

    /** Return the image being displayed (after image processing). */
    public PlanarImage getDisplayImage() {
        return _displayImage;
    }

    /** Return the object used to convert coordinates. */
    public CoordinateConverter getCoordinateConverter() {
        return _coordinateConverter;
    }

    /**
     * Set the image to display.
     */
    public void setImage(PlanarImage im) {
        // Note: we need to get the visible area of the image, but can't
        // use getVisibleArea(), since the image hasn't been displayed yet.
        // We know that the image will be centered when first loaded, so use
        // that area.
        int cw = getWidth(), ch = getHeight();
        if (cw == 0) {
            // System.out.println("XXX " + getName() + ": ImageDisplay.setImage can't get display size yet, will check again later...");
            _pendingImage = im;
            return;
        }
        double dw = im.getWidth() * _scale, dh = im.getHeight() * _scale;
        double x = Math.max((dw - cw) / 2.0, 0.);
        double y = Math.max((dh - ch) / 2.0, 0.);
        Rectangle2D.Double region = new Rectangle2D.Double(x / _scale, y / _scale, cw / _scale, ch / _scale);
        //System.out.println("XXX " + getName() + ": ImageDisplay.setImage region = : " + region);

        _newImage(true);		// call once before loading new image
        _imageProcessor.setSourceImage(im, region);
        _imageProcessor.update();
        _newImage(false);	// call once after loading new image
    }

    /**
     * Return the width of the source image in pixels
     */
    public int getImageWidth() {
        PlanarImage image = getImage();
        if (image != null) {
            if (_prescaled) // return original image size before prescaling
                return (int) (image.getWidth() / _scale);
            return image.getWidth();
        }
        return 0;
    }

    /**
     * Return the height of the source image in pixels
     */
    public int getImageHeight() {
        PlanarImage image = getImage();
        if (image != null) {
            if (_prescaled) // return original image size before prescaling
                return (int) (image.getHeight() / _scale);
            return image.getHeight();
        }
        return 0;
    }

    /**
     * This method is called before and after loading a new image.
     * @param before If true, it is before loading the image, otherwise afterwards.
     */
    private void _newImage(boolean before) {
        if (before) {	       // before loading image
            _centered = true;
        }
    }

    /**
     * Clear the image display, freeing up any resources currently used by the image
     * so that they can be garbage collected.
     */
    public void clear() {
        setImage(_EMPTY_IMAGE);
    }

    /**
     * Return true if the image has been cleared.
     */
    public boolean isClear() {
        PlanarImage im = _imageProcessor.getSourceImage();
        return (im == _EMPTY_IMAGE);
    }

    /** called when the image has changed to update the display */
    public void updateImage() {
        _updateImage(_imageProcessor.getDisplayImage());
    }

    /**
     * This method updates the source image for this window, which is
     * scaled to the correct magnification before displaying.
     */
    private void _updateImage(PlanarImage im) {
        if (im == null) {
            return;
        }

        // center the image if it is smaller than the window
        _centerImage(im);

        // scale and translate the image as needed
        _displayImage = _scale(im);

        _sampleModel = _displayImage.getSampleModel();
        if (_sampleModel == null)
            return;

        // First check whether the opimage has already set a suitable ColorModel
        _colorModel = _displayImage.getColorModel();
        if (_colorModel == null) {
            // If not, then create one.
            _colorModel = PlanarImage.createColorModel(_sampleModel);
            if (_colorModel == null) {
                throw new IllegalArgumentException("no color model");
            }
        }
        _minTileX = _displayImage.getMinTileX();
        _maxTileX = _displayImage.getMinTileX() + _displayImage.getNumXTiles() - 1;
        _minTileY = _displayImage.getMinTileY();
        _maxTileY = _displayImage.getMinTileY() + _displayImage.getNumYTiles() - 1;
        _tileWidth = _displayImage.getTileWidth();
        _tileHeight = _displayImage.getTileHeight();
        _tileGridXOffset = _displayImage.getTileGridXOffset();
        _tileGridYOffset = _displayImage.getTileGridYOffset();

        repaint();
    }

    /**
     * Return true if the image supports world coordinates (has the necessary keywords in the
     * header).
     */
    public boolean isWCS() {
        return _wcs != null;
    }

    /**
     * Return the object used to convert between image and world coordinates,
     * or null if none was set.
     */
    public WorldCoordinateConverter getWCS() {
        return _wcs;
    }

    /**
     * Set the object used to convert between image and world coordinates.
     */
    public void setWCS(WorldCoordinateConverter wcs) {
        _wcs = wcs;
    }

    /** Set to true (default) to automatically center the image, if it is smaller than the window. */
    public void setAutoCenterImage(boolean b) {
        _autoCenterImage = b;
    }

    /** Return true if the image is automatically centered when it is smaller than the window. */
    public boolean isAutoCenterImage() {
        return _autoCenterImage;
    }

    /**
     * If a new image was just loaded, center the image in it's window,
     * otherwise only center it if it is smaller than the display window.
     */
    private void _centerImage(PlanarImage im) {
        if (!_autoCenterImage)
            return;

        float scale = _scale;
        if (_prescaled)
            scale = 1.0F;
        int cw = getWidth(), ch = getHeight();
        double dw = im.getWidth() * scale, dh = im.getHeight() * scale;
        double x = _origin.getX(), y = _origin.getY();
        boolean center = false;

        // not a new image, only center if image is smaller than window
        if (dw < cw || _centered) {
            x = (dw - cw) / 2.0;
            center = true;
        }

        if (dh < ch || _centered) {
            y = (dh - ch) / 2.0;
            center = true;
        }
        if (center) {
            //System.out.println("XXX " + getName() + ": centerImage");
            _origin.setLocation(x, y);
            _centered = true;
        }
    }

    private int _XtoTileX(int x) {
        return (int) Math.floor((double) (x - _tileGridXOffset) / _tileWidth);
    }

    private int _YtoTileY(int y) {
        return (int) Math.floor((double) (y - _tileGridYOffset) / _tileHeight);
    }

    private int _TileXtoX(int tx) {
        return tx * _tileWidth + _tileGridXOffset;
    }

    private int _TileYtoY(int ty) {
        return ty * _tileHeight + _tileGridYOffset;
    }

    // speed up math min and max by inlining
    private int _maxInt(int a, int b) {
        return a > b ? a : b;
    }

    private int _minInt(int a, int b) {
        return (a <= b) ? a : b;
    }

    /**
     * Paint the image onto a Graphics object.  The painting is
     * performed tile-by-tile, and includes a grey region covering the
     * unused portion of image tiles as well as the general
     * background.  At this point the image must be byte data.
     */
    public synchronized void paintComponent(Graphics g) {
        Graphics2D g2D = (Graphics2D) g;

        int componentWidth = getWidth();
        int componentHeight = getHeight();

        g2D.setComposite(AlphaComposite.Src);
        g2D.setColor(getBackground());
        g2D.fillRect(0, 0, componentWidth, componentHeight);

        // if _displayImage is null, it's just a component
        if (_displayImage == null || _sampleModel == null)
            return;

        // Get the clipping rectangle and translate it into image coordinates.
        Rectangle clipBounds = g2D.getClipBounds();
        Rectangle2D region = _displayImage.getBounds().createIntersection(clipBounds);
        g2D.setClip(region);

        // Determine the extent of the clipping region in tile coordinates.
        int txmin, txmax, tymin, tymax;
        int ti, tj;
        int x = (int) region.getX();
        int y = (int) region.getY();
        int w = (int) region.getWidth();
        int h = (int) region.getHeight();

        txmin = _XtoTileX(x);
        txmin = _maxInt(txmin, _minTileX);
        txmin = _minInt(txmin, _maxTileX);

        txmax = _XtoTileX(x + w - 1);
        txmax = _maxInt(txmax, _minTileX);
        txmax = _minInt(txmax, _maxTileX);

        tymin = _YtoTileY(y);
        tymin = _maxInt(tymin, _minTileY);
        tymin = _minInt(tymin, _maxTileY);

        tymax = _YtoTileY(y + h - 1);
        tymax = _maxInt(tymax, _minTileY);
        tymax = _minInt(tymax, _maxTileY);
        Insets insets = getInsets();

        // Loop over tiles within the clipping region
        for (tj = tymin; tj <= tymax; tj++) {
            for (ti = txmin; ti <= txmax; ti++) {

                int tx = _TileXtoX(ti);
                int ty = _TileYtoY(tj);

                Raster tile = _displayImage.getTile(ti, tj);
                if (tile == null)
                    return;
                DataBuffer dataBuffer = tile.getDataBuffer();
                if (dataBuffer == null)
                    return;

                WritableRaster wr = Raster.createWritableRaster(_sampleModel, dataBuffer, null);
                BufferedImage bi = new BufferedImage(_colorModel, wr, _colorModel.isAlphaPremultiplied(), null);

                // correctly handles band offsets
                g2D.drawRenderedImage(bi, AffineTransform.getTranslateInstance(tx + insets.left, ty + insets.top));
            }
        }
        g2D.setClip(clipBounds); // restore previous clip bounds

        // derived classes may want to insert some graphics here
        _notifyGraphicsHandlers(g2D);
    }

    /**
     * Register as an image graphics handler.
     */
    public void addImageGraphicsHandler(ImageGraphicsHandler igh) {
        _listenerList.add(ImageGraphicsHandler.class, igh);
    }

    /**
     * Unregister as an image graphics handler.
     */
    public void removeImageGraphicsHandler(ImageGraphicsHandler igh) {
        _listenerList.remove(ImageGraphicsHandler.class, igh);
    }

    /**
     * Notify any ImageGraphicsHandlers
     */
    private void _notifyGraphicsHandlers(Graphics2D g) {
        Object[] listeners = _listenerList.getListenerList();
        for (int i = listeners.length - 2; i >= 0; i -= 2) {
            if (listeners[i] == ImageGraphicsHandler.class) {
                ((ImageGraphicsHandler) listeners[i + 1]).drawImageGraphics(this, g);
            }
        }
    }

    /**
     * Set the origin of the image to display in canvas coordinates.
     */
    public void setOrigin(Point2D.Double origin) {
        _origin = origin;
        _centered = false;
    }

    /**
     * Return the origin of the displayed image in canvas coordinates.
     */
    public Point2D.Double getOrigin() {
        return new Point2D.Double(_origin.x, _origin.y);
    }

    /**
     * Return the image canvas component.
     */
    public JComponent getCanvas() {
        return this;
    }

    /**
     * Set the scale (zoom factor) for the image.
     * This also adjusts the origin so that the center of the image remains about the same.
     */
    public void setScale(float scale) {
        _coordinateConverter.canvasToUserCoords(_origin, false);
        _scale = _actualScale = scale;
        _coordinateConverter.userToCanvasCoords(_origin, false);
    }

    /**
     * Set the scale (zoom factor) for the image, but lie about it later when asked.
     * This method is needed when working with images that have been prescaled by the
     * image reader, so that the correct coordinates can still be displayed.
     *
     * @param actualScale this is the scale value that is actually applied to the image data
     * @param apparentScale this is the scale value that will be reported by getScale()
     */
    public void setScale(float actualScale, float apparentScale) {
        _coordinateConverter.canvasToUserCoords(_origin, false);
        _scale = apparentScale;
        _actualScale = actualScale;
        _coordinateConverter.userToCanvasCoords(_origin, false);
    }

    /**
     * Return the current scale (zoom factor) for the image.
     */
    public float getScale() {
        return _scale;
    }

    /**
     * Set the interpolation object used to scale the image (a subclass
     * of Interpolation, such as InterpolationNearest (default), or
     * InterpolationBilinear (better, but slower)).
     */
    public void setInterpolation(Interpolation i) {
        _interpolation = i;
    }

    /** Return the interpolation object used to scale the image */
    public Interpolation getInterpolation() {
        return _interpolation;
    }

    /**
     * Return the value of the pixel in the given band at the given user coordinates
     */
    public float getPixelValue(Point2D.Double p, int band) {
        PlanarImage im = _imageProcessor.getRescaledSourceImage();
        if (im != null) {
            int ix = (int) p.getX(), iy = (int) p.getY();
            if (ix < 0 || ix > im.getWidth() || iy < 0 || iy > im.getHeight())
                return 0.0F;
            int x = _XtoTileX(ix);
            int y = _YtoTileY(iy);
            if (x < 0 || y < 0)
                return 0.0F;
            Raster tile = im.getTile(x, y);
            return tile.getSampleFloat(ix, iy, band);
        }
        return 0;
    }

    /**
     * Set to true if the image being displayed has been prescaled (such as
     * for a pan window or thumbnail image).
     * If true, the scale value will only be used to calculate coordinate
     * transformations, but the image will not actually be scaled.
     */
    public void setPrescaled(boolean b) {
        _prescaled = b;
    }

    /** Return true if the image has been prescaled */
    public boolean isPrescaled() {
        return _prescaled;
    }

    /** Set the optional rendering hints for the image scale operation */
    public void setScaleHints(RenderingHints hints) {
        _scaleHints = hints;
    }

    /** Return the optional rendering hints used for the image scale operation */
    public RenderingHints getScaleHints() {
        return _scaleHints;
    }

    /**
     * Perform a translate/scale operation on the given image using the current
     * settings and return the resulting image. The input image is assumed to be
     * at mag 1.
     */
    private PlanarImage _scale(PlanarImage im) {
        if (im != null) {
            float tx = (float) _origin.getX();
            float ty = (float) _origin.getY();

            if (_actualScale == 1 || _prescaled) {
                if (tx != 0 || ty != 0) {
                    im = ImageOps.translate(im, -tx, -ty, _interpolation);
                }
            } else {
                im = ImageOps.scale(im, _actualScale, _actualScale, -tx, -ty, _interpolation, _scaleHints);
            }
        }
        return im;
    }

    /**
     * Set the scaling factor so that the image will fit in a window of the
     * given size.
     * <p>
     * Note that only integer scaling factors are used, for example
     * 2, 1, 1/2, 1/3, etc., for performance reasons.
     */
    protected void scaleToFit(int width, int height) {
        float w = getImageWidth(), h = getImageHeight();
        if (w != 0. && h != 0.) {
            float scale = Math.min(width / w, height / h);
            if (scale >= 1.0F)
                scale = (float) Math.round(scale);
            else
                scale = 1.0F / (float) Math.round(1.0F / scale);
            setScale(scale);
        }
    }

    /**
     * Set the scaling factor so that the image will fit in the current window.
     * <p>
     * Note that only integer scaling factors are used, for example
     * 2, 1, 1/2, 1/3, etc., for performance reasons.
     */
    public void scaleToFit() {
        int cw = getWidth(), ch = getHeight();
        if (cw != 0) {
            scaleToFit(cw, ch);
        }
    }

    /**
     * Return a rectangle describing the visible area of the image
     * (in user coordinates).
     */
    public Rectangle2D.Double getVisibleArea() {
        Rectangle2D.Double r = new Rectangle2D.Double();
        Point2D.Double p = new Point2D.Double(0, 0);
        _coordinateConverter.screenToUserCoords(p, false);

        Point2D.Double size = new Point2D.Double(getWidth(), getHeight());
        _coordinateConverter.screenToUserCoords(size, true);

        r.setRect(p.getX(), p.getY(), size.getX(), size.getY());
        return r;
    }

    /** Return true if this widget has been initialized and is displaying an image. */
    public boolean isInitialized() {
        return _displayImage != null;
    }

    /**
     * Set to true if scrolling and other operations should update the image immediately,
     * otherwise only on button release.
     */
    public void setImmediateMode(boolean b) {
        _immediateMode = b;
    }

    /** Return true if immediate mode is turned on. */
    public boolean isImmediateMode() {
        return _immediateMode;
    }

    /**
     * test main: usage: java ImageDisplay <filename>.
     */
    public static void main(String[] args) {
        JFrame frame = new JFrame("ImageDisplay");
        ImageDisplay display = new ImageDisplay();
        if (args.length > 0) {
            try {
                display.setImage(JAI.create("fileload", args[0]));
            } catch (Exception e) {
                System.out.println("error: " + e.toString());
                System.exit(1);
            }
        }
        frame.getContentPane().add(display, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
        frame.addWindowListener(new BasicWindowMonitor());
    }
}


text:
'use strict';

const RelayProfiler = require('RelayProfiler');
const RelayQueryRequest = require('RelayQueryRequest');

const invariant = require('invariant');
const resolveImmediate = require('resolveImmediate');
const throwFailedPromise = require('throwFailedPromise');
const warning = require('warning');

import type RelayMutationRequest from 'RelayMutationRequest';
import type RelayQuery from 'RelayQuery';
import type {ChangeSubscription, NetworkLayer} from 'RelayTypes';

type Subscriber = {
  queryCallback: ?QueryCallback,
  mutationCallback: ?MutationCallback,
};

export type MutationCallback = (request: RelayMutationRequest) => void;
export type QueryCallback = (request: RelayQueryRequest) => void;

/**
 * @internal
 *
 * `RelayNetworkLayer` provides a method to inject custom network behavior.
 */
class RelayNetworkLayer {
  _defaultImplementation: ?NetworkLayer;
  _implementation: ?NetworkLayer;
  _queue: ?Array<RelayQueryRequest>;
  _subscribers: Array<Subscriber>;

  constructor() {
    this._implementation = null;
    this._queue = null;
    this._subscribers = [];
  }

  /**
   * @internal
   */
  injectDefaultImplementation(implementation: ?NetworkLayer): void {
    if (this._defaultImplementation) {
      warning(
        false,
        'RelayNetworkLayer: Call received to injectDefaultImplementation(), ' +
        'but a default layer was already injected.'
      );
    }
    this._defaultImplementation = implementation;
  }

  injectImplementation(implementation: ?NetworkLayer): void {
    if (this._implementation) {
      warning(
        false,
        'RelayNetworkLayer: Call received to injectImplementation(), but ' +
        'a layer was already injected.'
      );
    }
    this._implementation = implementation;
  }

  addNetworkSubscriber(
    queryCallback?: ?QueryCallback,
    mutationCallback?: ?MutationCallback
  ) : ChangeSubscription {
    const index = this._subscribers.length;
    this._subscribers.push({queryCallback, mutationCallback});
    return {
      remove: () => {
        delete this._subscribers[index];
      },
    };
  }

  sendMutation(mutationRequest: RelayMutationRequest): void {
    const implementation = this._getImplementation();
    this._subscribers.forEach(({mutationCallback}) => {
      if (mutationCallback) {
        mutationCallback(mutationRequest);
      }
    });
    const maybePromise = implementation.sendMutation(mutationRequest);
    if (maybePromise) {
      throwFailedPromise(Promise.resolve(maybePromise));
    }
  }

  sendQueries(queryRequests: Array<RelayQueryRequest>): void {
    const implementation = this._getImplementation();
    this._subscribers.forEach(({queryCallback}) => {
      if (queryCallback) {
        queryRequests.forEach(request => {
          // $FlowIssue #10907496 queryCallback was checked above
          queryCallback(request);
        });
      }
    });
    const maybePromise = implementation.sendQueries(queryRequests);
    if (maybePromise) {
      throwFailedPromise(Promise.resolve(maybePromise));
    }
  }

  supports(...options: Array<string>): boolean {
    const implementation = this._getImplementation();
    return implementation.supports(...options);
  }

  _getImplementation(): NetworkLayer {
    const implementation = this._implementation || this._defaultImplementation;
    invariant(
      implementation,
      'RelayNetworkLayer: Use `RelayEnvironment.injectNetworkLayer` to ' +
      'configure a network layer.'
    );
    return implementation;
  }

  /**
   * Schedules the supplied `query` to be sent to the server.
   *
   * This is a low-level transport API; application code should use higher-level
   * interfaces exposed by RelayContainer for retrieving data transparently via
   * queries defined on components.
   */
  fetchRelayQuery(query: RelayQuery.Root): Promise<any> {
    const currentQueue = this._queue || [];
    if (!this._queue) {
      this._queue = currentQueue;
      resolveImmediate(() => {
        this._queue = null;
        profileQueue(currentQueue);
        this.sendQueries(currentQueue);
      });
    }
    const request = new RelayQueryRequest(query);
    currentQueue.push(request);
    return request.getPromise();
  }
}

/**
 * Profiles time from request to receiving the first server response.
 */
function profileQueue(currentQueue: Array<RelayQueryRequest>): void {
  // TODO #8783781: remove aggregate `fetchRelayQuery` profiler
  let firstResultProfiler = RelayProfiler.profile('fetchRelayQuery');
  currentQueue.forEach(query => {
    const profiler = RelayProfiler.profile('fetchRelayQuery.query');
    const onSettle = () => {
      profiler.stop();
      if (firstResultProfiler) {
        firstResultProfiler.stop();
        firstResultProfiler = null;
      }
    };
    query.done(onSettle, onSettle);
  });
}

RelayProfiler.instrumentMethods(RelayNetworkLayer.prototype, {
  sendMutation: 'RelayNetworkLayer.sendMutation',
  sendQueries: 'RelayNetworkLayer.sendQueries',
});

module.exports = RelayNetworkLayer;


text:
package com.asakusafw.bridge.hadoop.directio;

import static com.asakusafw.bridge.hadoop.directio.Util.*;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.util.ReflectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.asakusafw.bridge.hadoop.ModelInputRecordReader;
import com.asakusafw.bridge.hadoop.combine.CombinedInputSplit;
import com.asakusafw.bridge.hadoop.combine.CombinedRecordReader;
import com.asakusafw.bridge.hadoop.combine.DefaultSplitCombiner;
import com.asakusafw.bridge.hadoop.combine.SplitCombiner;
import com.asakusafw.bridge.stage.StageInfo;
import com.asakusafw.runtime.directio.Counter;
import com.asakusafw.runtime.directio.DataDefinition;
import com.asakusafw.runtime.directio.DataFormat;
import com.asakusafw.runtime.directio.DirectDataSource;
import com.asakusafw.runtime.directio.DirectDataSourceConstants;
import com.asakusafw.runtime.directio.DirectDataSourceRepository;
import com.asakusafw.runtime.directio.DirectInputFragment;
import com.asakusafw.runtime.directio.FilePattern;
import com.asakusafw.runtime.directio.ResourcePattern;
import com.asakusafw.runtime.directio.SimpleDataDefinition;
import com.asakusafw.runtime.io.ModelInput;
import com.asakusafw.runtime.stage.input.BridgeInputFormat.NullInputSplit;
import com.asakusafw.runtime.stage.input.BridgeInputFormat.NullRecordReader;

/**
 * An Hadoop {@code InputFormat} for Direct I/O file inputs.
 * This requires {@link StageInfo} object onto Hadoop configuration as {@link StageInfo#KEY_NAME}.
 * @since 0.1.0
 * @version 0.4.2
 */
public class DirectFileInputFormat extends InputFormat<NullWritable, Object> {

    static final Logger LOG = LoggerFactory.getLogger(DirectFileInputFormat.class);

    static final String KEY_PREFIX = "com.asakusafw.bridge.directio.input."; //$NON-NLS-1$

    /**
     * The attribute key name of base path.
     */
    public static final String KEY_BASE_PATH = KEY_PREFIX + "basePath"; //$NON-NLS-1$

    /**
     * The attribute key name of resource path/pattern.
     */
    public static final String KEY_RESOURCE_PATH = KEY_PREFIX + "resourcePath"; //$NON-NLS-1$

    /**
     * The attribute key name of data class.
     */
    public static final String KEY_DATA_CLASS = KEY_PREFIX + "dataClass"; //$NON-NLS-1$

    /**
     * The attribute key name of format class.
     */
    public static final String KEY_FORMAT_CLASS = KEY_PREFIX + "formatClass"; //$NON-NLS-1$

    /**
     * The attribute key name of filter class.
     */
    public static final String KEY_FILTER_CLASS = KEY_PREFIX + "filterClass"; //$NON-NLS-1$

    /**
     * The attribute key name of whether the target input is optional.
     */
    public static final String KEY_OPTIONAL = KEY_PREFIX + "optional"; //$NON-NLS-1$

    /**
     * The attribute key name of max number of combined input splits.
     * @since 0.4.2
     */
    public static final String KEY_COMBINE = KEY_PREFIX + "combine"; //$NON-NLS-1$

    @Override
    public List<InputSplit> getSplits(JobContext context) throws IOException, InterruptedException {
        Configuration conf = context.getConfiguration();
        StageInfo stage = getStageInfo(conf);
        DirectFileInputInfo<?> info = extractInfo(context);
        DirectDataSourceRepository repository = getDataSourceRepository(context);
        String containerPath = repository.getContainerPath(info.basePath);
        List<DirectInputFragment> fragments = findFragments(info, repository);
        List<InputSplit> results = new ArrayList<>();
        for (DirectInputFragment fragment : fragments) {
            DirectFileInputSplit split = new DirectFileInputSplit(
                    containerPath, info.definition, fragment,
                    stage.getBatchArguments());
            ReflectionUtils.setConf(split, conf);
            results.add(split);
        }
        if (results.isEmpty()) {
            results.add(new NullInputSplit());
        }
        int splits = context.getConfiguration().getInt(KEY_COMBINE, -1);
        if (splits >= 1 && splits < results.size()) {
            SplitCombiner combiner = new DefaultSplitCombiner();
            return combiner.combine(context, splits, results);
        } else {
            return results;
        }
    }

    private static List<DirectInputFragment> findFragments(
            DirectFileInputInfo<?> info,
            DirectDataSourceRepository repository) throws IOException, InterruptedException {
        String containerPath = repository.getContainerPath(info.basePath);
        String componentPath = repository.getComponentPath(info.basePath);
        DirectDataSource ds = repository.getRelatedDataSource(containerPath);
        List<DirectInputFragment> fragments =
                ds.findInputFragments(info.definition, componentPath, info.resourcePattern);
        if (fragments.isEmpty()) {
            if (info.optional) {
                LOG.info(MessageFormat.format(
                        "skipped optional input (datasource={0}, path=\"{1}\", type={2})",
                        repository.getRelatedId(info.basePath),
                        ds.path(componentPath, info.resourcePattern),
                        info.definition.getDataClass().getName()));
            } else {
                throw new IOException(MessageFormat.format(
                        "input not found (datasource={0}, path=\"{1}\", type={2})",
                        repository.getRelatedId(info.basePath),
                        ds.path(componentPath, info.resourcePattern),
                        info.definition.getDataClass().getName()));
            }
        }
        return fragments;
    }

    private static DirectFileInputInfo<?> extractInfo(JobContext context) {
        Configuration conf = context.getConfiguration();
        String basePath = extract(conf, KEY_BASE_PATH, true, true);
        String resourcePath = extract(conf, KEY_RESOURCE_PATH, true, true);
        Class<?> dataClass = extractClass(conf, KEY_DATA_CLASS, true);
        Class<?> formatClass = extractClass(conf, KEY_FORMAT_CLASS, true);
        Class<?> filterClass = extractClass(conf, KEY_FILTER_CLASS, false);
        String optionalString = extract(conf, KEY_OPTIONAL, false, false);
        if (optionalString == null) {
            optionalString = DirectDataSourceConstants.DEFAULT_OPTIONAL;
        }

        ResourcePattern resourcePattern = FilePattern.compile(resourcePath);
        DataDefinition<?> definition = SimpleDataDefinition.newInstance(
                dataClass,
                (DataFormat<?>) ReflectionUtils.newInstance(formatClass, conf),
                createFilter(filterClass, conf));
        boolean optional = Boolean.parseBoolean(optionalString);

        return new DirectFileInputInfo<>(basePath, resourcePattern, definition, optional);
    }

    private static String extract(Configuration conf, String key, boolean mandatory, boolean resolve) {
        String value = conf.get(key);
        if (value == null) {
            if (mandatory) {
                throw new IllegalStateException(MessageFormat.format(
                        "missing mandatory configuration: {0}",
                        key));
            }
            return null;
        }
        if (resolve) {
            StageInfo info = getStageInfo(conf);
            try {
                value = info.resolveUserVariables(value);
            } catch (IllegalArgumentException e) {
                throw new IllegalStateException(MessageFormat.format(
                        "failed to resolve configuration: {0}={1}",
                        key,
                        value), e);
            }
        }
        return value;
    }

    @SuppressWarnings("unchecked")
    private static <T> Class<T> extractClass(Configuration conf, String key, boolean mandatory) {
        String value = extract(conf, key, mandatory, false);
        if (value == null) {
            return null;
        }
        try {
            return (Class<T>) conf.getClassByName(value);
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException(MessageFormat.format(
                    "failed to resolve a class: {0}={1}",
                    key,
                    value), e);
        }
    }

    @Override
    public RecordReader<NullWritable, Object> createRecordReader(
            InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
        if (split instanceof DirectFileInputSplit) {
            DirectFileInputSplit info = (DirectFileInputSplit) split;
            DataDefinition<?> definition = info.getDataDefinition();
            return createRecordReader(definition, info, context);
        } else if (split instanceof CombinedInputSplit) {
            return new CombinedRecordReader<>(this);
        } else if (split instanceof NullInputSplit) {
            return createNullRecordReader(context);
        } else {
            throw new IOException(MessageFormat.format(
                    "unknown input split: {0}",
                    split));
        }
    }

    private static <T> RecordReader<NullWritable, Object> createRecordReader(
            DataDefinition<T> definition,
            DirectFileInputSplit split,
            TaskAttemptContext context) throws IOException, InterruptedException {
        assert definition != null;
        assert split != null;
        assert context != null;
        Configuration conf = context.getConfiguration();
        T buffer = ReflectionUtils.newInstance(definition.getDataClass(), conf);
        Counter counter = new Counter();
        DirectInputFragment fragment = split.getInputFragment();
        ModelInput<T> input = createInput(context, split.getContainerPath(), definition, counter, fragment);
        return new ModelInputRecordReader<>(input, buffer, counter, fragment.getSize());
    }

    private static <T> ModelInput<T> createInput(
            TaskAttemptContext context,
            String containerPath,
            DataDefinition<T> definition,
            Counter counter,
            DirectInputFragment fragment) throws IOException, InterruptedException {
        assert context != null;
        assert containerPath != null;
        assert definition != null;
        assert counter != null;
        assert fragment != null;
        DirectDataSourceRepository repo = getDataSourceRepository(context);
        DirectDataSource ds = repo.getRelatedDataSource(containerPath);
        return ds.openInput(definition, fragment, counter);
    }

    private static RecordReader<NullWritable, Object> createNullRecordReader(TaskAttemptContext context) {
        assert context != null;
        return new NullRecordReader<>();
    }

    private static class DirectFileInputInfo<T> {

        final String basePath;

        final ResourcePattern resourcePattern;

        final DataDefinition<T> definition;

        final boolean optional;

        DirectFileInputInfo(
                String basePath, ResourcePattern resourcePattern,
                DataDefinition<T> definition, boolean optional) {
            this.basePath = basePath;
            this.resourcePattern = resourcePattern;
            this.definition = definition;
            this.optional = optional;
        }
    }
}


text:
from tacker.sol_refactored.objects import base
from tacker.sol_refactored.objects import fields

# NFV-SOL 005
# - v3.3.1 9.5.3.3 (API version: 2.1.0)
@base.TackerObjectRegistry.register
class VnfPackageArtifactInfoV2(base.TackerObject, base.TackerObjectDictCompat):

    # Version 1.0: Initial version
    VERSION = '1.0'

    fields = {
        'artifactPath': fields.StringField(nullable=True),
        'artifactURI': fields.UriField(nullable=True),
        'checksum': fields.ChecksumField(nullable=False),
        'isEncrypted': fields.BooleanField(nullable=False),
        'nonManoArtifactSetId': fields.StringField(nullable=True),
        'artifactClassification': fields.EnumField(
            valid_values=[
                'HISTORY',
                'TESTING',
                'LICENSE',
            ],
            nullable=True,
        ),
        'metadata': fields.KeyValuePairsField(nullable=True),
    }


text:
some iterator functions,
  * each
  * map
  * filter
  * times
  * map
  * find
  * mapKeys
  * mapToArray

all work objects and on arrays


text:
@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, StockGraphDelegate>

- (IBAction)stockBtn:(id)sender;
@property (strong, nonatomic) IBOutlet UITextField *symInput;
@property (strong, nonatomic) IBOutlet UITableView *stockTable;

@end


text:
<!DOCTYPE html>

<title>500 Page | Pages</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link type="text/css" href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,800italic,400,700,800">
    <link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Oswald:400,700,300">
    <link type="text/css" rel="stylesheet" href="vendors/jquery-ui-1.10.3.custom/css/ui-lightness/jquery-ui-1.10.3.custom.css">
    <link type="text/css" rel="stylesheet" href="vendors/font-awesome/css/font-awesome.min.css">
    <link type="text/css" rel="stylesheet" href="vendors/bootstrap/css/bootstrap.min.css">

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

    <link type="text/css" rel="stylesheet" href="css/style.css">
    <link type="text/css" rel="stylesheet" href="css/style-mango.css" id="theme-style">
    <link type="text/css" rel="stylesheet" href="css/style-responsive.css">
    <link type="text/css" rel="stylesheet" href="css/vendors.css">
    <link type="text/css" rel="stylesheet" href="css/themes/white-pink.css" id="color-style">
    <link rel="shortcut icon" href="images/favicon.ico">

500!

Internal Server Error

The website cannot display the page.

Return home or please come back in a while.


text:
<?php

class Me_StatusTest extends TestCase
{

    private $model;
    private static $id;

    public function setUp()
    {
        parent::setUp();
        $this->model = TeamWorkPm\Factory::build('me/status');
    }

    /**
     * @dataProvider provider
     * @test
     */
    public function insert($data)
    {
        try {
            self::$id = $this->model->save($data);
            $this->assertGreaterThan(0, self::$id);
        } catch(\TeamWorkPm\Exception $e) {
            $this->fail($e->getMessage());
        }
    }

    /**
     * @test
     */
    public function get()
    {
        try {
            $status = $this->model->get();
            $this->assertEquals($status->id, self::$id);
        } catch(\TeamWorkPm\Exception $e) {
            $this->fail($e->getMessage());
        }
    }

    /**
     * @dataProvider provider
     * @test
     */
    public function update($data)
    {
        try {
            $data['id'] = null;
            $this->model->save($data);
            $this->fail('An expected exception has not been raised.');
        } catch (\TeamWorkPm\Exception $e) {
            $this->assertEquals('Required field id', $e->getMessage());
        }
        try {
            $data['id']     = self::$id;
            $data['status'] = rand_string($data['status']);
            $this->assertTrue($this->model->save($data));
            $status = $this->model->get();
            $this->assertEquals($data['status'], $status->status);
        } catch(\TeamWorkPm\Exception $e) {
            $this->fail($e->getMessage());
        }
    }

    public function provider()
    {
        return [
            [
                [
                    'status' => 'Test me status',
                    'notify' => false
                ]
            ]
        ];
    }
}