text:
#import "ZXAlignmentPattern.h"

@interface ZXAlignmentPattern ()

@property (nonatomic, assign) float estimatedModuleSize;

@end

@implementation ZXAlignmentPattern

@synthesize estimatedModuleSize;

- (id)initWithPosX:(float)posX posY:(float)posY estimatedModuleSize:(float)anEstimatedModuleSize {
  if (self = [super initWithX:posX y:posY]) {
    self.estimatedModuleSize = anEstimatedModuleSize;
  }

  return self;
}

/**
 * Determines if this alignment pattern "about equals" an alignment pattern at the stated
 * position and size -- meaning, it is at nearly the same center with nearly the same size.
 */
- (BOOL)aboutEquals:(float)moduleSize i:(float)i j:(float)j {
  if (fabsf(i - self.y) <= moduleSize && fabsf(j - self.x) <= moduleSize) {
    float moduleSizeDiff = fabsf(moduleSize - self.estimatedModuleSize);
    return moduleSizeDiff <= 1.0f || moduleSizeDiff <= estimatedModuleSize;
  }

  return NO;
}

/**
 * Combines this object's current estimate of a finder pattern position and module size
 * with a new estimate. It returns a new FinderPattern containing an average of the two.
 */
- (ZXAlignmentPattern *)combineEstimateI:(float)i j:(float)j newModuleSize:(float)newModuleSize {
  float combinedX = (self.x + j) / 2.0f;
  float combinedY = (self.y + i) / 2.0f;
  float combinedModuleSize = (self.estimatedModuleSize + newModuleSize) / 2.0f;
  return [[[ZXAlignmentPattern alloc] initWithPosX:combinedX posY:combinedY estimatedModuleSize:combinedModuleSize] autorelease];
}

@end

redpajama_set_name: RedPajamaGithub


text:
"""Compatibility module defining operations on duck numpy-arrays.

Currently, this means Dask or NumPy arrays. None of these functions should
accept or return xarray objects.
"""
import contextlib
import inspect
import warnings
from functools import partial

import numpy as np
import pandas as pd

from . import dask_array_ops, dtypes, npcompat, nputils
from .nputils import nanfirst, nanlast
from .pycompat import dask_array_type

try:
    import dask.array as dask_array
    from . import dask_array_compat
except ImportError:
    dask_array = None  # type: ignore
    dask_array_compat = None  # type: ignore

def _dask_or_eager_func(name, eager_module=np, dask_module=dask_array,
                        list_of_args=False, array_args=slice(1),
                        requires_dask=None):
    """Create a function that dispatches to dask for dask array inputs."""
    if dask_module is not None:
        def f(*args, **kwargs):
            if list_of_args:
                dispatch_args = args[0]
            else:
                dispatch_args = args[array_args]
            if any(isinstance(a, dask_array.Array) for a in dispatch_args):
                try:
                    wrapped = getattr(dask_module, name)
                except AttributeError as e:
                    raise AttributeError("%s: requires dask >=%s" %
                                         (e, requires_dask))
            else:
                wrapped = getattr(eager_module, name)
            return wrapped(*args, **kwargs)
    else:
        def f(*args, **kwargs):
            return getattr(eager_module, name)(*args, **kwargs)
    return f

def fail_on_dask_array_input(values, msg=None, func_name=None):
    if isinstance(values, dask_array_type):
        if msg is None:
            msg = '%r is not yet a valid method on dask arrays'
        if func_name is None:
            func_name = inspect.stack()[1][3]
        raise NotImplementedError(msg % func_name)

around = _dask_or_eager_func('around')
isclose = _dask_or_eager_func('isclose')
notnull = _dask_or_eager_func('notnull', eager_module=pd)
_isnull = _dask_or_eager_func('isnull', eager_module=pd)

def isnull(data):
    # GH837, GH861
    # isnull fcn from pandas will throw TypeError when run on numpy structured
    # array therefore for dims that are np structured arrays we assume all
    # data is present
    try:
        return _isnull(data)
    except TypeError:
        return np.zeros(data.shape, dtype=bool)

transpose = _dask_or_eager_func('transpose')
_where = _dask_or_eager_func('where', array_args=slice(3))
isin = _dask_or_eager_func('isin', eager_module=npcompat,
                           dask_module=dask_array_compat, array_args=slice(2))
take = _dask_or_eager_func('take')
broadcast_to = _dask_or_eager_func('broadcast_to')

_concatenate = _dask_or_eager_func('concatenate', list_of_args=True)
_stack = _dask_or_eager_func('stack', list_of_args=True)

array_all = _dask_or_eager_func('all')
array_any = _dask_or_eager_func('any')

tensordot = _dask_or_eager_func('tensordot', array_args=slice(2))
einsum = _dask_or_eager_func('einsum', array_args=slice(1, None),
                             requires_dask='0.17.3')

def gradient(x, coord, axis, edge_order):
    if isinstance(x, dask_array_type):
        return dask_array_compat.gradient(
            x, coord, axis=axis, edge_order=edge_order)
    return npcompat.gradient(x, coord, axis=axis, edge_order=edge_order)

def trapz(y, x, axis):
    if axis < 0:
        axis = y.ndim + axis
    x_sl1 = (slice(1, None), ) + (None, ) * (y.ndim - axis - 1)
    x_sl2 = (slice(None, -1), ) + (None, ) * (y.ndim - axis - 1)
    slice1 = (slice(None),) * axis + (slice(1, None), )
    slice2 = (slice(None),) * axis + (slice(None, -1), )
    dx = (x[x_sl1] - x[x_sl2])
    integrand = dx * 0.5 * (y[tuple(slice1)] + y[tuple(slice2)])
    return sum(integrand, axis=axis, skipna=False)

masked_invalid = _dask_or_eager_func(
    'masked_invalid', eager_module=np.ma,
    dask_module=getattr(dask_array, 'ma', None))

def asarray(data):
    return data if isinstance(data, dask_array_type) else np.asarray(data)

def as_shared_dtype(scalars_or_arrays):
    """Cast a arrays to a shared dtype using xarray's type promotion rules."""
    arrays = [asarray(x) for x in scalars_or_arrays]
    # Pass arrays directly instead of dtypes to result_type so scalars
    # get handled properly.
    # Note that result_type() safely gets the dtype from dask arrays without
    # evaluating them.
    out_type = dtypes.result_type(*arrays)
    return [x.astype(out_type, copy=False) for x in arrays]

def as_like_arrays(*data):
    if all(isinstance(d, dask_array_type) for d in data):
        return data
    else:
        return tuple(np.asarray(d) for d in data)

def allclose_or_equiv(arr1, arr2, rtol=1e-5, atol=1e-8):
    """Like np.allclose, but also allows values to be NaN in both arrays
    """
    arr1, arr2 = as_like_arrays(arr1, arr2)
    if arr1.shape != arr2.shape:
        return False
    return bool(
        isclose(arr1, arr2, rtol=rtol, atol=atol, equal_nan=True).all())

def array_equiv(arr1, arr2):
    """Like np.array_equal, but also allows values to be NaN in both arrays
    """
    arr1, arr2 = as_like_arrays(arr1, arr2)
    if arr1.shape != arr2.shape:
        return False

    with warnings.catch_warnings():
        warnings.filterwarnings('ignore', "In the future, 'NAT == x'")

        flag_array = (arr1 == arr2)
        flag_array |= (isnull(arr1) & isnull(arr2))

        return bool(flag_array.all())

def array_notnull_equiv(arr1, arr2):
    """Like np.array_equal, but also allows values to be NaN in either or both
    arrays
    """
    arr1, arr2 = as_like_arrays(arr1, arr2)
    if arr1.shape != arr2.shape:
        return False

    with warnings.catch_warnings():
        warnings.filterwarnings('ignore', "In the future, 'NAT == x'")

        flag_array = (arr1 == arr2)
        flag_array |= isnull(arr1)
        flag_array |= isnull(arr2)

        return bool(flag_array.all())

def count(data, axis=None):
    """Count the number of non-NA in this array along the given axis or axes
    """
    return np.sum(np.logical_not(isnull(data)), axis=axis)

def where(condition, x, y):
    """Three argument where() with better dtype promotion rules."""
    return _where(condition, *as_shared_dtype([x, y]))

def where_method(data, cond, other=dtypes.NA):
    if other is dtypes.NA:
        other = dtypes.get_fill_value(data.dtype)
    return where(cond, data, other)

def fillna(data, other):
    return where(isnull(data), other, data)

def concatenate(arrays, axis=0):
    """concatenate() with better dtype promotion rules."""
    return _concatenate(as_shared_dtype(arrays), axis=axis)

def stack(arrays, axis=0):
    """stack() with better dtype promotion rules."""
    return _stack(as_shared_dtype(arrays), axis=axis)

@contextlib.contextmanager
def _ignore_warnings_if(condition):
    if condition:
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            yield
    else:
        yield

def _create_nan_agg_method(name, coerce_strings=False):
    from . import nanops

    def f(values, axis=None, skipna=None, **kwargs):
        if kwargs.pop('out', None) is not None:
            raise TypeError('`out` is not valid for {}'.format(name))

        values = asarray(values)

        if coerce_strings and values.dtype.kind in 'SU':
            values = values.astype(object)

        func = None
        if skipna or (skipna is None and values.dtype.kind in 'cfO'):
            nanname = 'nan' + name
            func = getattr(nanops, nanname)
        else:
            func = _dask_or_eager_func(name)

        try:
            return func(values, axis=axis, **kwargs)
        except AttributeError:
            if isinstance(values, dask_array_type):
                try:  # dask/dask#3133 dask sometimes needs dtype argument
                    # if func does not accept dtype, then raises TypeError
                    return func(values, axis=axis, dtype=values.dtype,
                                **kwargs)
                except (AttributeError, TypeError):
                    msg = '%s is not yet implemented on dask arrays' % name
            else:
                msg = ('%s is not available with skipna=False with the '
                       'installed version of numpy; upgrade to numpy 1.12 '
                       'or newer to use skipna=True or skipna=None' % name)
            raise NotImplementedError(msg)

    f.__name__ = name
    return f

# Attributes `numeric_only`, `available_min_count` is used for docs.
# See ops.inject_reduce_methods
argmax = _create_nan_agg_method('argmax', coerce_strings=True)
argmin = _create_nan_agg_method('argmin', coerce_strings=True)
max = _create_nan_agg_method('max', coerce_strings=True)
min = _create_nan_agg_method('min', coerce_strings=True)
sum = _create_nan_agg_method('sum')
sum.numeric_only = True
sum.available_min_count = True
std = _create_nan_agg_method('std')
std.numeric_only = True
var = _create_nan_agg_method('var')
var.numeric_only = True
median = _create_nan_agg_method('median')
median.numeric_only = True
prod = _create_nan_agg_method('prod')
prod.numeric_only = True
sum.available_min_count = True
cumprod_1d = _create_nan_agg_method('cumprod')
cumprod_1d.numeric_only = True
cumsum_1d = _create_nan_agg_method('cumsum')
cumsum_1d.numeric_only = True

_mean = _create_nan_agg_method('mean')

def datetime_to_numeric(array, offset=None, datetime_unit=None, dtype=float):
    """Convert an array containing datetime-like data to an array of floats.

    Parameters
    ----------
    da : np.array
        Input data
    offset: Scalar with the same type of array or None
        If None, subtract minimum values to reduce round off error
    datetime_unit: None or any of {'Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms',
        'us', 'ns', 'ps', 'fs', 'as'}
    dtype: target dtype

    Returns
    -------
    array
    """
    # TODO: make this function dask-compatible?
    if offset is None:
        offset = array.min()
    array = array - offset

    if not hasattr(array, 'dtype'):  # scalar is converted to 0d-array
        array = np.array(array)

    if array.dtype.kind in 'O':
        # possibly convert object array containing datetime.timedelta
        array = np.asarray(pd.Series(array.ravel())).reshape(array.shape)

    if datetime_unit:
        array = array / np.timedelta64(1, datetime_unit)

    # convert np.NaT to np.nan
    if array.dtype.kind in 'mM':
        return np.where(isnull(array), np.nan, array.astype(dtype))
    return array.astype(dtype)

def _to_pytimedelta(array, unit='us'):
    index = pd.TimedeltaIndex(array.ravel(), unit=unit)
    return index.to_pytimedelta().reshape(array.shape)

def mean(array, axis=None, skipna=None, **kwargs):
    """inhouse mean that can handle np.datetime64 or cftime.datetime
    dtypes"""
    from .common import _contains_cftime_datetimes

    array = asarray(array)
    if array.dtype.kind in 'Mm':
        offset = min(array)
        # xarray always uses np.datetime64[ns] for np.datetime64 data
        dtype = 'timedelta64[ns]'
        return _mean(datetime_to_numeric(array, offset), axis=axis,
                     skipna=skipna, **kwargs).astype(dtype) + offset
    elif _contains_cftime_datetimes(array):
        if isinstance(array, dask_array_type):
            raise NotImplementedError(
                'Computing the mean of an array containing '
                'cftime.datetime objects is not yet implemented on '
                'dask arrays.')
        offset = min(array)
        timedeltas = datetime_to_numeric(array, offset, datetime_unit='us')
        mean_timedeltas = _mean(timedeltas, axis=axis, skipna=skipna,
                                **kwargs)
        return _to_pytimedelta(mean_timedeltas, unit='us') + offset
    else:
        return _mean(array, axis=axis, skipna=skipna, **kwargs)

mean.numeric_only = True  # type: ignore

def _nd_cum_func(cum_func, array, axis, **kwargs):
    array = asarray(array)
    if axis is None:
        axis = tuple(range(array.ndim))
    if isinstance(axis, int):
        axis = (axis,)

    out = array
    for ax in axis:
        out = cum_func(out, axis=ax, **kwargs)
    return out

def cumprod(array, axis=None, **kwargs):
    """N-dimensional version of cumprod."""
    return _nd_cum_func(cumprod_1d, array, axis, **kwargs)

def cumsum(array, axis=None, **kwargs):
    """N-dimensional version of cumsum."""
    return _nd_cum_func(cumsum_1d, array, axis, **kwargs)

_fail_on_dask_array_input_skipna = partial(
    fail_on_dask_array_input,
    msg='%r with skipna=True is not yet implemented on dask arrays')

def first(values, axis, skipna=None):
    """Return the first non-NA elements in this array along the given axis
    """
    if (skipna or skipna is None) and values.dtype.kind not in 'iSU':
        # only bother for dtypes that can hold NaN
        _fail_on_dask_array_input_skipna(values)
        return nanfirst(values, axis)
    return take(values, 0, axis=axis)

def last(values, axis, skipna=None):
    """Return the last non-NA elements in this array along the given axis
    """
    if (skipna or skipna is None) and values.dtype.kind not in 'iSU':
        # only bother for dtypes that can hold NaN
        _fail_on_dask_array_input_skipna(values)
        return nanlast(values, axis)
    return take(values, -1, axis=axis)

def rolling_window(array, axis, window, center, fill_value):
    """
    Make an ndarray with a rolling window of axis-th dimension.
    The rolling dimension will be placed at the last dimension.
    """
    if isinstance(array, dask_array_type):
        return dask_array_ops.rolling_window(
            array, axis, window, center, fill_value)
    else:  # np.ndarray
        return nputils.rolling_window(
            array, axis, window, center, fill_value)


text:
<?xml version="1.0" encoding="utf-8"?>
<merge
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:app="http://schemas.android.com/apk/res-auto"
	xmlns:tools="http://schemas.android.com/tools"
	tools:visibility="visible"
	>

	<LinearLayout
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:layout_gravity="center"
		android:layout_marginBottom="?actionBarSize"
		android:gravity="center"
		android:orientation="vertical"
		>

		<ru.fantlab.android.ui.widgets.FontTextView
			android:id="@+id/empty_text"
			style="@style/TextAppearance.AppCompat.Medium"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:autoLink="all"
			android:gravity="center"
			android:padding="@dimen/spacing_xs_large"
			android:text="@string/no_data"
			android:textColor="?colorAccent"
			/>

		<ru.fantlab.android.ui.widgets.FontButton
			android:id="@+id/reload"
			style="@style/Widget.AppCompat.Button.Borderless.Colored"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_marginBottom="@dimen/spacing_xs_large"
			android:gravity="center"
			android:text="@string/reload"
			android:textAppearance="@style/TextAppearance.AppCompat.Title"
			android:textColor="@color/material_amber_800"
			/>

	</LinearLayout>

</merge>


text:
package com.mblinn.oo.tinyweb.stepfour

import com.mblinn.oo.tinyweb.ControllerException
import com.mblinn.oo.tinyweb.RenderingException

trait Controller {
  def handleRequest(httpRequest: HttpRequest): HttpResponse
}

class FunctionController(view: View, doRequest: (HttpRequest) =>
  Map[String, List[String]] ) extends Controller {

  def handleRequest(request: HttpRequest): HttpResponse = {
    try {
      val model = doRequest(request)
      val responseBody = view.render(model)
      HttpResponse(responseBody, 200)
    } catch {
      case e: ControllerException =>
        HttpResponse("", e.getStatusCode)
      case e: RenderingException =>
        HttpResponse("Exception while rendering.", 500)
      case e: Exception =>
        HttpResponse("", 500)
    }
  }
}


text:
package Connect4;

import javax.swing.Timer;

/**
 * A game mode in which players can place two pieces instead of one.
 * In an attempt at balance, only a single piece can be placed on the first turn.
 * @author Owen Jow
 */
public class FourByTwoPanel extends TwoPlayerPanel {
    /**
     * We'll need to create a special board for this mode.
     * (The default board switches turns every time a piece is dropped.)
     */
    @Override
    public void activate() {
        requestFocus();
        addMouseListener(mouseListener);
        addMouseMotionListener(mouseListener);
        timer = new Timer(1, this);
        timer.start();
        board = new FourByTwoBoard();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;

namespace Microsoft.Azure.Management.Insights.Models
{
    /// <summary>
    /// Webhook notification.
    /// </summary>
    public partial class WebhookNotification
    {
        private IDictionary<string, string> _properties;

        /// <summary>
        /// Optional. Gets or sets a property bag of settings.
        /// </summary>
        public IDictionary<string, string> Properties
        {
            get { return this._properties; }
            set { this._properties = value; }
        }

        private string _serviceUri;

        /// <summary>
        /// Optional. Gets or sets the service address to receive the
        /// notification.
        /// </summary>
        public string ServiceUri
        {
            get { return this._serviceUri; }
            set { this._serviceUri = value; }
        }

        /// <summary>
        /// Initializes a new instance of the WebhookNotification class.
        /// </summary>
        public WebhookNotification()
        {
            this.Properties = new LazyDictionary<string, string>();
        }
    }
}


text:
package org.magicdgs.readtools.cmd.argumentcollections;

import org.magicdgs.readtools.RTBaseTest;

import htsjdk.samtools.SAMReadGroupRecord;
import htsjdk.samtools.util.Iso8601Date;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * @author Daniel Gomez-Sanchez (magicDGS)
 */
public class ReadGroupArgumentCollectionUnitTest extends RTBaseTest {

    @Test
    public void testGetNoArgumentsReadGroup() throws Exception {
        final SAMReadGroupRecord expected = new SAMReadGroupRecord("RGID");
        expected.setProgramGroup("ReadTools");
        expected.setSample("sampleName");
        Assert.assertEquals(new ReadGroupArgumentCollection()
                        .getReadGroupFromArguments(expected.getReadGroupId(), expected.getSample()),
                expected);
    }

    @Test
    public void testGetReadGroupWithArguments() throws Exception {
        // setting expected RG
        final SAMReadGroupRecord expected = new SAMReadGroupRecord("RGID");
        expected.setProgramGroup("ReadTools");
        expected.setSample("sampleName");
        // setting args
        final ReadGroupArgumentCollection rgargs = new ReadGroupArgumentCollection();

        // starting setting params
        expected.setLibrary("LB");
        rgargs.readGroupLibrary = "LB";

        expected.setPlatform("ILLUMINA");
        rgargs.readGroupPlatform = SAMReadGroupRecord.PlatformValue.ILLUMINA;

        expected.setPlatformUnit("PU");
        rgargs.readGroupPlatformUnit = expected.getPlatformUnit();

        expected.setSequencingCenter("CN");
        rgargs.readGroupSequencingCenter = expected.getSequencingCenter();

        final Iso8601Date date = new Iso8601Date("2007-11-03");
        expected.setRunDate(date);
        rgargs.readGroupRunDate = date;

        expected.setPredictedMedianInsertSize(100);
        rgargs.readGroupPredictedInsertSize = expected.getPredictedMedianInsertSize();

        expected.setPlatformModel("PM");
        rgargs.readGroupPlatformModel = expected.getPlatformModel();

        // testing
        Assert.assertEquals(rgargs
                        .getReadGroupFromArguments(expected.getReadGroupId(), expected.getSample()),
                expected);
    }

}


text:
/// @file xed-gen-table-defs.h

// This file was automatically generated.
// Do not edit this file.

#if !defined(_XED_GEN_TABLE_DEFS_H_)
# define _XED_GEN_TABLE_DEFS_H_
#define XED_MAX_ATTRIBUTE_COUNT 38
#define XED_MAX_GRAPH_NODES 8015
#define XED_MAX_GRAPH_NEXT_NODES 12672
#define XED_MAX_INST_TABLE_NODES 2470
#define XED_MAX_OPERAND_TABLE_NODES 6612
#define XED_MAX_REQUIRED_SIMPLE_FLAGS_ENTRIES 870
#define XED_MAX_REQUIRED_COMPLEX_FLAGS_ENTRIES 53
#define XED_MAX_IFORMS_PER_ICLASS 27
#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;

namespace MadOwlAdminWebApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.EnableCors();

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}


text:
**Type**		: SERVICE
**Status**		: TESTED
**Description**	: cloudera cdh4 slave recipe 1.0.0
**Maintainer**	: Fastconnect
**Maintainer email**	:
**Contributors**		:
**Homepage**			:
**License**				: Apache 2.0
**Build**:
**Linux sudoer permissions**	: REQUIRED
**Windows Admin permissions**	: Not supported
**Release Date**				: July 26th 2013

## Recipe version

* **Date** : Month Day Year (tag creation date)
	* **Tag/Branch Name** 	: cloudera cdh4 slave recipe 1.0.0
	* **Recipe Base URL**   : [https://github.com/fastconnect/cloudify-cloudera](https://github.com/fastconnect/cloudify-cloudera)

## Tested Cloud & OS

* **Amazon EC2**
	* **precise64** : Ubuntu precise 64 bits
	* **ImageID**	: eu-west-1/ami-fc7a6e88

## Details

### Service dependencies

Dependencies between services <> applications

* **cdh4-manager** :
	* **Service TAG** 	: current version
	* **Details**		: cdh4-slave depends on cdh4-manager

* **cdh4-master** :
	* **Service TAG** 	: current version
	* **Details**		: cdh4-slave depends on cdh4-master

### Service description
This folder contains an application recipe for cloudera cdh4.
manages installation of packages and configuration of **slaves roles** such as Tasktracker and DataNode...
cloudera Services to configure are defined in the properties file of cdh4-manager service.
Also configure nodes as mongoDB shards if necessary

### Properties file

* **Property name** : *agentServerPort*
	* REQUIRED
	* **Description** :Default is *7182*.

* **Property name** : *agentListeningPort*
	* REQUIRED
	* **Description** :Default is *9000*

* **Property name** : *mongoDPort*
	* REQUIRED
	* **Description** :the port for the mongoD instance. Default is *27018*

* **Property name** : *clouderaHadoopVersion*
	* REQUIRED
	* **Description** : cloudera Hadoop version (cdh4 version): supported and tested version is *4.3.0*

* **Property name** : *clouderaManagerVersion*
	* REQUIRED
	* **Description** : cloudera manager version (cm4 version): supported and tested version is *4.6.1*

### Custom commands
None

## Changelist


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jme3.gde.blender.filetypes;

import java.io.IOException;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.MIMEResolver;
import org.openide.loaders.DataObject;
import org.openide.loaders.DataObjectExistsException;
import org.openide.loaders.MultiFileLoader;
import org.openide.util.NbBundle.Messages;

/**
 *
 * @author normenhansen
 */
@Messages({
    "LBL_BlenderDae_LOADER=Collada Files (via Blender)"
})
@MIMEResolver.ExtensionRegistration(
    displayName = "#LBL_BlenderDae_LOADER",
mimeType = "model/vnd.collada+xml",
extension = {"dae", "DAE"})
@DataObject.Registration(
    mimeType = "model/vnd.collada+xml",
iconBase = "com/jme3/gde/blender/blender.png",
displayName = "#LBL_BlenderDae_LOADER",
position = 300)
@ActionReferences({
    @ActionReference(
        path = "Loaders/model/vnd.collada+xml/Actions",
    id =
    @ActionID(category = "System", id = "org.openide.actions.OpenAction"),
    position = 100,
    separatorAfter = 200),
    @ActionReference(
        path = "Loaders/model/vnd.collada+xml/Actions",
    id =
    @ActionID(category = "Edit", id = "org.openide.actions.CutAction"),
    position = 300),
    @ActionReference(
        path = "Loaders/model/vnd.collada+xml/Actions",
    id =
    @ActionID(category = "Edit", id = "org.openide.actions.CopyAction"),
    position = 400,
    separatorAfter = 500),
    @ActionReference(
        path = "Loaders/model/vnd.collada+xml/Actions",
    id =
    @ActionID(category = "Edit", id = "org.openide.actions.DeleteAction"),
    position = 600),
    @ActionReference(
        path = "Loaders/model/vnd.collada+xml/Actions",
    id =
    @ActionID(category = "System", id = "org.openide.actions.RenameAction"),
    position = 700,
    separatorAfter = 800),
    @ActionReference(
        path = "Loaders/model/vnd.collada+xml/Actions",
    id =
    @ActionID(category = "System", id = "org.openide.actions.SaveAsTemplateAction"),
    position = 900,
    separatorAfter = 1000),
    @ActionReference(
        path = "Loaders/model/vnd.collada+xml/Actions",
    id =
    @ActionID(category = "System", id = "org.openide.actions.FileSystemAction"),
    position = 1100,
    separatorAfter = 1200),
    @ActionReference(
        path = "Loaders/model/vnd.collada+xml/Actions",
    id =
    @ActionID(category = "System", id = "org.openide.actions.ToolsAction"),
    position = 1300),
    @ActionReference(
        path = "Loaders/model/vnd.collada+xml/Actions",
    id =
    @ActionID(category = "System", id = "org.openide.actions.PropertiesAction"),
    position = 1400)
})
public class BlenderDaeDataObject extends AbstractBlenderImportDataObject {

    public BlenderDaeDataObject(FileObject pf, MultiFileLoader loader) throws DataObjectExistsException, IOException {
        super(pf, loader);
        SUFFIX = "dae";
    }
}


text:
package org.archive.wayback.archivalurl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletException;

import org.archive.wayback.core.CaptureSearchResult;
import org.archive.wayback.core.UIResults;
import org.archive.wayback.core.WaybackRequest;
import org.archive.wayback.replay.JSPExecutor;
import org.archive.wayback.replay.html.ReplayParseContext;
import org.archive.wayback.replay.html.StringTransformer;
import org.archive.wayback.replay.html.transformer.JSStringTransformer;
import org.archive.wayback.util.htmllex.ContextAwareLexer;
import org.htmlparser.Node;
import org.htmlparser.Tag;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.lexer.Page;
import org.htmlparser.nodes.TagNode;

import junit.framework.TestCase;

/**
 * test {@link FastArchivalUrlReplayParseEventHandler}.
 * also covers {@link StandardAttributeRewriter}.
 *
 */
public class FastArchivalUrlReplayParseEventHandlerTest extends TestCase {

	FastArchivalUrlReplayParseEventHandler delegator;

	final String baseUrl = "http://www.example.com/";
	final String timestamp = "2001";
	final String outputCharset = "UTF-8";
	final String charSet = "UTF-8";

    ArchivalUrlResultURIConverter uriConverter;
    ArchivalUrlContextResultURIConverterFactory fact;
    ReplayParseContext context;
	JSPExecutor jspExec = null;

	@Override
	protected void setUp() throws Exception {
		uriConverter = new ArchivalUrlResultURIConverter();
		uriConverter.setReplayURIPrefix("http://replay.archive.org/");

		fact = new ArchivalUrlContextResultURIConverterFactory(
			(ArchivalUrlResultURIConverter)uriConverter);

		// The URL of the page, for resolving in-page relative URLs:
		CaptureSearchResult capture = new CaptureSearchResult();
		capture.setCaptureTimestamp(timestamp);
		capture.setOriginalUrl(baseUrl);
		// urlKey is not set as it is unused

		// set up the context:
		context = new ReplayParseContext(fact, capture);
		context.setOutputCharset(outputCharset);

		delegator = new FastArchivalUrlReplayParseEventHandler();
		delegator.setEndJsp(null);
		delegator.setJspInsertPath(null);
		delegator.init();
	}

    public void testHtmlScriptElementSupport() throws Exception {
        final String input = ""
                + " "
                + "foo" + "";
        final String expected = ""
                + " "
                + "foo"
                + "";
        assertEquals(expected, doEndToEnd(input));
    }

	public void testAnchorHrefAbsolute() throws Exception {
		final String input = "" +
				"foo" +
				"";
		final String expected = "" +
				"" +
				"foo";
		assertEquals(expected, doEndToEnd(input));
	}

	public void testAnchorHrefRelative() throws Exception {
		final String input = "" +
				"foo" +
				"";
		final String expected = "" +
				"foo" +
				"";
		assertEquals(expected, doEndToEnd(input));
	}

	public void testAnchorHrefAbsoluteInJavascript() throws Exception {
		final String input = "" +
				"American Symphony Orchestra League" +
				"";
		final String expected = "" +
				"American Symphony Orchestra League" +
				"";
		assertEquals(expected, doEndToEnd(input));
	}

	public void testStyleElementBackgroundUrl() throws Exception {
	    final String input = "" +
	    		"" +
	    		"" +
	    		"" +
	    		"";
        final String expected = "" +
                "" +
                "" +
                "" +
                "";
	    assertEquals(expected, doEndToEnd(input));
	}
	/**
	 * HTML entities in <STYLE> element are not unescaped.
	 * (although this is an unlikely scenario)
	 * @throws Exception
	 */
	public void testStyleElementBackgroundUrlNoUnescape() throws Exception {
	    final String input = "" +
	    		"" +
	    		"" +
	    		"" +
	    		"";
        final String expected = "" +
                "" +
                "" +
                "" +
                "";
	    assertEquals(expected, doEndToEnd(input));
	}

	public void testStyleElementImportUrl() throws Exception {
        final String input = "" +
                "" +
                "" +
                "" +
                "";
        final String expected = "" +
                "" +
                "" +
                "" +
                "";
        assertEquals(expected, doEndToEnd(input));
	}

	public void testStyleElmeentImportUrlInsideCDATA() throws Exception {
        final String input = "" +
                "" +
                "" +
                "" +
                "";
        final String expected = "" +
                "" +
                "" +
                "" +
                "";
        String out = doEndToEnd(input);
        assertEquals(expected, out);
	}

	/**
	 * Some people enclose in-line STYLE content with HTML Comment
	 * for better support for stone age browsers.
	 * @throws Exception
	 */
	public void testStyleElmeentImportUrlInsideHTMLComment() throws Exception {
        final String input = "" +
                "" +
                "" +
                "" +
                "";
        final String expected = "" +
                "" +
                "" +
                "" +
                "";
        String out = doEndToEnd(input);
        assertEquals(expected, out);
	}

    public void testStyleElementFontfaceSrcUrl() throws Exception {
        // font data is not an image technically, but it'd require more elaborate
        // pattern match to differentiate a context of url function. use im_ for
        // font data for now.
        final String input = "" +
                "" +
                "" +
                "" +
                "";
        final String expected = "" +
                "" +
                "" +
                "" +
                "";
        assertEquals(expected, doEndToEnd(input));
    }

    /**
     * URL-rewrite must not unescape HTML entities in URL.
     *
Reported in ARI-3774.
     * Now all attribute values are unescaped before processing, and then escaped back
     * before writing out.  This has a side-effect: bare "{@code &}" gets rewritten to
     * "{@code &}"

     *
     * @throws Exception
     */
	public void testHTMLEntityInURL() throws Exception {
		// note "&amp" - it should appear in translated URL as it does in the original.
		final String input = ""
				+ ""
				+ ""
				+ ""
				+ "";
		final String expected = ""
				+ ""
				+ ""
				+ ""
				+ "";
		assertEquals(expected, doEndToEnd(input));
	}

	/**
	 * test of {@code unescapeAttributeValue } == {@code false} case.
	 * bare "{@code &}" is unchanged.
	 * @throws Exception
	 */
	public void testUnescapeAttributeValuesFalse() throws Exception {
		// disable unescaping HTML entities in attribute value.
		((StandardAttributeRewriter)delegator.getAttributeRewriter()).setUnescapeAttributeValues(false);

		// note "&amp" - it should appear in translated URL as it does in the original.
		final String input = ""
				+ ""
				+ ""
				+ ""
				+ "";
		final String expected = ""
				+ ""
				+ ""
				+ ""
				+ "";
		assertEquals(expected, doEndToEnd(input));
	}

	public void testLinkElement() throws Exception {
		final String input = "" +
				"" +
				"  <link rel=\"stylesheet\" href=\"basic.css?v=1.0&l=en\">" +
				"  <link rel=\"shortcut icon\" href=\"icon.png?v=1.0&rg=en\">" +
				"" +
				"" +
				"";
		final String expected = "" +
				"" +
				"  <link rel=\"stylesheet\" href=\"basic.css?v=1.0&l=en\">" +
				"  <link rel=\"shortcut icon\" href=\"icon.png?v=1.0&rg=en\">" +
				"" +
				"" +
				"";
		assertEquals(expected, doEndToEnd(input));
	}

	public void testStyleAttribute() throws Exception {
		final String input = "" +
				"" +
				"
" +
				"blah" +
				"
" +
				"" +
				"";
		final String expected = "" +
				"" +
				"
" +
				"blah" +
				"
" +
				"" +
				"";
		assertEquals(expected, doEndToEnd(input));
	}

	/**
	 * test of rewriting SCRIPT tag.
	 * Also covered is a feature for disabling script by returning {@code null} from
	 * {@code jsBlockTrans} (This feature may be removed/redesigned at any time).
	 * @throws Exception
	 */
	public void testDisableScriptElement() throws Exception {
		delegator.setJsBlockTrans(new StringTransformer() {
			@Override
			public String transform(ReplayParseContext context, String input) {
				if (input.equals("dropthis.js"))
					return null;
				else
					return input;
			}
		});
		final String input = "" +
				"" +
				"" +
				"" +
				"" +
				"" +
				"" +
				"";
		final String expected = "" +
				"" +
				"" +
				"" +
				"" +
				"" +
				"" +
				"";
		assertEquals(expected, doEndToEnd(input));
	}

	/**
	 * URL rewrite takes {@code BASE} element into account.
	 * @throws Exception
	 */
	public void testBase() throws Exception {
		final String input = "" +
				"<base href='http://othersite.com/'>" +
				"" +
				"next page" +
				"<base href='http://anothersite.com/'>" +
				"" +
				"";
		final String expected = "" +
				"<base href='http://replay.archive.org/2001/http://othersite.com/'>" +
				"" +
				"next page" +
				"<base href='http://replay.archive.org/2001/http://anothersite.com/'>" +
				"" +
				"";
		assertEquals(expected, doEndToEnd(input));
	}

	/**
	 * test of additional attribute rewrite rules for {@link StandardAttributeRewriter}.
	 * additional rules takes precedence over default one, if they are of the same specificity.
	 * @throws Exception
	 */
	public void testAdditionalAttributeRewriteRules() throws Exception {
		// adding custom rewrite rules through backdoor...
		Properties rules = new Properties();
		rules.setProperty("SPAN.DATA-URI.type", "an");
		rules.setProperty("A[ROLE=logo.download].HREF.type", "im");
		rules.setProperty("LINK[TYPE=text/javascript].HREF.type", "js");
		((StandardAttributeRewriter)delegator.getAttributeRewriter()).loadRulesFromProperties(rules);

		final String input = "" +
				"" +
				"<link rel='stylesheet' type='text/javascript' href='styles.js'>" +
				"" +
				"" +
				"" +
				"download logo" +
				"" +
				"";
		final String expected = "" +
				"" +
				"<link rel='stylesheet' type='text/javascript' href='styles.js'>" +
				"" +
				"" +
				"" +
				"download logo" +
				"" +
				"";

		assertEquals(expected, doEndToEnd(input));
	}

	/**
	 * test of {@link StandardAttributeRewriter#setDefaultRulesDisabled(boolean)}
	 * @throws Exception
	 */
	public void testDisableDefaultRules() throws Exception {
		// use local instance for modifying defaultRulesDisabled property.
		StandardAttributeRewriter rewriter = new StandardAttributeRewriter();
		rewriter.setDefaultRulesDisabled(true);
		Properties rules = new Properties();
		rules.setProperty("A[REWRITE=TRUE].HREF.type", "an");
		rewriter.setConfigProperties(rules);
		rewriter.init();
		delegator.setAttributeRewriter(rewriter);

		final String input ="" +
				"" +
				"ignore this" +
				"rewrite this" +
				"" +
				"";
		final String expected ="" +
				"" +
				"ignore this" +
				"rewrite this" +
				"" +
				"";

		assertEquals(expected, doEndToEnd(input));
	}

	/**
	 * JSPExecutor patched to return predictable text without
	 * actually running JSP.
	 */
	protected static class TestJSPExecutor extends JSPExecutor {
		public TestJSPExecutor() {
			// we cannot pass null WaybackRequest to JSPExecutor constructor,
			// because it accesses WaybackRequst.isAjaxRequest() method.
			//super(null, null, null, stubWaybackRequest(), null, null, null);
			super(null, null, new UIResults(stubWaybackRequest(), null));
		}
		// for testing with context flags (ex. fw_)
		public TestJSPExecutor(WaybackRequest wbRequest) {
			//super(null, null, null, wbRequest, null, null, null);
			super(null, null, new UIResults(wbRequest, null));
		}
		@Override
		public String jspToString(String jspPath) throws ServletException,
				IOException {
			return "[[[JSP-INSERT:" + jspPath + "]]]";
		}
		private static WaybackRequest stubWaybackRequest() {
			WaybackRequest wbRequest = new WaybackRequest();
			// make sure ajaxRequest is false (true disables JSP inserts)
			// it's false by default currently, but just in case (paranoia).
			wbRequest.setAjaxRequest(false);
			return wbRequest;
		}
	}

	/**
	 * Servers often return non-HTML resource with {@code Content-Type: text/html}.
	 * Inserting HTML annotation to non-HTML resource can break its replay.
	 * Therefore, don't insert {@code EndJsp} if resource does not appear to be
	 * HTML.
	 * @throws Exception
	 */
	public void testNoEndJspForNonHTML() throws Exception {
		delegator.setEndJsp("end.jsp");
		jspExec = new TestJSPExecutor();

		final String input = "{\"a\": 1}";
		final String expected = "{\"a\": 1}";

		String output = doEndToEnd(input);
		System.out.println(output);
		assertEquals(expected, output);
	}

	/**
	 * JSP inserts: well formed case.
	 * @throws Exception
	 */
	public void testInserts() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body-insert.jsp");
		jspExec = new TestJSPExecutor();

		final String input = "" +
				"" +
				"<title>BarBar</title>" +
				"" +
				"<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">" +
				"" +
				"" +
				"
" +
				"" +
				"
" +
				"" +
				"";
		final String expected = "" +
				"" +
				"[[[JSP-INSERT:head.jsp]]]" +
				"<title>BarBar</title>" +
				"" +
				"<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">" +
				"" +
				"" +
				"[[[JSP-INSERT:body-insert.jsp]]]" +
				"
" +
				"" +
				"
" +
				"" +
				"";
		String output = doEndToEnd(input);
		System.out.println(output);
		assertEquals(expected, output);
	}

	/**
	 * Pathological case:
	 * Missing HEAD tag. head-insert shall be inserted just before
	 * the first open tag (excluding !DOCTYPE and HTML).
	 * @throws Exception
	 */
	public void testMissingHeadTag() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body.jsp");
		jspExec = new TestJSPExecutor();

		final String input = "" +
				"<title>BarBar</title>" +
				"" +
				"Content" +
				"" +
				"";
		final String expected = "" +
				"[[[JSP-INSERT:head.jsp]]]" +
				"<title>BarBar</title>" +
				"" +
				"[[[JSP-INSERT:body.jsp]]]" +
				"Content" +
				"" +
				"";

		String output = doEndToEnd(input);
		assertEquals(expected, output);
	}

	public void testMissingBodyTag() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body-insert.jsp");
		jspExec = new TestJSPExecutor();

		final String input = "" +
				"" +
				"<title>BarBar</title>" +
				"" +
				"" +
				"
" +
				"" +
				"
" +
				"" +
				"";
		final String expected = "" +
				"" +
				"[[[JSP-INSERT:head.jsp]]]" +
				"<title>BarBar</title>" +
				"" +
				"" +
				"[[[JSP-INSERT:body-insert.jsp]]]" +
				"
" +
				"" +
				"
" +
				"" +
				"";
		String output = doEndToEnd(input);
		System.out.println(output);
		assertEquals(expected, output);
	}

	/**
	 * Pathological case:
	 * Content has {@code } but missing {@code } and {@code BODY}.
	 * @throws Exception
	 */
	public void testMissingHeadCloseTag() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body-insert.jsp");
		jspExec = new TestJSPExecutor();

		final String input = "" +
				"" +
				"<title>BarBar</title>" +
				"" +
				"" +
				"
" +
				"" +
				"
" +
				"" +
				"";
		final String expected = "" +
				"" +
				"[[[JSP-INSERT:head.jsp]]]" +
				"<title>BarBar</title>" +
				"" +
				"" +
				"" +
				"[[[JSP-INSERT:body-insert.jsp]]]" +
				"
" +
				"" +
				"
" +
				"" +
				"";
		String output = doEndToEnd(input);
		System.out.println(output);
		assertEquals(expected, output);
	}

	/**
	 * Pathological case:
	 * Content has {@code } but missing {@code } and {@code BODY}.
	 * @throws Exception
	 */
	public void testMissingHeadCloseAndBodyTag() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body-insert.jsp");
		jspExec = new TestJSPExecutor();

		final String input = "" +
				"" +
				"<title>BarBar</title>" +
				"" +
				"
" +
				"" +
				"
" +
				"" +
				"";
		final String expected = "" +
				"" +
				"[[[JSP-INSERT:head.jsp]]]" +
				"<title>BarBar</title>" +
				"" +
				"[[[JSP-INSERT:body-insert.jsp]]]" +
				"
" +
				"" +
				"
" +
				"" +
				"";
		String output = doEndToEnd(input);
		System.out.println(output);
		assertEquals(expected, output);
	}

	/**
	 * Pathological case:
	 * both HEAD and BODY tags are missing. There are some in-HEAD tags.
	 * @throws Exception
	 */
	public void testMissingHeadAndBodyTag() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body-insert.jsp");
		jspExec = new TestJSPExecutor();

		final String input =
				"<title>BarBar</title>" +
				"" +
				"
" +
				"" +
				"
";
		final String expected =
				"[[[JSP-INSERT:head.jsp]]]" +
				"<title>BarBar</title>" +
				"" +
				"[[[JSP-INSERT:body-insert.jsp]]]" +
				"
" +
				"" +
				"
";
		String output = doEndToEnd(input);
		System.out.println(output);
		assertEquals(expected, output);
	}

	/**
	 * Pathological case:
	 * both HEAD and BODY tags are missing. There are some in-HEAD tags.
	 * @throws Exception
	 */
	public void testMissingHeadAndBodyTagStartsWithContentTag() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body-insert.jsp");
		jspExec = new TestJSPExecutor();

		final String input =
				"
" +
				"" +
				"
";
		final String expected =
				"[[[JSP-INSERT:head.jsp]]]" +
				"[[[JSP-INSERT:body-insert.jsp]]]" +
				"
" +
				"" +
				"
";
		String output = doEndToEnd(input);
		System.out.println(output);
		assertEquals(expected, output);
	}

	/**
	 * Pathological case:
	 * Content-producing tag appearing before BODY tag.
	 * body-insert is inserted before the tag, not after the BODY tag.
	 * @throws Exception
	 */
	public void testNonHeadTagBeforeBodyTag() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body-insert.jsp");
		jspExec = new TestJSPExecutor();

		final String input = "" +
				"<title>BarBar</title>" +
				"" +
				"
TEXT
" +
				"" +
				"
" +
				"" +
				"
" +
				"" +
				"";
		final String expected = "" +
				"[[[JSP-INSERT:head.jsp]]]" +
				"<title>BarBar</title>" +
				"" +
				"[[[JSP-INSERT:body-insert.jsp]]]" +
				"
TEXT
" +
				"" +
				"
" +
				"" +
				"
" +
				"" +
				"";
		String output = doEndToEnd(input);
		System.out.println(output);
		assertEquals(expected, output);
	}

	/**
	 * pathological case of two HEAD tags.
	 * head-insert shall be inserted after the first HEAD tag.
	 * @throws Exception
	 */
	public void testExtraHeadTag() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		jspExec = new TestJSPExecutor();

		final String input = "" +
				"" +
				"" +
				"<title>BarBar</title>" +
				"" +
				"Content" +
				"";
		final String expected = "" +
				"" +
				"[[[JSP-INSERT:head.jsp]]]" +
				"" +
				"<title>BarBar</title>" +
				"" +
				"Content" +
				"";

		String output = doEndToEnd(input);
		assertEquals(expected, output);
	}

	/**
	 * body-inset shall not be inserted to resource rendered
	 * insider {@code FRAME} (identified by {@code fw_} context
	 * flag, {@code frameWrapperContext} in {@code WaybackRequest}.
	 * @throws Exception
	 */
	public void testNoBodyInsertForFrameContent() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body-insert.jsp");
		WaybackRequest wbRequest = new WaybackRequest();
		wbRequest.setAjaxRequest(false);
		wbRequest.setFrameWrapperContext(true);

		jspExec = new TestJSPExecutor(wbRequest);

		final String input = "" +
				"" +
				"<title>BarBar</title>" +
				"" +
				"" +
				"content" +
				"" +
				"";
		final String expected = "" +
				"" +
				"[[[JSP-INSERT:head.jsp]]]" +
				"<title>BarBar</title>" +
				"" +
				"" +
				"content" +
				"" +
				"";
		String output = doEndToEnd(input);
		System.out.println(output);
		assertEquals(expected, output);
	}

	/**
	 * similarly for {@code IFRAME}.
	 * @throws Exception
	 */
	public void testNoBodyInsertForIFrameContent() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body-insert.jsp");
		WaybackRequest wbRequest = new WaybackRequest();
		wbRequest.setAjaxRequest(false);
		wbRequest.setIFrameWrapperContext(true);

		jspExec = new TestJSPExecutor(wbRequest);

		final String input = "" +
				"" +
				"<title>BarBar</title>" +
				"" +
				"" +
				"content" +
				"" +
				"";
		final String expected = "" +
				"" +
				"[[[JSP-INSERT:head.jsp]]]" +
				"<title>BarBar</title>" +
				"" +
				"" +
				"content" +
				"" +
				"";
		String output = doEndToEnd(input);
		System.out.println(output);
		assertEquals(expected, output);
	}

    /**
	 * Pathological case:
	 * content-bearing tags before FRAMESET, even before HEAD.
	 * currently {@link FastArchivalUrlReplayParseEventHandler} alone cannot
	 * handle this case well. {@link ArchivalUrlSAXRewriteReplayRenderer} has
	 * workaround for this kind of case.
	 * @throws Exception
	 */
	public void testFramesetWithExtraTags() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body-insert.jsp");
		jspExec = new TestJSPExecutor();

		final String input =
				"
" +
				"" +
				"" +
				"<frameset border=\"0\" cols=\"150,*\" frameborder=\"0\">" +
				"<frame>" +
				"<frame>" +
				"</frameset>" +
				"";
		final String expected =
				"[[[JSP-INSERT:head.jsp]]][[[JSP-INSERT:body-insert.jsp]]]" +
				"
" +
				"" +
				"" +
				"<frameset border=\"0\" cols=\"150,*\" frameborder=\"0\">" +
				"<frame>" +
				"<frame>" +
				"</frameset>" +
				"";
		String output = doEndToEnd(input);
		System.out.println(output);
		assertEquals(expected, output);
	}

	/**
	 * HTMLParser appears to parse the content of {@code " +
				"";
		final String expected = "[[[JSP-INSERT:head.jsp]]]" +
				"[[[JSP-INSERT:body-insert.jsp]]]";

        String out = doEndToEnd(input);
        System.out.println(out);

        assertEquals(expected, out);
	}

	public void testXHTML() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body-insert.jsp");
		delegator.setEndJsp("end.jsp");
		jspExec = new TestJSPExecutor();

		final String input = "" +
				"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
				"" +
				"  " +
				"    <title>homepage</title>" +
				"  " +
				"  " +
				"  body body" +
				"  " +
				"";
		final String expected = "" +
				"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
				"" +
				"  [[[JSP-INSERT:head.jsp]]]" +
				"    <title>homepage</title>" +
				"  " +
				"  [[[JSP-INSERT:body-insert.jsp]]]" +
				"  body body" +
				"  " +
				"[[[JSP-INSERT:end.jsp]]]";
		String out = doEndToEnd(input);
		System.out.println(out);
		assertEquals(expected, out);
	}

	/**
	 * test of rewriting URLs in DOM event handler attributes.
	 *
only limited set of attributes are supported currently.

	 * @throws Exception
	 */
	public void testDOMEventHandlers() throws Exception {
		// Need a local test instance because changing jsBlockTrans after calling init()
		// has no effect currently.
		delegator = new FastArchivalUrlReplayParseEventHandler();
		delegator.setEndJsp(null);
		delegator.setJspInsertPath(null);
		// sample input below has two backslashes - use custom jsBlockTrans
		JSStringTransformer jsBlockTrans = new JSStringTransformer();
		jsBlockTrans.setRegex("['\"](https?:\\\\{0,2}/\\\\{0,2}/[a-zA-Z0-9_@.-]+)");
		delegator.setJsBlockTrans(jsBlockTrans);
		delegator.init();

		// test sample from Facebook timeline
		final String input = "" +
				"<a class=\"_1xw shareLink _1y0\" href=\"http://www.facebook.com/l.php?" +
				"u=http%3A%2F%2Fwww.ncadv.org%2F&h=PAQH&" +
				"enc=AZPB&" +
				"s=1\" target=\"_blank\" rel=\"nofollow\" " +
				"onmouseover=\"LinkshimAsyncLink.swap(this, "http:\\\\/\\\\/www.ncadv.org\\\\/");\" " +
				"onclick=\"LinkshimAsyncLink.swap(this, "http:\\\\/\\\\/www.facebook.com\\\\/l.php?" +
				"u=http\\\\u00253A\\\\u00252F\\\\u00252Fwww.ncadv.org\\\\u00252F&h=PAQH&enc=AZPB&s=1");\">" +
				"";
		// Note: onmouseover attribute is NOT rewritten currently.
		// Note: URL is first normalized by ParseContext.resolve(), in which backslash escapes are
		//   removed. so "http:\\/\\/www.facebook.com" becomes "http://www.facebook.com"
		final String expected = "" +
				"<a class=\"_1xw shareLink _1y0\" href=\"http://replay.archive.org/2001/http://www.facebook.com/l.php?" +
				"u=http%3A%2F%2Fwww.ncadv.org%2F&h=PAQH&" +
				"enc=AZPB&" +
				"s=1\" target=\"_blank\" rel=\"nofollow\" " +
				"onmouseover=\"LinkshimAsyncLink.swap(this, "http:\\\\/\\\\/www.ncadv.org\\\\/");\" " +
				"onclick=\"LinkshimAsyncLink.swap(this, "http://replay.archive.org/2001/http://www.facebook.com\\\\/l.php?" +
				"u=http\\\\u00253A\\\\u00252F\\\\u00252Fwww.ncadv.org\\\\u00252F&h=PAQH&enc=AZPB&s=1");\">" +
				"";
		String output = doEndToEnd(input);
		System.out.println(output);
		assertEquals(expected, output);
	}

	/**
	 * NOSCRIPT in HEAD can contain arbitrary element (we've seen IMG and IFRAME
	 * occuring inside NOSCRIPT), and it shall not trigger injection of
	 * body-inserts.
	 * @throws Exception
	 */
	public void testNOSCRIPT() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body-insert.jsp");
		jspExec = new TestJSPExecutor();

		final String input = "<!DOCTYPE html>\n" +
				"\n" +
				"  \n" +
				"    \n" +
				"  \n" +
				"\n" +
				"\n" +
				"  body body\n" +
				"\n" +
				"\n";
		final String expected = "<!DOCTYPE html>\n" +
				"[[[JSP-INSERT:head.jsp]]]\n" +
				"  \n" +
				"    \n" +
				"  \n" +
				"\n" +
				"[[[JSP-INSERT:body-insert.jsp]]]\n" +
				"  body body\n" +
				"\n" +
				"\n";;
		String out = doEndToEnd(input);
		//System.out.println(out);
		assertEquals(expected, out);
	}

	/**
	 * pathological case of missing {@code }.
	 * {@code } shall close  as well.
	 * @throws Exception
	 */
	public void testNOSCRIPT_missingCloseTag() throws Exception {
		delegator.setHeadInsertJsp("head.jsp");
		delegator.setJspInsertPath("body-insert.jsp");
		jspExec = new TestJSPExecutor();

		final String input = "<!DOCTYPE html>\n" +
				"\n" +
				"  \n" +
				"    \n" +
				"\n" +
				"\n" +
				"  body body\n" +
				"\n" +
				"\n";
		final String expected = "<!DOCTYPE html>\n" +
				"[[[JSP-INSERT:head.jsp]]]\n" +
				"  \n" +
				"    \n" +
				"\n" +
				"[[[JSP-INSERT:body-insert.jsp]]]\n" +
				"  body body\n" +
				"\n" +
				"\n";;
		String out = doEndToEnd(input);
		//System.out.println(out);
		assertEquals(expected, out);
	}

    public String doEndToEnd(String input) throws Exception {
		ByteArrayInputStream bais = new ByteArrayInputStream(input.getBytes(charSet));

		// To make sure we get the length, we have to buffer it all up...
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		context.setOutputStream(baos);
		context.setJspExec(jspExec);

		// and finally, parse, using the special lexer that knows how to
		// handle javascript blocks containing unescaped HTML entities:
		Page lexPage = new Page(bais,charSet);
		Lexer lexer = new Lexer(lexPage);
		Lexer.STRICT_REMARKS = false;
		ContextAwareLexer lex = new ContextAwareLexer(lexer, context);

		Node node;
		while ((node = lex.nextNode()) != null) {
			delegator.handleNode(context, node);
		}
		delegator.handleParseComplete(context);

		// At this point, baos contains the utf-8 encoded bytes of our result:
		return new String(baos.toByteArray(), outputCharset);
	}

	// The followings checks expected (quirky) behaviors of HTMLParser.
	// If these expectations get broken by HTMLParser upgrades, it is very likely
	// we need to change our code.

    /**
     * test expected behavior of htmlparser.
     *
htmlparser does neither unescape HTML entities found in text, nor
     * escape special characters in Node.toHtml().  We have a workaround based on this
     * behavior.  If this expectation breaks, we need to modify our code.

     * @throws Exception
     */
    public void testHtmlParser_attributeValueEscaping() throws Exception {
    	final String html = "" +
    			"" +
    			"anchor" +
    			"" +
    			"";
    	byte[] bytes = html.getBytes();
    	ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    	Page page = new Page(bais, "UTF-8");
    	Lexer lexer = new Lexer(page);
    	Node node;
    	while ((node = lexer.nextNode()) != null) {
    		if (node instanceof Tag) {
    			Tag tag = (Tag)node;
    			if (tag.getTagName().equalsIgnoreCase("A") && !tag.isEndTag()) {
    				assertEquals("href", "http://example.com/api?a=1&b=2&c=3"", tag.getAttribute("HREF"));

    				String htmlout = tag.toHtml();
    				assertEquals("toHtml output", "", htmlout);
    			}
    		}
    	}
	}

    /**
     * test expected behavior of {@code HTMLParser} - handling of CDATA.
     * {@code HTMLParser} gives out {@code <![CDATA[ ... ]]>} as single
     * {@code TagNode}.  Quirk is that {@code tagName} can also include
     * characters following "<![CDATA[". And apparently there's no way
     * to update the content.
     * @throws Exception
     */
    public void testHtmlParser_CDATA() throws Exception {
    	final String html = "<![CDATA[aaaa\nbbbb]]>";

    	byte[] bytes = html.getBytes();
    	ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    	Page page = new Page(bais, "UTF-8");
    	Lexer lexer = new Lexer(page);
    	Node node;

    	node = lexer.nextNode();
    	// HTMLParser returns CDATA section as TagNode
    	assertTrue(node instanceof TagNode);
    	TagNode tag = (TagNode)node;
    	// whose tagName is "![CDATA[" *plus* non-whitespace chars following
    	// it.  And if they are alphabets, they get capitalized.
    	assertTrue(tag.getTagName().startsWith("![CDATA["));
    	assertEquals("AAAA", tag.getTagName().substring("![CDATA[".length()));
    	// Fortunately, getText() returns entire CDATA section, including
    	// leading "!CDATA[" and trailing "]]" (no < and >), unmodified.
    	String text = tag.getText();
    	System.out.println("text=\"" + text + "\" (" + text.length() + " chars)");
    	assertEquals("![CDATA[aaaa\nbbbb]]", text);
    	// but setText() results in ClassCastException
    	try {
    		tag.setText("![CDATA[bbbb]]");
    		fail("setText() did not throw an Exception");
    	} catch (ClassCastException ex) {
    		// expected
    	}
    }
}


text:
package com.jcabi.github;

import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.jcabi.http.Request;
import com.jcabi.http.response.RestResponse;
import java.io.IOException;
import java.net.HttpURLConnection;
import javax.json.JsonObject;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import org.hamcrest.Matchers;

/**
 * Public members of a GitHub organization.
 *
 * @author Chris Rebert (github@chrisrebert.com)
 * @version $Id$
 * @see Organization Members API
 * @since 0.24
 */
@Immutable
@Loggable(Loggable.DEBUG)
@EqualsAndHashCode(of = { "entry", "organization" })
public final class RtPublicMembers implements PublicMembers {
    /**
     * API entry point.
     */
    private final transient Request entry;

    /**
     * RESTful request.
     */
    private final transient Request request;

    /**
     * Organization.
     */
    private final transient Organization organization;

    /**
     * Public ctor.
     * @param req Request
     * @param organ Organization
     */
    public RtPublicMembers(
        @NotNull(message = "request cannot be NULL")
        final Request req,
        @NotNull(message = "organization cannot be NULL")
        final Organization organ
    ) {
        this.entry = req;
        this.request = req.uri()
            .path("/orgs")
            .path(organ.login())
            .path("public_members")
            .back();
        this.organization = organ;
    }

    @Override
    @NotNull(message = "organization is never NULL")
    public Organization org() {
        return this.organization;
    }

    @Override
    public void conceal(
        @NotNull(message = "user cannot be NULL")
        final User user
    ) throws IOException {
        this.request
            .uri().path(user.login()).back()
            .method(Request.DELETE)
            .fetch().as(RestResponse.class)
            .assertStatus(HttpURLConnection.HTTP_NO_CONTENT);
    }

    @Override
    public void publicize(
        @NotNull(message = "user cannot be NULL")
        final User user
    ) throws IOException {
        this.request
            .uri().path(user.login()).back()
            .method(Request.PUT)
            .fetch().as(RestResponse.class)
            .assertStatus(HttpURLConnection.HTTP_NO_CONTENT);
    }

    @Override
    @NotNull(message = "iterable is never NULL")
    public Iterable<User> iterate() {
        return new RtPagination<User>(
            this.request,
            new RtValuePagination.Mapping<User, JsonObject>() {
                @Override
                public User map(final JsonObject object) {
                    return new RtUser(
                        RtPublicMembers.this.organization.github(),
                        RtPublicMembers.this.entry,
                        object.getString("login")
                    );
                }
            }
        );
    }

    @Override
    public boolean contains(
        @NotNull(message = "user cannot be NULL")
        final User user
    ) throws IOException {
        return this.request
            .uri().path(user.login()).back()
            .method(Request.GET)
            .fetch().as(RestResponse.class)
            .assertStatus(
                Matchers.isOneOf(
                    HttpURLConnection.HTTP_NO_CONTENT,
                    HttpURLConnection.HTTP_NOT_FOUND
            )
        )
            .status() == HttpURLConnection.HTTP_NO_CONTENT;
    }
}


text:
layout: page
title: Rider Red Foundation Executive Retreat
date: 2016-05-24
author: Amy Liu
tags: weekly links, java
status: published
summary: Maecenas ac erat id ligula.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 02/27/2018
  endDate: 02/28/2018
  ctyhocn: HOURGHX
  groupCode: RRFER
published: true
---
Morbi purus ex, aliquet quis congue eu, fringilla ac tellus. Etiam ac dolor eu ante commodo tempor convallis at ex. Fusce semper lorem eget lacus lacinia, nec congue enim venenatis. Integer elementum mauris non nisi dapibus, quis dictum ligula porta. Integer aliquet eu est hendrerit dignissim. Nam non commodo ex. In vestibulum tincidunt sollicitudin. Donec id bibendum magna. Ut nec turpis a urna scelerisque blandit id a est.

* Donec egestas urna et nisl egestas, eget pulvinar arcu varius
* Morbi in metus in augue venenatis dignissim ut a magna
* Phasellus eget ante nec metus tempus volutpat
* Nunc volutpat lorem sit amet felis efficitur convallis
* Nulla hendrerit eros id ipsum lacinia, id sagittis enim pellentesque.

Phasellus bibendum sollicitudin ante, a pulvinar sem mollis interdum. Suspendisse elementum viverra justo sed posuere. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis convallis urna vel ornare porttitor. Nullam vitae tortor at elit tristique faucibus at ac nulla. Nullam consectetur consectetur felis. Vestibulum blandit eget diam nec gravida. Integer rhoncus egestas nunc, ac ultricies lorem sollicitudin sit amet. Nulla vel augue at enim faucibus vulputate. Aliquam porttitor suscipit efficitur. Nullam non sem dictum, mattis lacus sed, mollis neque. Sed quis ex scelerisque est vulputate pulvinar eget sit amet sem. In blandit facilisis nisl, eu luctus magna congue sit amet. Donec rhoncus gravida mattis. Quisque eu neque a lectus congue semper id vitae ipsum.


text:
facts("Sparse (semi-)nonnegative Tucker decomposition") do

context("nonnegative decomposition") do
    # An example of nonnegative and semi-nonnegative Tucker decomposition
    tucker_orig = rand_tucker((4, 5, 6), (40, 50, 60), factors_nonneg=true, core_nonneg=true)
    tnsr_orig = compose(tucker_orig)

    tnsr_max = maximum(tnsr_orig)
    map!(x -> x / tnsr_max, tucker_orig.core)
    map!(x -> x / tnsr_max, tnsr_orig)

    tnsr = add_noise(tnsr_orig, 0.6, true)

    # Solve the problem
    @time tucker_spnn = spnntucker(tnsr, size(tucker_orig.core), tol=1E-4, ini_decomp=:hosvd,
                             core_nonneg=true,
                             max_iter=1000, verbose=true, lambdas=fill(0.1, 4))

    # Reporting
    @fact rel_residue(tucker_spnn) --> less_than(0.05)
    info("Relative error of decomposition : $(rel_residue(tucker_spnn))")
end

context("semi-nonnegative decomposition") do
    tucker_orig = rand_tucker((4, 5, 6), (40, 50, 60), factors_nonneg=true, core_nonneg=false)
    tnsr_orig = compose(tucker_orig)

    tnsr_max = maximum(tnsr_orig)
    map!(x -> x / tnsr_max, tucker_orig.core)
    map!(x -> x / tnsr_max, tnsr_orig)

    tnsr = add_noise(tnsr_orig, 0.6, false)

    # Solve the problem
    @time tucker_spnn = spnntucker(tnsr, size(tucker_orig.core), tol=1E-4, ini_decomp=:hosvd,
                             core_nonneg=false,
                             max_iter=1000, verbose=true, lambdas=fill(0.1, 4))

    # Reporting
    @fact rel_residue(tucker_spnn) --> less_than(0.05)
    info("Relative error of decomposition : $(rel_residue(tucker_spnn))")
end

end


text:
.class public Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;
.super Landroid/database/DataSetObserver;
.source "PseudoGridView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/systemui/qs/PseudoGridView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "ViewGroupAdapterBridge"
.end annotation

# instance fields
.field private final mAdapter:Landroid/widget/BaseAdapter;

.field private mReleased:Z

.field private final mViewGroup:Ljava/lang/ref/WeakReference;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/lang/ref/WeakReference",
            "<",
            "Landroid/view/ViewGroup;",
            ">;"
        }
    .end annotation
.end field

# direct methods
.method private constructor <init>(Landroid/view/ViewGroup;Landroid/widget/BaseAdapter;)V
    .locals 1

    invoke-direct {p0}, Landroid/database/DataSetObserver;-><init>()V

    new-instance v0, Ljava/lang/ref/WeakReference;

    invoke-direct {v0, p1}, Ljava/lang/ref/WeakReference;-><init>(Ljava/lang/Object;)V

    iput-object v0, p0, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->mViewGroup:Ljava/lang/ref/WeakReference;

    iput-object p2, p0, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->mAdapter:Landroid/widget/BaseAdapter;

    const/4 v0, 0x0

    iput-boolean v0, p0, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->mReleased:Z

    iget-object v0, p0, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->mAdapter:Landroid/widget/BaseAdapter;

    invoke-virtual {v0, p0}, Landroid/widget/BaseAdapter;->registerDataSetObserver(Landroid/database/DataSetObserver;)V

    invoke-direct {p0}, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->refresh()V

    return-void
.end method

.method public static link(Landroid/view/ViewGroup;Landroid/widget/BaseAdapter;)V
    .locals 1

    new-instance v0, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;

    invoke-direct {v0, p0, p1}, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;-><init>(Landroid/view/ViewGroup;Landroid/widget/BaseAdapter;)V

    return-void
.end method

.method private refresh()V
    .locals 9

    iget-boolean v8, p0, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->mReleased:Z

    if-eqz v8, :cond_0

    return-void

    :cond_0
    iget-object v8, p0, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->mViewGroup:Ljava/lang/ref/WeakReference;

    invoke-virtual {v8}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v7

    check-cast v7, Landroid/view/ViewGroup;

    if-nez v7, :cond_1

    invoke-direct {p0}, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->release()V

    return-void

    :cond_1
    invoke-virtual {v7}, Landroid/view/ViewGroup;->getChildCount()I

    move-result v2

    iget-object v8, p0, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->mAdapter:Landroid/widget/BaseAdapter;

    invoke-virtual {v8}, Landroid/widget/BaseAdapter;->getCount()I

    move-result v1

    invoke-static {v2, v1}, Ljava/lang/Math;->max(II)I

    move-result v0

    const/4 v3, 0x0

    :goto_0
    if-ge v3, v0, :cond_6

    if-ge v3, v1, :cond_5

    const/4 v6, 0x0

    if-ge v3, v2, :cond_2

    invoke-virtual {v7, v3}, Landroid/view/ViewGroup;->getChildAt(I)Landroid/view/View;

    move-result-object v6

    :cond_2
    iget-object v8, p0, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->mAdapter:Landroid/widget/BaseAdapter;

    invoke-virtual {v8, v3, v6, v7}, Landroid/widget/BaseAdapter;->getView(ILandroid/view/View;Landroid/view/ViewGroup;)Landroid/view/View;

    move-result-object v5

    if-nez v6, :cond_4

    invoke-virtual {v7, v5}, Landroid/view/ViewGroup;->addView(Landroid/view/View;)V

    :cond_3
    :goto_1
    add-int/lit8 v3, v3, 0x1

    goto :goto_0

    :cond_4
    if-eq v6, v5, :cond_3

    invoke-virtual {v7, v3}, Landroid/view/ViewGroup;->removeViewAt(I)V

    invoke-virtual {v7, v5, v3}, Landroid/view/ViewGroup;->addView(Landroid/view/View;I)V

    goto :goto_1

    :cond_5
    invoke-virtual {v7}, Landroid/view/ViewGroup;->getChildCount()I

    move-result v8

    add-int/lit8 v4, v8, -0x1

    invoke-virtual {v7, v4}, Landroid/view/ViewGroup;->removeViewAt(I)V

    goto :goto_1

    :cond_6
    return-void
.end method

.method private release()V
    .locals 1

    iget-boolean v0, p0, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->mReleased:Z

    if-nez v0, :cond_0

    const/4 v0, 0x1

    iput-boolean v0, p0, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->mReleased:Z

    iget-object v0, p0, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->mAdapter:Landroid/widget/BaseAdapter;

    invoke-virtual {v0, p0}, Landroid/widget/BaseAdapter;->unregisterDataSetObserver(Landroid/database/DataSetObserver;)V

    :cond_0
    return-void
.end method

# virtual methods
.method public onChanged()V
    .locals 0

    invoke-direct {p0}, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->refresh()V

    return-void
.end method

.method public onInvalidated()V
    .locals 0

    invoke-direct {p0}, Lcom/android/systemui/qs/PseudoGridView$ViewGroupAdapterBridge;->release()V

    return-void
.end method


text:
using App.Entity;
using App.Exception;
using System;
using System.Text.RegularExpressions;

namespace App.Validators
{
    /// <summary>
    ///
    /// User vaidator class
    /// Author : Catalin Radoiu
    ///
    /// </summary>
    public class UserValidator : IValidator<User>
    {
        /// <summary>
        /// This method checks if all the fields of a user are valid
        /// If a single field is not valid, ValidationException will be thrown
        /// </summary>
        /// <param name="entity"></param>
        public void validate(User entity)
        {
            string errors = "";
            if (!validateName(entity.FirstName))
            {
                errors += "The firstname must have between 2 and 30 letters!\n";
            }
            if (!validateName(entity.LastName))
            {
                errors += "The lastname must have between 2 and 30 letters!\n";
            }
            if (!validateEmail(entity.Email))
            {
                errors += "You have introduced an invalid email !\n";
            }
            if (!validatePassword(entity.Password))
            {
                errors += "The password must have between 8 and 30 characters and at least one number, one uppercase and one " +
                    "lowercase characer!\n";
            }
            if (!validateCountry(entity.Country))
            {
                errors += "The country must have between 3 and 25 letters !\n";
            }

            if (errors.Length != 0)
            {
                throw new ValidationException(errors);
            }
        }

        /// <summary>
        /// Checks if a name is valid
        /// A name is considered valid if it has only letter and at between 2 and 30 characters
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private bool validateName(string name)
        {
            if (name.Length < 2 || name.Length > 30)
            {
                return false;
            }
            if (!Regex.IsMatch(name, @"^[a-zA-Z]+$"))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// Check is the string got as parameter is a valid email adress
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        private bool validateEmail(string email)
        {
            try
            {
                System.Net.Mail.MailAddress addr = new System.Net.Mail.MailAddress(email);
                return addr.Address == email;
            }
            #pragma warning disable CS0168 // Variable is declared but never used
            catch (System.Exception exception)
            #pragma warning restore CS0168 // Variable is declared but never used
            {
                return false;
            }
        }

        /// <summary>
        /// Checks if a passwords is valid
        /// A passwords is considered valid if it has between 8 and 30 characters and at least one number, one lowercase letter and
        /// at least one upper case letter
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        private bool validatePassword(string password)
        {
            if (password.Length < 8 || password.Length > 30)
            {
                return false;
            }
            if (!Regex.IsMatch(password, @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$"))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// Checks if the string got as parameter is a valid country name
        /// The string is valid if it contains between 3 and 25 characters, only letters
        /// A country can contain hyphens
        /// </summary>
        /// <param name="country"></param>
        /// <returns></returns>
        public bool validateCountry(string country)
        {
            if (country.Length < 3 || country.Length > 25)
            {
                return false;
            }
            if (!Regex.IsMatch(country, @"^[a-zA-Z- ]+$"))
            {
                return false;
            }
            return true;
        }
    }
}


text:
#include "../stm32f4_discovery.hpp"

#include <xpcc/processing.hpp>
#include <xpcc/processing/protothread.hpp>
#include <xpcc/driver/color/tcs3414.hpp>

#include <xpcc/io/iostream.hpp>

#include <xpcc/architecture/interface/gpio.hpp>

xpcc::IODeviceWrapper< Usart2, xpcc::IOBuffer::BlockIfFull > device;
xpcc::IOStream stream(device);

/**
 * Example to demonstrate a XPCC driver for colour sensor TCS3414
 *
 * This example uses I2cMaster2 of STM32F407
 *
 * SDA PB11
 * SCL PB10
 *
 * GND and +3V3 are connected to the colour sensor.
 *
 */

// typedef I2cMaster1 MyI2cMaster;
typedef I2cMaster2 MyI2cMaster;
// typedef xpcc::SoftwareI2cMaster<GpioB10, GpioB11> MyI2cMaster;

class ThreadOne : public xpcc::pt::Protothread
{
public:
	ThreadOne() :
		colorSensor()
	{
	}

	bool
	update()
	{
		PT_BEGIN();

		stream << "Ping the device from ThreadOne" << xpcc::endl;

		// ping the device until it responds
		while (true)
		{
			// we wait until the task started
			if (PT_CALL(colorSensor.ping())) {
			 	break;
			}
			// otherwise, try again in 100ms
			this->timeout.restart(100);
			PT_WAIT_UNTIL(this->timeout.isExpired());
		}

		stream << "Device responded" << xpcc::endl;

		while (true)
		{
			if (PT_CALL(colorSensor.initialize())) {
				break;
			}
			// otherwise, try again in 100ms
			this->timeout.restart(100);
			PT_WAIT_UNTIL(this->timeout.isExpired());
		}

		stream << "Device initialized" << xpcc::endl;

		while (true)
		{
			if (PT_CALL(colorSensor.configure(
					xpcc::tcs3414::Gain::X16,
					xpcc::tcs3414::Prescaler::DEFAULT,
					xpcc::tcs3414::IntegrationMode::INTERNAL,
					static_cast<uint8_t>(xpcc::tcs3414::NominalIntegrationTime::MSEC_100)))){
				break;
			}
			// otherwise, try again in 100ms
			this->timeout.restart(100);
			PT_WAIT_UNTIL(this->timeout.isExpired());
		}

		stream << "Device configured" << xpcc::endl;

		while (true)
		{
			if (PT_CALL(colorSensor.refreshAllColors())) {
				auto colors = colorSensor.getOldColors();
				stream.printf("RGB: %5d %5d %5d", colors.red, colors.green, colors.blue);
				xpcc::color::HsvT<xpcc::tcs3414::UnderlyingType> hsv;
				colors.toHsv(&hsv);
				stream.printf("  %5d\n", hsv.hue);
			}
			this->timeout.restart(500);
			PT_WAIT_UNTIL(this->timeout.isExpired());
		}

		PT_END();
	}

private:
	xpcc::ShortTimeout timeout;
	xpcc::Tcs3414<MyI2cMaster> colorSensor;
};

ThreadOne one;

// ----------------------------------------------------------------------------
MAIN_FUNCTION
{
	Board::initialize();

	GpioOutputA2::connect(Usart2::Tx);
	Usart2::initialize<Board::systemClock, xpcc::Uart::B115200>(10);

	GpioB11::connect(I2cMaster2::Sda);
	GpioB10::connect(I2cMaster2::Scl);

	MyI2cMaster::initialize<Board::systemClock, 100000>();

	stream << "\n\nWelcome to TCS3414 demo!\n\n";

	xpcc::ShortPeriodicTimer tmr(500);

	while (1)
	{
		one.update();
		if (tmr.execute()) {
			Board::LedOrange::toggle();
		}
	}

	return 0;
}


text:
gradle clean build -x test
service tomcat stop
rm -rf /opt/tomcat/webapps/*
cp -v build/libs/MediNetServices.war /opt/tomcat/webapps/ROOT.war
service tomcat start


text:
<!-- toc -->
## Contents

  * [Developer Workflow](#developer-workflow)
  * [TDD](#tdd)
  * [Tactics](#tactics)
    * [Approving Files](#approving-files)<!-- endToc -->

For Intention Only:
Diagram representing the workflow of a dev using approval tests
The user will have tasks
User tasks / actions
User sees

## Developer Workflow
digraph G { node [style=filled, shape=rect]

* Separate steps with user vs automatic

User would do:
- approvaltests already installed
- user does: write new test -> run the test

```mermaid
digraph G { node [style=filled, shape=rect]

Verify(object) ->

}
```

## TDD

Test Driven Development usually follow the path

1. Write Arange/Act/Assert Test
1. See it fail
1. Write Code
1. See it pass

Approvaltests loop is slightly different.

It splits the writing of the test into 2 parts:
1. Write Arange/Act part
1. Do the Assert part (Approve it)

These part get seperated to create the full cycle
1. Write Arange/Act
1. See it fail
1. Write Code
1. See it produce the desired output
1. Approve it
1. See it pass

## Tactics

### Approving Files

Coping from the recieved into the appproved. This can be done on the file system or directly in the diff tool.

"Expected Failure"  -> {"failure2", "Pass (unexpected)"}
GOAL:  capture the Expected result
use Approval Tests to KEEP TRACK of passing tests


text:
package chat.rocket.android.helper;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * SHA-256, MD5, ...
 */
public class CheckSum {
  /**
   * SHA-256.
   */
  public static String sha256(String orig) {
    MessageDigest messageDigest;
    try {
      messageDigest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException exception) {
      return null;
    }
    messageDigest.update(orig.getBytes(Charset.forName("UTF-8")));

    StringBuilder stringBuilder = new StringBuilder();
    for (byte b : messageDigest.digest()) {
      stringBuilder.append(String.format("%02x", b & 0xff));
    }

    return stringBuilder.toString();
  }
}


text:
NSString *const DConnectConnectionProfileName = @"connection";

// Attribute
NSString *const DConnectConnectionProfileAttrWifi              = @"wifi";
NSString *const DConnectConnectionProfileAttrBluetooth         = @"bluetooth";
NSString *const DConnectConnectionProfileAttrDiscoverable      = @"discoverable";
NSString *const DConnectConnectionProfileAttrBLE               = @"ble";
NSString *const DConnectConnectionProfileAttrNFC               = @"nfc";
NSString *const DConnectConnectionProfileAttrOnWifiChange      = @"onwifichange";
NSString *const DConnectConnectionProfileAttrOnBluetoothChange = @"onbluetoothchange";
NSString *const DConnectConnectionProfileAttrOnBLEChange       = @"onblechange";
NSString *const DConnectConnectionProfileAttrOnNFCChange       = @"onnfcchange";

// Parameter
NSString *const DConnectConnectionProfileParamEnable        = @"enable";
NSString *const DConnectConnectionProfileParamConnectStatus = @"connectStatus";

// Interface
NSString *const DConnectConnectionProfileInterfaceBluetooth = @"bluetooth";

@implementation DConnectConnectionProfile

#pragma mark - DConnectionProfile Methods

- (NSString *) profileName {
    return DConnectConnectionProfileName;
}

#pragma mark - Setter

+ (void) setEnable:(BOOL)enable target:(DConnectMessage *)message {
    if (!message) {
        @throw @"Message must not be nil.";
    } else {
        [message setBool:enable forKey:DConnectConnectionProfileParamEnable];
    }
}

+ (void) setConnectStatus:(DConnectMessage *)connectStatus target:(DConnectMessage *)message {
    if (!connectStatus) {
        @throw @"ConnectStatus must not be nil.";
    } else if (!message) {
        @throw @"Message must not be nil.";
    } else {
        [message setMessage:connectStatus forKey:DConnectConnectionProfileParamConnectStatus];
    }
}

@end


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#define VTK_WRAPPING_CXX
#define VTK_STREAMS_FWD_ONLY
#include <nan.h>

#include "vtkObjectWrap.h"
#include "vtkStringToImageWrap.h"
#include "../../plus/plus.h"

using namespace v8;

extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap;
Nan::Persistent<v8::FunctionTemplate> VtkStringToImageWrap::ptpl;

VtkStringToImageWrap::VtkStringToImageWrap()
{ }

VtkStringToImageWrap::VtkStringToImageWrap(vtkSmartPointer<vtkStringToImage> _native)
{ native = _native; }

VtkStringToImageWrap::~VtkStringToImageWrap()
{ }

void VtkStringToImageWrap::Init(v8::Local<v8::Object> exports)
{
	Nan::SetAccessor(exports, Nan::New("vtkStringToImage").ToLocalChecked(), ConstructorGetter);
	Nan::SetAccessor(exports, Nan::New("StringToImage").ToLocalChecked(), ConstructorGetter);
}

void VtkStringToImageWrap::ConstructorGetter(
	v8::Local<v8::String> property,
	const Nan::PropertyCallbackInfo<v8::Value>& info)
{
	InitPtpl();
	info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction());
}

void VtkStringToImageWrap::InitPtpl()
{
	if (!ptpl.IsEmpty()) return;
	v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
	VtkObjectWrap::InitPtpl( );
	tpl->Inherit(Nan::New<FunctionTemplate>(VtkObjectWrap::ptpl));
	tpl->SetClassName(Nan::New("VtkStringToImageWrap").ToLocalChecked());
	tpl->InstanceTemplate()->SetInternalFieldCount(1);

	Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName);
	Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName);

	Nan::SetPrototypeMethod(tpl, "GetScaleToPowerOfTwo", GetScaleToPowerOfTwo);
	Nan::SetPrototypeMethod(tpl, "getScaleToPowerOfTwo", GetScaleToPowerOfTwo);

	Nan::SetPrototypeMethod(tpl, "IsA", IsA);
	Nan::SetPrototypeMethod(tpl, "isA", IsA);

	Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance);
	Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance);

	Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast);
	Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast);

	Nan::SetPrototypeMethod(tpl, "SetScaleToPowerOfTwo", SetScaleToPowerOfTwo);
	Nan::SetPrototypeMethod(tpl, "setScaleToPowerOfTwo", SetScaleToPowerOfTwo);

#ifdef VTK_NODE_PLUS_VTKSTRINGTOIMAGEWRAP_INITPTPL
	VTK_NODE_PLUS_VTKSTRINGTOIMAGEWRAP_INITPTPL
#endif
	ptpl.Reset( tpl );
}

void VtkStringToImageWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	if(!info.IsConstructCall())
	{
		Nan::ThrowError("Constructor not called in a construct call.");
		return;
	}

	if(info.Length() == 0)
	{
		Nan::ThrowError("Cannot create instance of abstract class.");
		return;
	}
	else
	{
		if(info[0]->ToObject() != vtkNodeJsNoWrap )
		{
			Nan::ThrowError("Parameter Error");
			return;
		}
	}

	info.GetReturnValue().Set(info.This());
}

void VtkStringToImageWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkStringToImageWrap *wrapper = ObjectWrap::Unwrap<VtkStringToImageWrap>(info.Holder());
	vtkStringToImage *native = (vtkStringToImage *)wrapper->native.GetPointer();
	char const * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetClassName();
	info.GetReturnValue().Set(Nan::New(r).ToLocalChecked());
}

void VtkStringToImageWrap::GetScaleToPowerOfTwo(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkStringToImageWrap *wrapper = ObjectWrap::Unwrap<VtkStringToImageWrap>(info.Holder());
	vtkStringToImage *native = (vtkStringToImage *)wrapper->native.GetPointer();
	bool r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->GetScaleToPowerOfTwo();
	info.GetReturnValue().Set(Nan::New(r));
}

void VtkStringToImageWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkStringToImageWrap *wrapper = ObjectWrap::Unwrap<VtkStringToImageWrap>(info.Holder());
	vtkStringToImage *native = (vtkStringToImage *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsString())
	{
		Nan::Utf8String a0(info[0]);
		int r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->IsA(
			*a0
		);
		info.GetReturnValue().Set(Nan::New(r));
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkStringToImageWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkStringToImageWrap *wrapper = ObjectWrap::Unwrap<VtkStringToImageWrap>(info.Holder());
	vtkStringToImage *native = (vtkStringToImage *)wrapper->native.GetPointer();
	vtkStringToImage * r;
	if(info.Length() != 0)
	{
		Nan::ThrowError("Too many parameters.");
		return;
	}
	r = native->NewInstance();
	VtkStringToImageWrap::InitPtpl();
	v8::Local<v8::Value> argv[1] =
		{ Nan::New(vtkNodeJsNoWrap) };
	v8::Local<v8::Function> cons =
		Nan::New<v8::FunctionTemplate>(VtkStringToImageWrap::ptpl)->GetFunction();
	v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
	VtkStringToImageWrap *w = new VtkStringToImageWrap();
	w->native = r;
	w->Wrap(wo);
	info.GetReturnValue().Set(wo);
}

void VtkStringToImageWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkStringToImageWrap *wrapper = ObjectWrap::Unwrap<VtkStringToImageWrap>(info.Holder());
	vtkStringToImage *native = (vtkStringToImage *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0]))
	{
		VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject());
		vtkStringToImage * r;
		if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		r = native->SafeDownCast(
			(vtkObject *) a0->native.GetPointer()
		);
		VtkStringToImageWrap::InitPtpl();
		v8::Local<v8::Value> argv[1] =
			{ Nan::New(vtkNodeJsNoWrap) };
		v8::Local<v8::Function> cons =
			Nan::New<v8::FunctionTemplate>(VtkStringToImageWrap::ptpl)->GetFunction();
		v8::Local<v8::Object> wo = cons->NewInstance(1, argv);
		VtkStringToImageWrap *w = new VtkStringToImageWrap();
		w->native = r;
		w->Wrap(wo);
		info.GetReturnValue().Set(wo);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}

void VtkStringToImageWrap::SetScaleToPowerOfTwo(const Nan::FunctionCallbackInfo<v8::Value>& info)
{
	VtkStringToImageWrap *wrapper = ObjectWrap::Unwrap<VtkStringToImageWrap>(info.Holder());
	vtkStringToImage *native = (vtkStringToImage *)wrapper->native.GetPointer();
	if(info.Length() > 0 && info[0]->IsBoolean())
	{
				if(info.Length() != 1)
		{
			Nan::ThrowError("Too many parameters.");
			return;
		}
		native->SetScaleToPowerOfTwo(
			info[0]->BooleanValue()
		);
		return;
	}
	Nan::ThrowError("Parameter mismatch");
}


text:
SELECT          'dc-wmata' as system,
                trim(lower(r.route_id)) as id,
                trim(r.route_long_name) as name,
                'train' as type,
                '' as directions
FROM            dc_wmata_routes as r
JOIN            dc_wmata_trips as t
                ON r.route_id = t.route_id
WHERE           r.route_type = 1
GROUP BY        r.route_id

UNION

SELECT          'dc-wmata' as system,
                trim(lower(r.route_id)) as id,
                trim(COALESCE(r.route_long_name, r.route_short_name)) as name,
                'bus' as type,
                string_agg(DISTINCT initcap(trim(t.trip_headsign)), ', ') as directions
FROM            dc_wmata_routes as r
JOIN            dc_wmata_trips as t
                ON r.route_id = t.route_id
WHERE           r.route_type = 3
GROUP BY        r.route_id
ORDER BY        type,
                id,
                directions


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.bayofmany.peapod</groupId>
        <artifactId>peapod-parent</artifactId>
        <version>0.4.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>peapod-demo</artifactId>
    <name>Peapod Demo</name>
    <description>Showcase of Peapod functionality using the TinkerPop 3 sample graphs.</description>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.2</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>peapod</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tinkerpop</groupId>
            <artifactId>tinkergraph-gremlin</artifactId>
            <version>${tinkerpop.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>