text:
#ifdef HAVE_CONFIG_H
#include "../ext_config.h"
#endif

#include <php.h>
#include "../php_ext.h"
#include "../ext.h"

#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>

#include "kernel/main.h"
#include "kernel/memory.h"
#include "kernel/string.h"
#include "kernel/object.h"
#include "kernel/operators.h"
#include "kernel/fcall.h"
#include "kernel/array.h"

ZEPHIR_INIT_CLASS(Test_Pregmatch) {

	ZEPHIR_REGISTER_CLASS(Test, Pregmatch, test, pregmatch, test_pregmatch_method_entry, 0);

	return SUCCESS;

}

PHP_METHOD(Test_Pregmatch, testWithoutReturnAndMatches) {

	zval pattern, subject, _0, _1, _2;
	zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
	zval *this_ptr = getThis();

	ZVAL_UNDEF(&pattern);
	ZVAL_UNDEF(&subject);
	ZVAL_UNDEF(&_0);
	ZVAL_UNDEF(&_1);
	ZVAL_UNDEF(&_2);

	ZEPHIR_MM_GROW();

	ZEPHIR_INIT_VAR(&pattern);
	ZVAL_STRING(&pattern, "/def$/");
	ZEPHIR_INIT_VAR(&subject);
	ZVAL_STRING(&subject, "abcdef");
	ZEPHIR_INIT_VAR(&_0);
	ZEPHIR_INIT_VAR(&_1);
	zephir_preg_match(&_1, &pattern, &subject, &_0, 0, 0 , 0 );
	ZEPHIR_INIT_VAR(&_2);
	zephir_preg_match(return_value, &pattern, &subject, &_2, 0, 0 , 0 );
	RETURN_MM();

}

PHP_METHOD(Test_Pregmatch, testWithoutReturns) {

	zval pattern, subject, matches, _0;
	zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
	zval *this_ptr = getThis();

	ZVAL_UNDEF(&pattern);
	ZVAL_UNDEF(&subject);
	ZVAL_UNDEF(&matches);
	ZVAL_UNDEF(&_0);

	ZEPHIR_MM_GROW();

	ZEPHIR_INIT_VAR(&matches);
	ZVAL_NULL(&matches);
	ZEPHIR_INIT_VAR(&pattern);
	ZVAL_STRING(&pattern, "/def$/");
	ZEPHIR_INIT_VAR(&subject);
	ZVAL_STRING(&subject, "abcdef");
	ZEPHIR_INIT_VAR(&_0);
	zephir_preg_match(&_0, &pattern, &subject, &matches, 0, 0 , 0 );
	RETURN_CCTOR(&matches);

}

PHP_METHOD(Test_Pregmatch, testWithoutMatches) {

	zval pattern, subject, matched, _0;
	zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
	zval *this_ptr = getThis();

	ZVAL_UNDEF(&pattern);
	ZVAL_UNDEF(&subject);
	ZVAL_UNDEF(&matched);
	ZVAL_UNDEF(&_0);

	ZEPHIR_MM_GROW();

	ZEPHIR_INIT_VAR(&pattern);
	ZVAL_STRING(&pattern, "/def$/");
	ZEPHIR_INIT_VAR(&subject);
	ZVAL_STRING(&subject, "abcdef");
	ZEPHIR_INIT_VAR(&_0);
	ZEPHIR_INIT_VAR(&matched);
	zephir_preg_match(&matched, &pattern, &subject, &_0, 0, 0 , 0 );
	RETURN_CCTOR(&matched);

}

PHP_METHOD(Test_Pregmatch, testPregMatchAll) {

	zval pattern, subject, results;
	zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
	zval *this_ptr = getThis();

	ZVAL_UNDEF(&pattern);
	ZVAL_UNDEF(&subject);
	ZVAL_UNDEF(&results);

	ZEPHIR_MM_GROW();

	ZEPHIR_INIT_VAR(&pattern);
	ZVAL_STRING(&pattern, "/def$/");
	ZEPHIR_INIT_VAR(&subject);
	ZVAL_STRING(&subject, "abcdef");
	ZEPHIR_INIT_VAR(&results);
	array_init(&results);
	zephir_preg_match(return_value, &pattern, &subject, &results, 1, 0 , 0 );
	RETURN_MM();

}

PHP_METHOD(Test_Pregmatch, testPregMatchFallback) {

	zval pattern, subject, matches;
	zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
	zval *this_ptr = getThis();

	ZVAL_UNDEF(&pattern);
	ZVAL_UNDEF(&subject);
	ZVAL_UNDEF(&matches);

	ZEPHIR_MM_GROW();

	ZEPHIR_INIT_VAR(&matches);
	ZVAL_NULL(&matches);
	ZEPHIR_INIT_NVAR(&matches);
	array_init(&matches);
	ZEPHIR_INIT_VAR(&pattern);
	ZVAL_STRING(&pattern, "/def$/");
	ZEPHIR_INIT_VAR(&subject);
	ZVAL_STRING(&subject, "abcdef");
	zephir_preg_match(return_value, &pattern, &subject, &matches, 0, 0 , 0 );
	RETURN_MM();

}

PHP_METHOD(Test_Pregmatch, testPregMatch2Params) {

	zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
	zval *pattern, pattern_sub, *subject, subject_sub, _0;
	zval *this_ptr = getThis();

	ZVAL_UNDEF(&pattern_sub);
	ZVAL_UNDEF(&subject_sub);
	ZVAL_UNDEF(&_0);

	ZEPHIR_MM_GROW();
	zephir_fetch_params(1, 2, 0, &pattern, &subject);

	ZEPHIR_INIT_VAR(&_0);
	zephir_preg_match(return_value, pattern, subject, &_0, 0, 0 , 0 );
	RETURN_MM();

}

PHP_METHOD(Test_Pregmatch, testPregMatch3Params) {

	zval *pattern, pattern_sub, *subject, subject_sub, *matches, matches_sub;
	zval *this_ptr = getThis();

	ZVAL_UNDEF(&pattern_sub);
	ZVAL_UNDEF(&subject_sub);
	ZVAL_UNDEF(&matches_sub);

	zephir_fetch_params_without_memory_grow(3, 0, &pattern, &subject, &matches);

	zephir_preg_match(return_value, pattern, subject, matches, 0, 0 , 0 );
	return;

}

PHP_METHOD(Test_Pregmatch, testPregMatch4Params) {

	zval *pattern, pattern_sub, *subject, subject_sub, *matches, matches_sub, *flags, flags_sub;
	zval *this_ptr = getThis();

	ZVAL_UNDEF(&pattern_sub);
	ZVAL_UNDEF(&subject_sub);
	ZVAL_UNDEF(&matches_sub);
	ZVAL_UNDEF(&flags_sub);

	zephir_fetch_params_without_memory_grow(4, 0, &pattern, &subject, &matches, &flags);

	zephir_preg_match(return_value, pattern, subject, matches, 0, zephir_get_intval(flags) , 0 );
	return;

}

PHP_METHOD(Test_Pregmatch, testPregMatch5Params) {

	zval *pattern, pattern_sub, *subject, subject_sub, *matches, matches_sub, *flags, flags_sub, *offset, offset_sub;
	zval *this_ptr = getThis();

	ZVAL_UNDEF(&pattern_sub);
	ZVAL_UNDEF(&subject_sub);
	ZVAL_UNDEF(&matches_sub);
	ZVAL_UNDEF(&flags_sub);
	ZVAL_UNDEF(&offset_sub);

	zephir_fetch_params_without_memory_grow(5, 0, &pattern, &subject, &matches, &flags, &offset);

	zephir_preg_match(return_value, pattern, subject, matches, 0, zephir_get_intval(flags) , zephir_get_intval(offset) );
	return;

}

/**
 * @link https://github.com/phalcon/zephir/issues/287
 */
PHP_METHOD(Test_Pregmatch, testPregMatchSaveMatches) {

	zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
	zval *str_param = NULL, *pattern_param = NULL, matches, _0;
	zval str, pattern;
	zval *this_ptr = getThis();

	ZVAL_UNDEF(&str);
	ZVAL_UNDEF(&pattern);
	ZVAL_UNDEF(&matches);
	ZVAL_UNDEF(&_0);

	ZEPHIR_MM_GROW();
	zephir_fetch_params(1, 2, 0, &str_param, &pattern_param);

	zephir_get_strval(&str, str_param);
	zephir_get_strval(&pattern, pattern_param);

	ZEPHIR_INIT_VAR(&matches);
	ZVAL_NULL(&matches);
	ZEPHIR_INIT_VAR(&_0);
	zephir_preg_match(&_0, &pattern, &str, &matches, 0, 0 , 0 );
	RETURN_CCTOR(&matches);

}

PHP_METHOD(Test_Pregmatch, testMatchAll) {

	zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
	zval *flags, flags_sub, text, matches, _0, _1, _2;
	zval *this_ptr = getThis();

	ZVAL_UNDEF(&flags_sub);
	ZVAL_UNDEF(&text);
	ZVAL_UNDEF(&matches);
	ZVAL_UNDEF(&_0);
	ZVAL_UNDEF(&_1);
	ZVAL_UNDEF(&_2);

	ZEPHIR_MM_GROW();
	zephir_fetch_params(1, 1, 0, &flags);

	ZEPHIR_INIT_VAR(&matches);
	array_init(&matches);
	ZEPHIR_INIT_VAR(&text);
	ZVAL_STRING(&text, "test1,test2");
	ZEPHIR_INIT_VAR(&_0);
	ZVAL_STRING(&_0, "/(test[0-9]+)/");
	ZEPHIR_INIT_VAR(&_1);
	ZEPHIR_INIT_VAR(&_2);
	ZVAL_STRING(&_2, "/(test[0-9]+)/");
	zephir_preg_match(&_1, &_2, &text, &matches, 1, zephir_get_intval(flags) , 0 );
	RETURN_CCTOR(&matches);

}

PHP_METHOD(Test_Pregmatch, testMatchAllInZep) {

	zval m1, m2, _0;
	zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
	zephir_fcall_cache_entry *_1 = NULL;
	zend_long ZEPHIR_LAST_CALL_STATUS;
	zval *this_ptr = getThis();

	ZVAL_UNDEF(&m1);
	ZVAL_UNDEF(&m2);
	ZVAL_UNDEF(&_0);

	ZEPHIR_MM_GROW();

	ZVAL_LONG(&_0, 1);
	ZEPHIR_CALL_METHOD(&m1, this_ptr, "testmatchall", &_1, 0, &_0);
	zephir_check_call_status();
	ZVAL_LONG(&_0, 2);
	ZEPHIR_CALL_METHOD(&m2, this_ptr, "testmatchall", &_1, 0, &_0);
	zephir_check_call_status();
	zephir_create_array(return_value, 2, 0);
	zephir_array_fast_append(return_value, &m1);
	zephir_array_fast_append(return_value, &m2);
	RETURN_MM();

}


text:
'''Trains CGAN on MNIST using Keras

CGAN is Conditional Generative Adversarial Nets.
This version of CGAN is similar to DCGAN. The difference mainly
is that the z-vector of geneerator is conditioned by a one-hot label
to produce specific fake images. The discriminator is trained to
discriminate real from fake images that are conditioned on
specific one-hot labels.

[1] Mirza, Mehdi, and Simon Osindero. "Conditional generative
adversarial nets." arXiv preprint arXiv:1411.1784 (2014).
'''

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import keras
from keras.layers import Activation, Dense, Input
from keras.layers import Conv2D, Flatten
from keras.layers import Reshape, Conv2DTranspose
from keras.layers import LeakyReLU
from keras.layers import BatchNormalization
from keras.optimizers import RMSprop
from keras.models import Model
from keras.datasets import mnist
from keras.utils import to_categorical

import numpy as np
import math
import matplotlib.pyplot as plt

def generator(inputs, y_labels, image_size):
    """Build a Generator Model

    Inputs are concatenated before Dense layer.
    Stacks of BN-ReLU-Conv2DTranpose to generate fake images
    Output activation is sigmoid instead of tanh in orig DCGAN.
    Sigmoid converges easily.

    # Arguments
        inputs (Layer): Input layer of the generator (the z-vector)
        y_labels (Layer): Input layer for one-hot vector to condition
            the inputs
        image_size: Target size of one side (assuming square image)

    # Returns
        Model: Generator Model
    """
    image_resize = image_size // 4
    kernel_size = 5
    layer_filters = [128, 64, 32, 1]

    x = keras.layers.concatenate([inputs, y_labels], axis=1)
    x = Dense(image_resize * image_resize * layer_filters[0])(x)
    x = Reshape((image_resize, image_resize, layer_filters[0]))(x)

    # x = Dense(image_resize * image_resize * layer_filters[0])(inputs)
    # x = Reshape((image_resize, image_resize, layer_filters[0]))(x)

    # y = Dense(image_resize * image_resize * 16)(y_labels)
    # y = Reshape((image_resize, image_resize, 16))(y)
    # x = keras.layers.concatenate([x, y])

    for filters in layer_filters:
        if filters > layer_filters[-2]:
            strides = 2
        else:
            strides = 1
        x = BatchNormalization()(x)
        x = Activation('relu')(x)
        x = Conv2DTranspose(filters=filters,
                            kernel_size=kernel_size,
                            strides=strides,
                            padding='same')(x)

    x = Activation('sigmoid')(x)
    generator = Model([inputs, y_labels], x, name='generator')
    return generator

def discriminator(inputs, y_labels, image_size):
    """Build a Discriminator Model

    Inputs are concatenated after Dense layer.
    Stacks of LeakyReLU-Conv2D to discriminate real from fake
    The network does not converge with BN so it is not used here
    unlike in DCGAN paper.

    # Arguments
        inputs (Layer): Input layer of the discriminator (the image)
        y_labels (Layer): Input layer for one-hot vector to condition
            the inputs
        image_size: Target size of one side (assuming square image)

    # Returns
        Model: Discriminator Model
    """
    kernel_size = 5
    layer_filters = [32, 64, 128, 256]

    x = inputs

    y = Dense(image_size * image_size)(y_labels)
    y = Reshape((image_size, image_size, 1))(y)
    x = keras.layers.concatenate([x, y])

    for filters in layer_filters:
        if filters == layer_filters[-1]:
            strides = 1
        else:
            strides = 2
        x = LeakyReLU(alpha=0.2)(x)
        x = Conv2D(filters=filters,
                   kernel_size=kernel_size,
                   strides=strides,
                   padding='same')(x)

    x = Flatten()(x)
    x = Dense(1)(x)
    x = Activation('sigmoid')(x)
    discriminator = Model([inputs, y_labels], x, name='discriminator')
    return discriminator

def train(models, data, params):
    """Train the Discriminator and Adversarial Networks

    Alternately train Discriminator and Adversarial networks by batch
    Discriminator is trained first with properly labelled real and fake images
    Adversarial is trained next with fake images pretending to be real
    Discriminator inputs are conditioned by train labels for real images,
    and random labels for fake images
    Adversarial inputs are conditioned by random labels
    Generate sample images per save_interval

    # Arguments
        models (list): Generator, Discriminator, Adversarial models
        data (list): x_train, y_train data
        params (list): Network parameters

    """
    generator, discriminator, adversarial = models
    x_train, y_train = data
    batch_size, latent_size, train_steps, num_labels = params
    save_interval = 500
    noise_input = np.random.uniform(-1.0, 1.0, size=[16, latent_size])
    noise_class = np.eye(num_labels)[np.random.choice(num_labels, 16)]
    for i in range(train_steps):
        # Random real images and their labels
        rand_indexes = np.random.randint(0, x_train.shape[0], size=batch_size)
        real_images = x_train[rand_indexes]
        real_labels = y_train[rand_indexes]
        # Generate fake images and their labels
        noise = np.random.uniform(-1.0, 1.0, size=[batch_size, latent_size])
        fake_labels = np.eye(num_labels)[np.random.choice(num_labels,
                                                           batch_size)]

        fake_images = generator.predict([noise, fake_labels])
        x = np.concatenate((real_images, fake_images))

        y_labels = np.concatenate((real_labels, fake_labels))

        # Label real and fake images
        y = np.ones([2 * batch_size, 1])
        y[batch_size:, :] = 0
        # Train the Discriminator network
        metrics = discriminator.train_on_batch([x, y_labels], y)
        loss = metrics[0]
        acc = metrics[1]
        log = "%d: [discriminator loss: %f, acc: %f]" % (i, loss, acc)

        # Generate random noise and fake labels
        noise = np.random.uniform(-1.0, 1.0, size=[batch_size, latent_size])
        fake_labels = np.eye(num_labels)[np.random.choice(num_labels,
                                                           batch_size)]
        # Label fake images as real
        y = np.ones([batch_size, 1])
        # Train the Adversarial network
        metrics = adversarial.train_on_batch([noise, fake_labels], y)
        loss = metrics[0]
        acc = metrics[1]
        log = "%s [adversarial loss: %f, acc: %f]" % (log, loss, acc)
        print(log)
        if (i + 1) % save_interval == 0:
            if (i + 1) == train_steps:
                show = True
            else:
                show = False
            plot_images(generator,
                        noise_input=noise_input,
                        noise_class=noise_class,
                        show=show,
                        step=(i + 1))

def plot_images(generator,
                noise_input,
                noise_class,
                show=False,
                step=0):
    """Generate fake images and plot them

    For visualization purposes, generate fake images given labels
    then plot them in a square grid

    # Arguments
        generator (Model): The Generator Model for fake images generation
        noise_input (ndarray): Array of z-vectors
        noise_class (ndarray): Array of labels
        show (bool): Whether to show plot or not
        step (int): Appended to filename of the save images

    """
    filename = "mnist_cgan_%d.png" % step
    images = generator.predict([noise_input, noise_class])
    print("Labels: ", np.argmax(noise_class, axis=1))
    plt.figure(figsize=(2.4, 2.4))
    num_images = images.shape[0]
    image_size = images.shape[1]
    rows = int(math.sqrt(noise_input.shape[0]))
    for i in range(num_images):
        plt.subplot(rows, rows, i + 1)
        image = images[i, :, :, :]
        image = np.reshape(image, [image_size, image_size])
        plt.imshow(image, cmap='gray')
        plt.axis('off')
    plt.savefig(filename)
    if show:
        plt.show()
    else:
        plt.close('all')

# MNIST dataset
(x_train, y_train), (_, _) = mnist.load_data()

image_size = x_train.shape[1]
x_train = np.reshape(x_train, [-1, image_size, image_size, 1])
x_train = x_train.astype('float32') / 255

num_labels = np.amax(y_train) + 1
y_train = to_categorical(y_train)

# Network parameters
# The latent or z vector is 100-dim
latent_size = 100
batch_size = 64
train_steps = 40000
lr = 0.0002
decay = 6e-8
input_shape = (image_size, image_size, 1)
label_shape = (num_labels, )

# Build Discriminator Model
inputs = Input(shape=input_shape, name='discriminator_input')
y_labels = Input(shape=label_shape, name='class_labels')

discriminator = discriminator(inputs, y_labels, image_size)
# [1] uses Adam, but discriminator converges easily with RMSprop
optimizer = RMSprop(lr=lr, decay=decay)
discriminator.compile(loss='binary_crossentropy',
                      optimizer=optimizer,
                      metrics=['accuracy'])
discriminator.summary()

# Build Generator Model
input_shape = (latent_size, )
inputs = Input(shape=input_shape, name='z_input')
generator = generator(inputs, y_labels, image_size)
generator.summary()

# Build Adversarial Model = Generator + Discriminator
optimizer = RMSprop(lr=lr*0.5, decay=decay*0.5)
discriminator.trainable = False
adversarial = Model([inputs, y_labels],
                    discriminator([generator([inputs, y_labels]), y_labels]),
                    name='cgan')
adversarial.compile(loss='binary_crossentropy',
                    optimizer=optimizer,
                    metrics=['accuracy'])
adversarial.summary()

# Train Discriminator and Adversarial Networks
models = (generator, discriminator, adversarial)
data = (x_train, y_train)
params = (batch_size, latent_size, train_steps, num_labels)
train(models, data, params)

redpajama_set_name: RedPajamaGithub


text:
import { FocusableOption, FocusOptions, FocusOrigin } from '@angular/cdk/a11y';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { hasModifierKey } from '@angular/cdk/keycodes';
import {
  AfterViewChecked,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  Directive,
  ElementRef,
  EventEmitter,
  Inject,
  Input,
  OnDestroy,
  Optional,
  Output,
  QueryList,
  ViewEncapsulation,
} from '@angular/core';
import { fromEvent, Subject, Subscription } from 'rxjs';
import { BooleanInput, Key } from '../../../utils';
import { NovoOptgroup, NovoOptgroupBase, NOVO_OPTGROUP } from './optgroup.component';
import { NovoOptionParentComponent, NOVO_OPTION_PARENT_COMPONENT } from './option-parent';

/**
 * Option IDs need to be unique across components, so this counter exists outside of
 * the component definition.
 */
let _uniqueIdCounter = 0;

/** Event object emitted by NovoOption when selected or deselected. */
export class NovoOptionSelectionChange {
  constructor(
    /** Reference to the option that emitted the event. */
    public source: NovoOptionBase,
    /** Whether the change in the option's value was a result of a user action. */
    public isUserInput = false,
  ) {}
}

@Directive()
export class NovoOptionBase implements FocusableOption, AfterViewChecked, OnDestroy {
  private _selected = false;
  private _active = false;
  private _disabled = false;
  private _mostRecentViewValue = '';
  private _clickCapture: Subscription;
  private _clickPassive: Subscription;

  /** TODO: deprecate maybe, check support for table headers */
  @BooleanInput()
  @Input()
  keepOpen: boolean = false;

  @BooleanInput()
  @Input()
  novoInert: boolean = false;

  /** If there is no parent then nothing is managing the selection. */
  get selectable() {
    return this._parent;
  }

  /** Whether the wrapping component is in multiple selection mode. */
  get multiple() {
    return this._parent && this._parent.multiple;
  }

  /** The form value of the option. */
  @Input() value: any;

  /** The unique ID of the option. */
  @Input() id: string = `novo-option-${_uniqueIdCounter++}`;

  /** Whether the option is disabled. */
  @Input()
  get disabled() {
    return (this.group && this.group.disabled) || this._disabled;
  }
  set disabled(value: any) {
    this._disabled = coerceBooleanProperty(value);
  }

  @Input()
  get selected() {
    return this._selected;
  }
  set selected(value: any) {
    this._selected = coerceBooleanProperty(value);
  }

  /** Event emitted when the option is selected or deselected. */
  // tslint:disable-next-line:no-output-on-prefix
  @Output() readonly onSelectionChange = new EventEmitter<NovoOptionSelectionChange>();

  /** Emits when the state of the option changes and any parents have to be notified. */
  readonly _stateChanges = new Subject<void>();

  constructor(
    private _element: ElementRef<HTMLElement>,
    private _changeDetectorRef: ChangeDetectorRef,
    @Optional() @Inject(NOVO_OPTION_PARENT_COMPONENT) private _parent: NovoOptionParentComponent,
    @Optional() @Inject(NOVO_OPTGROUP) readonly group: NovoOptgroupBase,
  ) {
    // (click) is overridden when defined by user.
    this._clickCapture = fromEvent<MouseEvent>(this._element.nativeElement, 'click', { capture: true }).subscribe((evt: MouseEvent) => {
      this._handleDisabledClick(evt);
    });
    this._clickPassive = fromEvent<MouseEvent>(this._element.nativeElement, 'click').subscribe((evt: MouseEvent) => {
      setTimeout(() => this._handlePassiveClick(evt));
    });
  }

  /**
   * Whether or not the option is currently active and ready to be selected.
   * An active option displays styles as if it is focused, but the
   * focus is actually retained somewhere else. This comes in handy
   * for components like autocomplete where focus must remain on the input.
   */
  get active(): boolean {
    return this._active;
  }

  /**
   * The displayed value of the option. It is necessary to show the selected option in the
   * select's trigger.
   */
  get viewValue(): string {
    return (this._getHostElement().textContent || '').trim();
  }

  /** Selects the option. */
  select(): void {
    if (!this._selected) {
      this._selected = true;
      this._changeDetectorRef.markForCheck();
      // this._emitSelectionChangeEvent();
    }
  }

  /** Deselects the option. */
  deselect(): void {
    if (this._selected) {
      this._selected = false;
      this._changeDetectorRef.markForCheck();
      // this._emitSelectionChangeEvent();
    }
  }

  /** Sets focus onto this option. */
  focus(_origin?: FocusOrigin, options?: FocusOptions): void {
    // Note that we aren't using `_origin`, but we need to keep it because some internal consumers
    // use `NovoOption` in a `FocusKeyManager` and we need it to match `FocusableOption`.
    const element = this._getHostElement();

    if (typeof element.focus === 'function') {
      element.focus(options);
    }
  }

  /**
   * This method sets display styles on the option to make it appear
   * active. This is used by the ActiveDescendantKeyManager so key
   * events will display the proper options as active on arrow key events.
   */
  setActiveStyles(): void {
    if (!this._active) {
      this._active = true;
      this._changeDetectorRef.markForCheck();
    }
  }

  /**
   * This method removes display styles on the option that made it appear
   * active. This is used by the ActiveDescendantKeyManager so key
   * events will display the proper options as active on arrow key events.
   */
  setInactiveStyles(): void {
    if (this._active) {
      this._active = false;
      this._changeDetectorRef.markForCheck();
    }
  }

  /** Gets the label to be used when determining whether the option should be focused. */
  getLabel(): string {
    return this.viewValue;
  }

  _handleDisabledClick(event: MouseEvent) {
    if (this.disabled) {
      event.preventDefault();
      event.stopPropagation();
      event.stopImmediatePropagation();
    }
  }
  _handlePassiveClick(event: MouseEvent) {
    if (!this.novoInert) {
      this._selectViaInteraction();
    }
  }

  /** Ensures the option is selected when activated from the keyboard. */
  _handleKeydown(event: KeyboardEvent): void {
    if (event.target instanceof HTMLInputElement && event.key === Key.Enter) {
      this._emitSelectionChangeEvent(!this.keepOpen);
    } else if (
      !(event.target instanceof HTMLInputElement) &&
      (event.key === Key.Enter || event.key === Key.Space) &&
      !hasModifierKey(event)
    ) {
      this._selectViaInteraction();
      // Prevent the page from scrolling down and form submits.
      event.preventDefault();
    }
  }

  /**
   * `Selects the option while indicating the selection came from the user. Used to
   * determine if the select's view -> model callback should be invoked.`
   */
  _selectViaInteraction(): void {
    if (!this.disabled) {
      this._selected = this.multiple ? !this._selected : true;
      this._changeDetectorRef.markForCheck();
      this._emitSelectionChangeEvent(!this.keepOpen);
    }
  }

  /**
   * Force a click event
   */
  _clickViaInteraction(): void {
    if (!this.disabled) {
      this._element.nativeElement.click();
    }
  }

  /**
   * Gets the `aria-selected` value for the option. We explicitly omit the `aria-selected`
   * attribute from single-selection, unselected options. Including the `aria-selected="false"`
   * attributes adds a significant amount of noise to screen-reader users without providing useful
   * information.
   */
  _getAriaSelected(): boolean | null {
    return this.selected || (this.multiple ? false : null);
  }

  /** Returns the correct tabindex for the option depending on disabled state. */
  _getTabIndex(): string {
    return this.disabled ? '-1' : '0';
  }

  /** Gets the host DOM element. */
  _getHostElement(): HTMLElement {
    return this._element.nativeElement;
  }

  ngAfterViewChecked() {
    // Since parent components could be using the option's label to display the selected values
    // (e.g. `novo-select`) and they don't have a way of knowing if the option's label has changed
    // we have to check for changes in the DOM ourselves and dispatch an event. These checks are
    // relatively cheap, however we still limit them only to selected options in order to avoid
    // hitting the DOM too often.
    if (this._selected) {
      const viewValue = this.viewValue;

      if (viewValue !== this._mostRecentViewValue) {
        this._mostRecentViewValue = viewValue;
        this._stateChanges.next();
      }
    }
  }

  ngOnDestroy() {
    this._stateChanges.complete();
    this._clickCapture.unsubscribe();
    this._clickPassive.unsubscribe();
  }

  /** Emits the selection change event. */
  private _emitSelectionChangeEvent(isUserInput = false): void {
    this.onSelectionChange.emit(new NovoOptionSelectionChange(this, isUserInput));
  }
}

/**
 * Single option inside of a `<novo-select>` element.
 */
@Component({
  selector: 'novo-option',
  exportAs: 'novoOption',
  host: {
    role: 'option',
    '[id]': 'id',
    '[attr.tabindex]': '_getTabIndex()',
    '[attr.aria-selected]': '_getAriaSelected()',
    '[attr.aria-disabled]': 'disabled.toString()',
    '[class.novo-active]': 'active',
    '[class.novo-selected]': 'selectable && selected',
    '[class.novo-option-multiple]': 'multiple',
    '[class.novo-option-disabled]': 'disabled',
    '[class.novo-option-inert]': 'novoInert',
    '(keydown)': '_handleKeydown($event)',
    class: 'novo-option novo-focus-indicator',
  },
  inputs: ['selected', 'keepOpen', 'novoInert', 'value', 'disabled'],
  styleUrls: ['option.component.scss'],
  templateUrl: 'option.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class NovoOption extends NovoOptionBase {
  constructor(
    element: ElementRef<HTMLElement>,
    changeDetectorRef: ChangeDetectorRef,
    @Optional() @Inject(NOVO_OPTION_PARENT_COMPONENT) parent: NovoOptionParentComponent,
    @Optional() @Inject(NOVO_OPTGROUP) group: NovoOptgroup,
  ) {
    super(element, changeDetectorRef, parent, group);
  }
}

/**
 * Counts the amount of option group labels that precede the specified option.
 * @param optionIndex Index of the option at which to start counting.
 * @param options Flat list of all of the options.
 * @param optionGroups Flat list of all of the option groups.
 * @docs-private
 */
export function _countGroupLabelsBeforeOption(
  optionIndex: number,
  options: QueryList<NovoOption>,
  optionGroups: QueryList<NovoOptgroup>,
): number {
  if (optionGroups.length) {
    let optionsArray = options.toArray();
    let groups = optionGroups.toArray();
    let groupCounter = 0;

    for (let i = 0; i < optionIndex + 1; i++) {
      if (optionsArray[i].group && optionsArray[i].group === groups[groupCounter]) {
        groupCounter++;
      }
    }

    return groupCounter;
  }

  return 0;
}

/**
 * Determines the position to which to scroll a panel in order for an option to be into view.
 * @param optionOffset Offset of the option from the top of the panel.
 * @param optionHeight Height of the options.
 * @param currentScrollPosition Current scroll position of the panel.
 * @param panelHeight Height of the panel.
 * @docs-private
 */
export function _getOptionScrollPosition(
  optionOffset: number,
  optionHeight: number,
  currentScrollPosition: number,
  panelHeight: number,
): number {
  if (optionOffset < currentScrollPosition) {
    return optionOffset;
  }

  if (optionOffset + optionHeight > currentScrollPosition + panelHeight) {
    return Math.max(0, optionOffset - panelHeight + optionHeight);
  }

  return currentScrollPosition;
}


text: cloud management


text:
/** @constructor */
ScalaJS.c.scala_runtime_ShortRef = (function() {
  ScalaJS.c.java_lang_Object.call(this);
  this.elem$1 = 0
});
ScalaJS.c.scala_runtime_ShortRef.prototype = new ScalaJS.inheritable.java_lang_Object();
ScalaJS.c.scala_runtime_ShortRef.prototype.constructor = ScalaJS.c.scala_runtime_ShortRef;
ScalaJS.c.scala_runtime_ShortRef.prototype.elem__S = (function() {
  return this.elem$1
});
ScalaJS.c.scala_runtime_ShortRef.prototype.elem$und$eq__S__V = (function(x$1) {
  this.elem$1 = x$1
});
ScalaJS.c.scala_runtime_ShortRef.prototype.toString__T = (function() {
  return ScalaJS.modules.scala_scalajs_runtime_RuntimeString().valueOf__I__T(this.elem__S())
});
ScalaJS.c.scala_runtime_ShortRef.prototype.init___S = (function(elem) {
  this.elem$1 = elem;
  ScalaJS.c.java_lang_Object.prototype.init___.call(this);
  return this
});
ScalaJS.c.scala_runtime_ShortRef.prototype.elem$und$eq__S__ = (function(x$1) {
  return ScalaJS.bV(this.elem$und$eq__S__V(x$1))
});
ScalaJS.c.scala_runtime_ShortRef.prototype.elem__ = (function() {
  return ScalaJS.bS(this.elem__S())
});
/** @constructor */
ScalaJS.inheritable.scala_runtime_ShortRef = (function() {
  /*<skip>*/
});
ScalaJS.inheritable.scala_runtime_ShortRef.prototype = ScalaJS.c.scala_runtime_ShortRef.prototype;
ScalaJS.is.scala_runtime_ShortRef = (function(obj) {
  return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_runtime_ShortRef)))
});
ScalaJS.as.scala_runtime_ShortRef = (function(obj) {
  if ((ScalaJS.is.scala_runtime_ShortRef(obj) || (obj === null))) {
    return obj
  } else {
    ScalaJS.throwClassCastException(obj, "scala.runtime.ShortRef")
  }
});
ScalaJS.isArrayOf.scala_runtime_ShortRef = (function(obj, depth) {
  return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_runtime_ShortRef)))
});
ScalaJS.asArrayOf.scala_runtime_ShortRef = (function(obj, depth) {
  if ((ScalaJS.isArrayOf.scala_runtime_ShortRef(obj, depth) || (obj === null))) {
    return obj
  } else {
    ScalaJS.throwArrayCastException(obj, "Lscala.runtime.ShortRef;", depth)
  }
});
ScalaJS.data.scala_runtime_ShortRef = new ScalaJS.ClassTypeData({
  scala_runtime_ShortRef: 0
}, false, "scala.runtime.ShortRef", ScalaJS.data.java_lang_Object, {
  scala_runtime_ShortRef: 1,
  java_io_Serializable: 1,
  java_lang_Object: 1
});
ScalaJS.c.scala_runtime_ShortRef.prototype.$classData = ScalaJS.data.scala_runtime_ShortRef;
//@ sourceMappingURL=ShortRef.js.map


text:
#import <CFNetwork/__NSCFURLSessionDataTask.h>

// Not exported
@interface __NSCFURLSessionUploadTask : __NSCFURLSessionDataTask
{
}

@end


text:
layout: post
title: "Peer Pressure"
tags:
- Self
categories:
- Learn
thumbnail_path: blog/personal/peer-pressure.jpg
---

Before the social media (about 15 years ago), I saw peer pressure as a good thing. The only source of peer pressure came from my friends - who were mostly like me. I'd be studying harder after a phone call before the exams to my friend due to peer pressure. Sometimes, I might even be encouraged to take a break and play a game of Cricket before the exams - with no guilt. However, growing up and the social media has changed the dynamics of peer pressure a lot!

{% include figure.html path="blog/personal/peer-pressure.jpg" alt="Peer Pressure" caption="Source" url="https://www.edutopia.org/article/how-peer-pressure-undermines-success-youki-terada" %}

- A lot of people are buying houses, is it the right time for me to buy one?
- I see photos on Instagram and Facebook about people traveling the world - should I be traveling more?
- My connections on LinkedIn have moved jobs or have got promoted - maybe I should work harder?

And the comparisons are endless. After some thinking and talking to wise friends, a few thoughts -

- Just because the people around you are doing something, it cannot be the only reason for you to follow them. It might work for them but for various reasons it might not work for you.
- The world tour vacation might not be as life changing as you had imagined and getting more money wouldn't solve any your problems as you had thought.
- The 4 step decision process from the book Decisive seem to work well for most situations. ([This Infographic](http://learnographics.com/decision-making.html) is a good summary of the book.)
	1. Widening your options.
	2. Reality test the assumptions.
	3. Attain distance before deciding.
	4. Prepare to be wrong.

{% include figure.html path="blog/personal/be-yourself.jpg" alt="Keep calm and be yourself" %}


text:
import ttsutil
import os.path

import urllib
import json

import untangle

import argparse
import shutil

import PIL.Image

cards={}

debug=True

# TTS util overrides
def make_filename(image):
  return ttsutil.make_cache_filename(image,"ANR")

def make_cache_dir():
  ttsutil.make_cache_dir("ANR")

def build_chest_file(deck,base_url):
  chest=ttsutil.build_chest_file(deck,base_url)
  if deck['side']=='Corp':
    chest['ObjectStates'][0]['Transform']['rotY']=90

  # check for special exceptions
  if deck['jinteki-biotech']:
    chest['ObjectStates'][0]['CustomDeck']['2']= {
      "FaceURL":base_url+'08012-id.jpg',
      "BackURL":base_url+'08012-id-back.jpg'
    }
    chest['ObjectStates'][0]['DeckIDs']=[200,201,202]+chest['ObjectStates'][0]['DeckIDs']

  return chest

def get_runner_back():
    filename = os.path.join("cards","ANR","runner-back.png")
    if not os.path.isfile(filename):
	print("No runner back found. Downloading")
        data=urllib.urlopen("http://vignette1.wikia.nocookie.net/ancur/images/a/a0/Runner_back.png/revision/latest").read()
        fh=open(filename,'wb')
        fh.write(data)
        fh.close()
    return ttsutil.load_image_at_size(filename)

def get_corp_back():
    filename = os.path.join("cards","ANR","corp-back.png")
    if not os.path.isfile(filename):
	print("No corp back found. Downloading")
        data=urllib.urlopen("http://vignette3.wikia.nocookie.net/ancur/images/c/c3/Corp_back.png/revision/latest").read()
        fh=open(filename,'wb')
        fh.write(data)
        fh.close()
    return ttsutil.load_image_at_size(filename)

def get_card(id):
    if not cards.has_key(id):
        filename = make_filename(id+".json")
        if not os.path.isfile(filename):
            make_cache_dir()
            print "Downloading card id: %s" % id
            data=urllib.urlopen("http://netrunnerdb.com/api/card/%s" % id).read()
            fh=open(filename,'w')
            fh.write(data)
            fh.close()
        data=open(filename).read()
        j_data=json.loads(data)
        cards[id]=j_data[0]
        image_filename = make_filename(id+".png")
        if not os.path.isfile(image_filename):
          make_cache_dir()
          print "Downloading card image to: %s" % image_filename
          data=urllib.urlopen("http://netrunnerdb.com/%s" % j_data[0]['imagesrc']).read()
          fh=open(image_filename,'wb')
          fh.write(data)
          fh.close()
    return cards[id]

def get_flip_image(id,idx):
    if id!='08012':
        print("Unknown flip id %s" % id )
        return
    if idx!='A' and idx!='B' and idx!='C':
        print("Unknown flip index %s for %s" % (idx,id) )
        return
    filename = make_filename(id+idx+".png")
    if not os.path.isfile(filename):
        make_cache_dir()
        print "Downloading card image to: %s" % filename
        # TODO: figure out a better way of doing this.
        data=None
        if idx=='A':
            data=urllib.urlopen("http://vignette2.wikia.nocookie.net/ancur/images/9/96/08012A.png").read()
        if idx=='B':
            data=urllib.urlopen("http://vignette3.wikia.nocookie.net/ancur/images/6/6a/08012B.png").read()
        if idx=='C':
            data=urllib.urlopen("http://vignette3.wikia.nocookie.net/ancur/images/a/a1/08012C.png").read()
        fh=open(filename,'wb')
        fh.write(data)
        fh.close()
    return ttsutil.load_image_at_size(filename)

def print_deck(deck):
    print('''
    Deck: %s
    Filename: %s
    Side: %s
    Size: %s
    ''' % ( deck['name'],deck['filename'],deck['side'],ttsutil.count_deck(deck)))

def load_netrunnerdb_deck(id):
    print("Attempting to load deck %s from netrunnerdb" % id )
    data=urllib.urlopen("http://netrunnerdb.com/api/decklist/%s" % id).read()
    j_data=json.loads(data)

    deck={
        'name':j_data['name'],
        'cards':[],
        'filename':ttsutil.sanitise_filename(j_data['name']),
        'jinteki-biotech':False
    }

    for id in j_data['cards'].keys():
        card=get_card(id)
        if card['type_code']=='identity':
            if id=='08012':
                deck['jinteki-biotech']=True
            else:
                deck['cards'].insert(0,(id,1))
            deck['side']=card['side']
        else:
            deck['cards'].append((id,j_data['cards'][id]))

    if debug:
        print_deck(deck)
    return deck

def load_octgn_deck(filename):
    print("Attempting to load octgn deck from %s" % filename )
    deckXML = untangle.parse(filename)
    deck={
        'cards':[],
        'name':os.path.splitext(os.path.basename(filename))[0],
        'jinteki-biotech':False
    }
    # add id
    id=deckXML.deck.section[0].card['id'][-5:]
    if id=='08012':
        deck['jinteki-biotech']=True
    else:
        deck['cards'].append((id,1))
    idcard=get_card(id)
    deck['side']=idcard['side']
    deck['filename']=ttsutil.sanitise_filename(deck['name'])
    # add the rest
    for card in deckXML.deck.section[1].card:
        deck['cards'].append((card['id'][-5:],int(card['qty'])))

    if debug:
        print_deck(deck)
    return deck

def build_08012_image():
    # build mini-deck for flip ID Jinteki Biotech
    im = PIL.Image.new('RGBA',(10*ttsutil.imgW,7*ttsutil.imgH),(0,0,0,0))
    offX=0
    image=get_flip_image('08012','A')
    im.paste(image,(offX,0))
    offX+=ttsutil.imgW
    image=get_flip_image('08012','B')
    im.paste(image,(offX,0))
    offX+=ttsutil.imgW
    image=get_flip_image('08012','C')
    im.paste(image,(offX,0))
    back=ttsutil.get_cache_image('08012','ANR')
    im.paste(back,(2700,2514))
    return im

def load_anr_back(deck):
    back=None
    if deck['back_filename']:
        print "loading custom back %s" % deck['back_filename']
        back=ttsutil.load_image_at_size(deck['back_filename'])
    else:
        if deck['side']=='Corp':
            back=get_corp_back()
        else:
            back=get_runner_back()
    return back

def write_files(deck,base_url,write_local,local_target,install):
  chest=build_chest_file(deck,base_url)
  back_image=load_anr_back(deck)

  ttsutil.write_files(deck,chest,base_url,write_local,local_target,install,back_image,"ANR")

  if not deck['jinteki-biotech']:
    return

  jbDeckImage=build_08012_image()
  jbBackImage=ttsutil.get_cache_image('08012','ANR')

  basefilename=deck['filename']
  jbDeckFilename=os.path.join(local_target,"08012-id.jpg")
  jbBackFilename=os.path.join(local_target,"08012-id-back.jpg")

  if write_local:
    print("Writing %s" % jbDeckFilename)
    print("Writing %s" % jbBackFilename)
    jbDeckImage.save(jbDeckFilename,'JPEG')
    jbBackImage.save(jbBackFilename,'JPEG')

  if install:
    ttsJbDeckFilename=ttsutil.make_tts_image_filename(base_url+jbDeckFilename)
    ttsJbBackFilename=ttsutil.make_tts_image_filename(base_url+jbBackFilename)
    print("Writing %s" % ttsJbDeckFilename)
    jbDeckImage.save(ttsJbDeckFilename,'JPEG')
    print("Writing %s" % ttsJbBackFilename)
    jbBackImage.save(ttsJbBackFilename,'JPEG')

def main():
    parser = argparse.ArgumentParser(description="Create a set of files for loading ANR decks into TableTop Simulator")
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument("-n","--netrunnerdb",metavar="ID",help="Load deck from netrunnerdb using given ID.")
    group.add_argument("-o","--octgn",metavar="file",help="Load the given o8n file (in octgn format).")
    parser.add_argument("-b","--back",metavar="backgroundFile",help="Override default back with given file.")
    parser.add_argument("-i","--install",action="store_true",help="Install files into local TTS install.")
    parser.add_argument("-w","--writelocal",action="store_true",help="Write files into the current directory.")
    parser.add_argument("-u","--url",help="Base url for where the images will be made availiable")
    args = parser.parse_args()

    if not (args.install or args.url):
        print("Warning: Neither install (-i) or url (-u) has been specified. You probably don't want to do this.")

    if not (args.install or args.writelocal):
        parser.error("At least one of -i or -w is required.")

    baseurl=args.url or "null://"

    if baseurl.startswith('file') and not baseurl.endswith(os.sep):
        baseurl+=os.sep
    if baseurl.startswith('http') and not baseurl.endswith('/'):
        baseurl+='/'

    deck=None
    if args.netrunnerdb != None:
        deck=load_netrunnerdb_deck(args.netrunnerdb)
    if args.octgn != None:
        deck=load_octgn_deck(args.octgn)

    deck['back_filename']=args.back
    write_files(deck,baseurl,args.writelocal,"",args.install)

if __name__ == "__main__":
    main()


text:
class Manage::AssignmentsController < AuthenticatedController

  before_filter :find_project
  before_action :set_assignment, only: [:show, :edit, :update, :destroy]
  def index
    authorize! :read, Assignment
    @assignments = @task.assignments.includes(:user)
  end

  # GET /works/1
  # GET /works/1.json
  def show
    authorize! :read, @assignment
  end

  # GET /works/new
  def new
    authorize! :create, Assignment
    @assignment = Assignment.new
    @url = project_task_assignments_path(@project,@task)
    set_users
  end

  # GET /works/1/edit
  def edit
    authorize! :update, @assignment
    @url = project_task_assignment_path(@project,@task,@assignment)
    set_users
    @users << @assignment.user
  end

  # POST /works
  # POST /works.json
  def create
    authorize! :create, Assignment
    @assignment = Assignment.new(assignment_params)
    @assignment.task = @task
    # @assignment.creator = current_user
    # @task.work = @work

    respond_to do |format|
      if @assignment.save!
        format.html { redirect_to project_task_assignments_path(@project,@task), notice: 'Assignment was successfully created.' }
        format.json { render action: 'show', status: :created, location: project_task_assignments_url(@project,@task) }
      else
        set_users
        @url = project_task_assignments_path(@project,@task)
        format.html { render action: 'new' }
        format.json { render json: @assignment.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /works/1
  # PATCH/PUT /works/1.json
  def update

    authorize! :update, @assignment
    respond_to do |format|
      if @assignment.update(assignment_params)
        format.html { redirect_to project_task_assignments_path(@project,@task), notice: 'Assignment was successfully updated.' }
        format.json { head :no_content }
      else
        url = project_task_assignment_path(@project,@task,@assignment)
        set_users
        @users << @assignment.user
        format.html { render action: 'edit' }
        format.json { render json: @assignment.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /works/1
  # DELETE /works/1.json
  def destroy
    authorize! :destroy, @assignment
    @assignment.destroy
    respond_to do |format|
      format.html { redirect_to project_task_assignments_path(@project,@task) }
      format.json { head :no_content }
    end
  end

  private
  def find_project
    @project = Project.find(params[:project_id])
    @task = @project.tasks.find(params[:task_id])
  end
  def set_assignment
    @assignment = @task.assignments.includes(:user).find(params[:id])
  end
  def assignment_params
    params.require(:assignment).permit(:user_id)
  end
  def set_users
    users_used = @task.assignments.map(&:user_id)
    unless users_used.empty?
      @users = User.where('id not in (?)', users_used)
    else
      @users = User.all
    end
  end
end


text:
'use strict';
const cluster = require('cluster');
const request = require('request');

let _statsForSecond = null;
const resetStats = () => {
    _statsForSecond = {
        code: {
            '1': 0,
            '2': 0,
            '3': 0,
            '4': 0,
            '5': 0
        },
        err: 0,
        to: 0,
        body: 0,

        cnt: 0,
        time: 0,
        min: Infinity,
        max: 0
    }
};
resetStats();

const _requests = [];
let _requestCount = 0;

process.on('message', (msg) => {
    if (!(msg && msg.type)) {
        console.error('invalid message');
        console.error(msg);
        return;
    }

    switch (msg.type) {
        case 'setup' :
            SETUP(msg.data);
            break;
        case 'req':
            DO_REQUESTS_FOR_SECOND(msg.data);
            break;
        case 'stats':
            STATS();
            break;
        case 'raw':
            RAW();
            break;
        default:
            throw 'unknown message';
    }
});

let concurrent = null;
let requestOptions = null;
let config = null;

const SETUP = (data) => {
    config = data;
    requestOptions = {
        url: config.url,
        method: config.method,
        timeout: config.timeout
    }
    concurrent = data.concurrentPerCPU;

    if (config.method === "POST") {
        let body = config.body;

        if (!requestOptions.headers) requestOptions.headers = {};
        requestOptions.headers['Content-Type'] = 'application/json';
        requestOptions.headers['Content-Length'] = body.length;

        requestOptions.body = body;
    }
};

const STATS = () => {
    process.send({ type: 'stats', data: _statsForSecond, req: _requestCount });
    resetStats();
};

const RAW = () => {
    process.send({ type: 'raw', data: _requests });
};

const DO_REQUESTS_FOR_SECOND = (second) => {
    for (let i = 0; i < concurrent; i++) {
        _requests.push({
            code: 0,
            time: 0,
            start: 0,
            sec: second,
            err: 0,
            to: 0,
            body: 0
        });
        setTimeout(_doSingleRequest.bind(null, i + second * concurrent), i / concurrent * 1000);
    }
};

const _doSingleRequest = (idx) => {
    _requestCount++;

    const req = _requests[idx];
    req.start = Date.now();

    request(requestOptions, (err, http, data) => {
        _requestCount--;

        const req = _requests[idx];
        req.time = Date.now() - req.start;
        if (!err) {
            _statsForSecond.time += req.time;
            _statsForSecond.cnt++;

            if (req.time < _statsForSecond.min) {
                _statsForSecond.min = req.time;
            }
            if (req.time > _statsForSecond.max) {
                _statsForSecond.max = req.time;
            }
        }

        if (err && err.code === 'ETIMEDOUT') {
            _statsForSecond.to++;
            return req.to = 1;
        }

        if (err) {
            config.verbose.e && console.error(err);
            _statsForSecond.err++;
            return req.err = 1;
        }

        req.code = http.statusCode;

        _statsForSecond.code[req.code.toString()[0]]++;
        config.verbose.c && console.log('HTTP:', req.code);

        config.verbose.b && console.log('BODY:', data);

        req.body = data.toString().trim().length ? 1 : 0;
        _statsForSecond.body += req.body;
    });
};


text:
<?php

final class ManiphestExcelDefaultFormat extends ManiphestExcelFormat {

  public function getName() {
    return pht('Default');
  }

  public function getFileName() {
    return 'maniphest_tasks_'.date('Ymd');
  }

  /**
   * @phutil-external-symbol class PHPExcel
   * @phutil-external-symbol class PHPExcel_IOFactory
   * @phutil-external-symbol class PHPExcel_Style_NumberFormat
   * @phutil-external-symbol class PHPExcel_Cell_DataType
   */
  public function buildWorkbook(
    PHPExcel $workbook,
    array $tasks,
    array $handles,
    PhabricatorUser $user) {

    $sheet = $workbook->setActiveSheetIndex(0);
    $sheet->setTitle(pht('Tasks'));

    $widths = array(
      null,
      15,
      null,
      10,
      15,
      15,
      60,
      30,
      20,
      100,
    );

    foreach ($widths as $col => $width) {
      if ($width !== null) {
        $sheet->getColumnDimension($this->col($col))->setWidth($width);
      }
    }

    $status_map = ManiphestTaskStatus::getTaskStatusMap();
    $pri_map = ManiphestTaskPriority::getTaskPriorityMap();

    $date_format = null;

    $rows = array();
    $rows[] = array(
      pht('ID'),
      pht('Owner'),
      pht('Status'),
      pht('Priority'),
      pht('Date Created'),
      pht('Date Updated'),
      pht('Title'),
      pht('Tags'),
      pht('URI'),
      pht('Description'),
    );

    $is_date = array(
      false,
      false,
      false,
      false,
      true,
      true,
      false,
      false,
      false,
      false,
    );

    $header_format = array(
      'font'  => array(
        'bold' => true,
      ),
    );

    foreach ($tasks as $task) {
      $task_owner = null;
      if ($task->getOwnerPHID()) {
        $task_owner = $handles[$task->getOwnerPHID()]->getName();
      }

      $projects = array();
      foreach ($task->getProjectPHIDs() as $phid) {
        $projects[] = $handles[$phid]->getName();
      }
      $projects = implode(', ', $projects);

      $rows[] = array(
        'T'.$task->getID(),
        $task_owner,
        idx($status_map, $task->getStatus(), '?'),
        idx($pri_map, $task->getPriority(), '?'),
        $this->computeExcelDate($task->getDateCreated()),
        $this->computeExcelDate($task->getDateModified()),
        $task->getTitle(),
        $projects,
        PhabricatorEnv::getProductionURI('/T'.$task->getID()),
        id(new PhutilUTF8StringTruncator())
        ->setMaximumBytes(512)
        ->truncateString($task->getDescription()),
      );
    }

    foreach ($rows as $row => $cols) {
      foreach ($cols as $col => $spec) {
        $cell_name = $this->col($col).($row + 1);
        $cell = $sheet
          ->setCellValue($cell_name, $spec, $return_cell = true);

        if ($row == 0) {
          $sheet->getStyle($cell_name)->applyFromArray($header_format);
        }

        if ($is_date[$col]) {
          $code = PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2;
          $sheet
            ->getStyle($cell_name)
            ->getNumberFormat()
            ->setFormatCode($code);
        } else {
          $cell->setDataType(PHPExcel_Cell_DataType::TYPE_STRING);
        }
      }
    }
  }

  private function col($n) {
    return chr(ord('A') + $n);
  }

}


text:
package org.wso2.carbon.apimgt.rest.api.common.interceptors;

import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;
import io.swagger.util.Json;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.apimgt.core.exception.APIManagementException;
import org.wso2.carbon.apimgt.core.exception.ErrorHandler;
import org.wso2.carbon.apimgt.core.exception.ExceptionCodes;
import org.wso2.carbon.apimgt.rest.api.common.RestApiConstants;
import org.wso2.carbon.apimgt.rest.api.common.api.RESTAPIAuthenticator;
import org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO;
import org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException;
import org.wso2.carbon.apimgt.rest.api.common.util.RestApiUtil;
import org.wso2.msf4j.Interceptor;
import org.wso2.msf4j.Request;
import org.wso2.msf4j.Response;
import org.wso2.msf4j.ServiceMethodInfo;

import java.util.HashMap;
import java.util.Locale;
import javax.ws.rs.core.MediaType;

import static org.wso2.carbon.messaging.Constants.PROTOCOL;

/**
 * Security Interceptor that does basic authentication for REST ApI requests.
 *
 */
@Component(
        name = "org.wso2.carbon.apimgt.rest.api.common.interceptors.RESTAPISecurityInterceptor",
        service = Interceptor.class,
        immediate = true
)
public class RESTAPISecurityInterceptor implements Interceptor {
    private static final Logger log = LoggerFactory.getLogger(RESTAPISecurityInterceptor.class);
    //todo authenticatorName should be read from a configuration
    private static String authenticatorName = "org.wso2.carbon.apimgt.rest.api.common.impl.OAuth2Authenticator";
    private RESTAPIAuthenticator authenticatorImplClass = null;

    /**
     * preCall is run before a handler method call is made. If any of the preCalls throw exception or return false then
     * no other subsequent preCalls will be called and the request processing will be terminated,
     * also no postCall interceptors will be called.
     *
     * @param request           HttpRequest being processed.
     * @param response          HttpResponder to send response.
     * @param serviceMethodInfo Info on handler method that will be called.
     * @return true if the request processing can continue, otherwise the hook should send response and return false to
     * stop further processing.
     * @throws APIMgtSecurityException if error occurs while executing the preCall
     */
    @Override
    public boolean preCall(Request request, Response response, ServiceMethodInfo serviceMethodInfo) throws
            APIMgtSecurityException {
        ErrorHandler errorHandler = null;
        boolean isAuthenticated = false;
        /* TODO: Following string contains check is done to avoid checking security headers in non API requests.
         * Consider this as a tempory fix until MSF4J support context based interceptor registration */
        String requestURI = request.getUri().toLowerCase(Locale.ENGLISH);
        if (!requestURI.contains("/api/am/")) {
            return true;
        }
        if (requestURI.contains("api/am/webserver/")) {
            return true;
        } else if (requestURI.contains("/login/token")) {
            return true;
        }

        String yamlContent = null;
        String protocol = (String) request.getProperty(PROTOCOL);
        Swagger swagger = null;
        if (requestURI.contains("/publisher")) {
            if (requestURI.contains("swagger.yaml")) {
                try {
                    yamlContent = RestApiUtil.getPublisherRestAPIResource();
                } catch (APIManagementException e) {
                    log.error("Couldn't find swagger.yaml for publisher", e);
                }
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(yamlContent)
                        .setMediaType("text/x-yaml").send();
                return false;
            }
        } else if (requestURI.contains("/store")) {
            if (requestURI.contains("swagger.json")) {
                try {
                    yamlContent = RestApiUtil.getStoreRestAPIResource();
                    swagger = new SwaggerParser().parse(yamlContent);
                    swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.STORE));
                    swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));

                } catch (APIManagementException e) {
                    log.error("Couldn't find swagger.json for store", e);
                }
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty
                        (swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
                return false;
            }
        } else if (requestURI.contains("/editor") || requestURI.contains("keyserver") || requestURI.contains("core")) {
            return true;
        } else if (requestURI.contains("/admin"))   {
            if (requestURI.contains("swagger.json")) {
                try {
                    yamlContent = RestApiUtil.getAdminRestAPIResource();
                    swagger = new SwaggerParser().parse(yamlContent);
                    swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.ADMIN));
                    swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));

                } catch (APIManagementException e) {
                    log.error("Couldn't find swagger.json for admin", e);
                }
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty
                        (swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
                return false;
            }
        }
        try {
            if (authenticatorImplClass == null) {
                Class<?> implClass = null;
                try {
                    implClass = Class.forName(authenticatorName);
                } catch (ClassNotFoundException e) {
                    throw new APIMgtSecurityException("Error while loading class " + authenticatorName, e);
                }
                authenticatorImplClass = (RESTAPIAuthenticator) implClass.newInstance();

            }
            isAuthenticated = authenticatorImplClass.authenticate(request, response, serviceMethodInfo);
        } catch (APIMgtSecurityException e) {
            errorHandler = e.getErrorHandler();
            log.error(e.getMessage() + " Requested Path: " + request.getUri());
        } catch (InstantiationException e) {
            log.error(e.getMessage() + " Error while instantiating authenticator: " + authenticatorName);
            isAuthenticated = false;
            errorHandler = ExceptionCodes.AUTH_GENERAL_ERROR;
        } catch (IllegalAccessException e) {
            log.error(e.getMessage() + " Error while accessing resource : " + authenticatorName);
            isAuthenticated = false;
            errorHandler = ExceptionCodes.AUTH_GENERAL_ERROR;

        }

        if (!isAuthenticated) {
            handleSecurityError(errorHandler, response);
        }
        return isAuthenticated;
    }

    /**
     * postCall is run after a handler method call is made. If any of the postCalls throw and exception then the
     * remaining postCalls will still be called. If the handler method was not called then postCall interceptors will
     * not be called.
     *
     * @param request           HttpRequest being processed.
     * @param status            Http status returned to the client.
     * @param serviceMethodInfo Info on handler method that was called.
     * @throws Exception if error occurs while executing the postCall
     */
    @Override
    public void postCall(Request request, int status, ServiceMethodInfo serviceMethodInfo) throws Exception {

    }

    /**
     * Handles error condition
     * @param errorHandler Security error code
     * @param responder    HttpResponder instance which is used send error messages back to the client
     */
    private void handleSecurityError(ErrorHandler errorHandler, Response responder) {
        HashMap<String, String> paramList = new HashMap<String, String>();
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorHandler, paramList);
        responder.setStatus(errorHandler.getHttpStatusCode());
        responder.setHeader(javax.ws.rs.core.HttpHeaders.WWW_AUTHENTICATE, RestApiConstants.AUTH_TYPE_OAUTH2);
        responder.setEntity(errorDTO);
        responder.setMediaType(MediaType.APPLICATION_JSON);
        responder.send();
    }
}


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

<author>
    <name>{{author.name}}</name>
    <link href="{{url_for('showAuthor', author_id=author.id )}}" />
    <id>{{author.id}}</id>

    <items>
    {% for item in author.items %}
        <item>
            <title>{{item.title}}</title>
            <id>{{item.id}}</id>
            <description>{{item.description}}</description>
            <type>{{item.type}}</type>
            <create_date>{{item.create_date}}</create_date>
            <date_added>{{item.date_added}}</date_added>
            <owner_id>{{item.user_id}}</owner_id>
            <url>{{item.archive_url}}</url>
            <notes>{{item.note}}</notes>
            <people>
                {% for person in item.people %}
                <person>
                    <name>{{person.name}}</name>
                    <id>{{person.id}}</id>
                </person>
                {% endfor %}
            </people>
            <subjects>
                {% for subject in item.subject %}
                <subject>
                    <name>{{subject.subject}}</name>
                    <id>{{subject.id}}</id>
                </subject>
                {% endfor %}
            </subjects>
            <collections>
                {% for collection in item.collections %}
                <collection>
                    <name>{{collection.name}}</name>
                    <id>{{collection.id}}</id>
                    <description>{{collection.description}}</description>
                </collection>
                {% endfor %}
            </collections>
        </item>
    {% endfor %}
    </items>
</author>


text:
#include <stdarg.h>

#include "windef.h"
#include "winbase.h"
#include "winerror.h"
#include "winternl.h"
#include "wmistr.h"
#include "evntrace.h"
#include "evntprov.h"

#include "wine/unicode.h"
#include "wine/debug.h"

#include "advapi32_misc.h"

WINE_DEFAULT_DEBUG_CHANNEL(advapi);
WINE_DECLARE_DEBUG_CHANNEL(eventlog);

/******************************************************************************
 * BackupEventLogA [ADVAPI32.@]
 *
 * Saves the event log to a backup file.
 *
 * PARAMS
 *  hEventLog        [I] Handle to event log to backup.
 *  lpBackupFileName [I] Name of the backup file.
 *
 * RETURNS
 *  Success: nonzero. File lpBackupFileName will contain the contents of
 *           hEvenLog.
 *  Failure: zero.
 */
BOOL WINAPI BackupEventLogA( HANDLE hEventLog, LPCSTR lpBackupFileName )
{
    LPWSTR backupW;
    BOOL ret;

    backupW = SERV_dup(lpBackupFileName);
    ret = BackupEventLogW(hEventLog, backupW);
    HeapFree(GetProcessHeap(), 0, backupW);

    return ret;
}

/******************************************************************************
 * BackupEventLogW [ADVAPI32.@]
 *
 * See BackupEventLogA.
 */
BOOL WINAPI BackupEventLogW( HANDLE hEventLog, LPCWSTR lpBackupFileName )
{
    FIXME("(%p,%s) stub\n", hEventLog, debugstr_w(lpBackupFileName));

    if (!lpBackupFileName)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    if (!hEventLog)
    {
        SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (GetFileAttributesW(lpBackupFileName) != INVALID_FILE_ATTRIBUTES)
    {
        SetLastError(ERROR_ALREADY_EXISTS);
        return FALSE;
    }

    return TRUE;
}

/******************************************************************************
 * ClearEventLogA [ADVAPI32.@]
 *
 * Clears the event log and optionally saves the log to a backup file.
 *
 * PARAMS
 *  hEvenLog         [I] Handle to event log to clear.
 *  lpBackupFileName [I] Name of the backup file.
 *
 * RETURNS
 *  Success: nonzero. if lpBackupFileName != NULL, lpBackupFileName will
 *           contain the contents of hEvenLog and the log will be cleared.
 *  Failure: zero. Fails if the event log is empty or if lpBackupFileName
 *           exists.
 */
BOOL WINAPI ClearEventLogA( HANDLE hEventLog, LPCSTR lpBackupFileName )
{
    LPWSTR backupW;
    BOOL ret;

    backupW = SERV_dup(lpBackupFileName);
    ret = ClearEventLogW(hEventLog, backupW);
    HeapFree(GetProcessHeap(), 0, backupW);

    return ret;
}

/******************************************************************************
 * ClearEventLogW [ADVAPI32.@]
 *
 * See ClearEventLogA.
 */
BOOL WINAPI ClearEventLogW( HANDLE hEventLog, LPCWSTR lpBackupFileName )
{
    FIXME("(%p,%s) stub\n", hEventLog, debugstr_w(lpBackupFileName));

    if (!hEventLog)
    {
        SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    return TRUE;
}

/******************************************************************************
 * CloseEventLog [ADVAPI32.@]
 *
 * Closes a read handle to the event log.
 *
 * PARAMS
 *  hEventLog [I/O] Handle of the event log to close.
 *
 * RETURNS
 *  Success: nonzero
 *  Failure: zero
 */
BOOL WINAPI CloseEventLog( HANDLE hEventLog )
{
    FIXME("(%p) stub\n", hEventLog);

    if (!hEventLog)
    {
        SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    return TRUE;
}

/******************************************************************************
 * ControlTraceW [ADVAPI32.@]
 *
 * Control a givel event trace session
 *
 */
ULONG WINAPI ControlTraceW( TRACEHANDLE hSession, LPCWSTR SessionName, PEVENT_TRACE_PROPERTIES Properties, ULONG control )
{
    FIXME("(%s, %s, %p, %d) stub\n", wine_dbgstr_longlong(hSession), debugstr_w(SessionName), Properties, control);
    return ERROR_SUCCESS;
}

/******************************************************************************
 * ControlTraceA [ADVAPI32.@]
 *
 * See ControlTraceW.
 *
 */
ULONG WINAPI ControlTraceA( TRACEHANDLE hSession, LPCSTR SessionName, PEVENT_TRACE_PROPERTIES Properties, ULONG control )
{
    FIXME("(%s, %s, %p, %d) stub\n", wine_dbgstr_longlong(hSession), debugstr_a(SessionName), Properties, control);
    return ERROR_SUCCESS;
}

/******************************************************************************
 * FlushTraceA [ADVAPI32.@]
 */
ULONG WINAPI FlushTraceA ( TRACEHANDLE hSession, LPCSTR SessionName, PEVENT_TRACE_PROPERTIES Properties )
{
    return ControlTraceA( hSession, SessionName, Properties, EVENT_TRACE_CONTROL_FLUSH );
}

/******************************************************************************
 * FlushTraceW [ADVAPI32.@]
 */
ULONG WINAPI FlushTraceW ( TRACEHANDLE hSession, LPCWSTR SessionName, PEVENT_TRACE_PROPERTIES Properties )
{
    return ControlTraceW( hSession, SessionName, Properties, EVENT_TRACE_CONTROL_FLUSH );
}

/******************************************************************************
 * DeregisterEventSource [ADVAPI32.@]
 *
 * Closes a write handle to an event log
 *
 * PARAMS
 *  hEventLog [I/O] Handle of the event log.
 *
 * RETURNS
 *  Success: nonzero
 *  Failure: zero
 */
BOOL WINAPI DeregisterEventSource( HANDLE hEventLog )
{
    FIXME("(%p) stub\n", hEventLog);
    return TRUE;
}

/******************************************************************************
 * EnableTraceEx [ADVAPI32.@]
 */
ULONG WINAPI EnableTraceEx( LPCGUID provider, LPCGUID source, TRACEHANDLE hSession, ULONG enable,
                            UCHAR level, ULONGLONG anykeyword, ULONGLONG allkeyword, ULONG enableprop,
                            PEVENT_FILTER_DESCRIPTOR filterdesc )
{
    FIXME("(%s, %s, %s, %d, %c, %s, %s, %d, %p): stub\n", debugstr_guid(provider),
            debugstr_guid(source), wine_dbgstr_longlong(hSession), enable, level,
            wine_dbgstr_longlong(anykeyword), wine_dbgstr_longlong(allkeyword),
            enableprop, filterdesc);

    return ERROR_SUCCESS;
}

/******************************************************************************
 * EnableTrace [ADVAPI32.@]
 */
ULONG WINAPI EnableTrace( ULONG enable, ULONG flag, ULONG level, LPCGUID guid, TRACEHANDLE hSession )
{
    FIXME("(%d, 0x%x, %d, %s, %s): stub\n", enable, flag, level,
            debugstr_guid(guid), wine_dbgstr_longlong(hSession));

    return ERROR_SUCCESS;
}

/******************************************************************************
 * GetEventLogInformation [ADVAPI32.@]
 *
 * Retrieve some information about an event log.
 *
 * PARAMS
 *  hEventLog      [I]   Handle to an open event log.
 *  dwInfoLevel    [I]   Level of information (only EVENTLOG_FULL_INFO)
 *  lpBuffer       [I/O] The buffer for the returned information
 *  cbBufSize      [I]   The size of the buffer
 *  pcbBytesNeeded [O]   The needed bytes to hold the information
 *
 * RETURNS
 *  Success: TRUE. lpBuffer will hold the information and pcbBytesNeeded shows
 *           the needed buffer size.
 *  Failure: FALSE.
 */
BOOL WINAPI GetEventLogInformation( HANDLE hEventLog, DWORD dwInfoLevel, LPVOID lpBuffer, DWORD cbBufSize, LPDWORD pcbBytesNeeded)
{
    EVENTLOG_FULL_INFORMATION *efi;

    FIXME("(%p, %d, %p, %d, %p) stub\n", hEventLog, dwInfoLevel, lpBuffer, cbBufSize, pcbBytesNeeded);

    if (dwInfoLevel != EVENTLOG_FULL_INFO)
    {
        SetLastError(ERROR_INVALID_LEVEL);
        return FALSE;
    }

    if (!hEventLog)
    {
        SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    if (!lpBuffer || !pcbBytesNeeded)
    {
        /* FIXME: This will be handled properly when eventlog is moved
         * to a higher level
         */
        SetLastError(RPC_X_NULL_REF_POINTER);
        return FALSE;
    }

    *pcbBytesNeeded = sizeof(EVENTLOG_FULL_INFORMATION);
    if (cbBufSize < sizeof(EVENTLOG_FULL_INFORMATION))
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        return FALSE;
    }

    /* Pretend the log is not full */
    efi = (EVENTLOG_FULL_INFORMATION *)lpBuffer;
    efi->dwFull = 0;

    return TRUE;
}

/******************************************************************************
 * GetNumberOfEventLogRecords [ADVAPI32.@]
 *
 * Retrieves the number of records in an event log.
 *
 * PARAMS
 *  hEventLog       [I] Handle to an open event log.
 *  NumberOfRecords [O] Number of records in the log.
 *
 * RETURNS
 *  Success: nonzero. NumberOfRecords will contain the number of records in
 *           the log.
 *  Failure: zero
 */
BOOL WINAPI GetNumberOfEventLogRecords( HANDLE hEventLog, PDWORD NumberOfRecords )
{
    FIXME("(%p,%p) stub\n", hEventLog, NumberOfRecords);

    if (!NumberOfRecords)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    if (!hEventLog)
    {
        SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    *NumberOfRecords = 0;

    return TRUE;
}

/******************************************************************************
 * GetOldestEventLogRecord [ADVAPI32.@]
 *
 * Retrieves the absolute record number of the oldest record in an even log.
 *
 * PARAMS
 *  hEventLog    [I] Handle to an open event log.
 *  OldestRecord [O] Absolute record number of the oldest record.
 *
 * RETURNS
 *  Success: nonzero. OldestRecord contains the record number of the oldest
 *           record in the log.
 *  Failure: zero
 */
BOOL WINAPI GetOldestEventLogRecord( HANDLE hEventLog, PDWORD OldestRecord )
{
    FIXME("(%p,%p) stub\n", hEventLog, OldestRecord);

    if (!OldestRecord)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    if (!hEventLog)
    {
        SetLastError(ERROR_INVALID_HANDLE);
        return FALSE;
    }

    *OldestRecord = 0;

    return TRUE;
}

/******************************************************************************
 * NotifyChangeEventLog [ADVAPI32.@]
 *
 * Enables an application to receive notification when an event is written
 * to an event log.
 *
 * PARAMS
 *  hEventLog [I] Handle to an event log.
 *  hEvent    [I] Handle to a manual-reset event object.
 *
 * RETURNS
 *  Success: nonzero
 *  Failure: zero
 */
BOOL WINAPI NotifyChangeEventLog( HANDLE hEventLog, HANDLE hEvent )
{
	FIXME("(%p,%p) stub\n", hEventLog, hEvent);
	return TRUE;
}

/******************************************************************************
 * OpenBackupEventLogA [ADVAPI32.@]
 *
 * Opens a handle to a backup event log.
 *
 * PARAMS
 *  lpUNCServerName [I] Universal Naming Convention name of the server on which
 *                      this will be performed.
 *  lpFileName      [I] Specifies the name of the backup file.
 *
 * RETURNS
 *  Success: Handle to the backup event log.
 *  Failure: NULL
 */
HANDLE WINAPI OpenBackupEventLogA( LPCSTR lpUNCServerName, LPCSTR lpFileName )
{
    LPWSTR uncnameW, filenameW;
    HANDLE handle;

    uncnameW = SERV_dup(lpUNCServerName);
    filenameW = SERV_dup(lpFileName);
    handle = OpenBackupEventLogW(uncnameW, filenameW);
    HeapFree(GetProcessHeap(), 0, uncnameW);
    HeapFree(GetProcessHeap(), 0, filenameW);

    return handle;
}

/******************************************************************************
 * OpenBackupEventLogW [ADVAPI32.@]
 *
 * See OpenBackupEventLogA.
 */
HANDLE WINAPI OpenBackupEventLogW( LPCWSTR lpUNCServerName, LPCWSTR lpFileName )
{
    FIXME("(%s,%s) stub\n", debugstr_w(lpUNCServerName), debugstr_w(lpFileName));

    if (!lpFileName)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return NULL;
    }

    if (lpUNCServerName && lpUNCServerName[0])
    {
        FIXME("Remote server not supported\n");
        SetLastError(RPC_S_SERVER_UNAVAILABLE);
        return NULL;
    }

    if (GetFileAttributesW(lpFileName) == INVALID_FILE_ATTRIBUTES)
    {
        SetLastError(ERROR_FILE_NOT_FOUND);
        return NULL;
    }

    return (HANDLE)0xcafe4242;
}

/******************************************************************************
 * OpenEventLogA [ADVAPI32.@]
 *
 * Opens a handle to the specified event log.
 *
 * PARAMS
 *  lpUNCServerName [I] UNC name of the server on which the event log is
 *                      opened.
 *  lpSourceName    [I] Name of the log.
 *
 * RETURNS
 *  Success: Handle to an event log.
 *  Failure: NULL
 */
HANDLE WINAPI OpenEventLogA( LPCSTR uncname, LPCSTR source )
{
    LPWSTR uncnameW, sourceW;
    HANDLE handle;

    uncnameW = SERV_dup(uncname);
    sourceW = SERV_dup(source);
    handle = OpenEventLogW(uncnameW, sourceW);
    HeapFree(GetProcessHeap(), 0, uncnameW);
    HeapFree(GetProcessHeap(), 0, sourceW);

    return handle;
}

/******************************************************************************
 * OpenEventLogW [ADVAPI32.@]
 *
 * See OpenEventLogA.
 */
HANDLE WINAPI OpenEventLogW( LPCWSTR uncname, LPCWSTR source )
{
    FIXME("(%s,%s) stub\n", debugstr_w(uncname), debugstr_w(source));

    if (!source)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return NULL;
    }

    if (uncname && uncname[0])
    {
        FIXME("Remote server not supported\n");
        SetLastError(RPC_S_SERVER_UNAVAILABLE);
        return NULL;
    }

    return (HANDLE)0xcafe4242;
}

/******************************************************************************
 * QueryAllTracesW [ADVAPI32.@]
 *
 * Query information for started event trace sessions
 *
 */
ULONG WINAPI QueryAllTracesW( PEVENT_TRACE_PROPERTIES * parray, ULONG arraycount, PULONG psessioncount )
{
    FIXME("(%p, %d, %p) stub\n", parray, arraycount, psessioncount);

    if (psessioncount) *psessioncount = 0;
    return ERROR_SUCCESS;
}

/******************************************************************************
 * QueryAllTracesA [ADVAPI32.@]
 *
 * See QueryAllTracesW.
 */
ULONG WINAPI QueryAllTracesA( PEVENT_TRACE_PROPERTIES * parray, ULONG arraycount, PULONG psessioncount )
{
    FIXME("(%p, %d, %p) stub\n", parray, arraycount, psessioncount);

    if (psessioncount) *psessioncount = 0;
    return ERROR_SUCCESS;
}

/******************************************************************************
 * ReadEventLogA [ADVAPI32.@]
 *
 * Reads a whole number of entries from an event log.
 *
 * PARAMS
 *  hEventLog                [I] Handle of the event log to read.
 *  dwReadFlags              [I] see MSDN doc.
 *  dwRecordOffset           [I] Log-entry record number to start at.
 *  lpBuffer                 [O] Buffer for the data read.
 *  nNumberOfBytesToRead     [I] Size of lpBuffer.
 *  pnBytesRead              [O] Receives number of bytes read.
 *  pnMinNumberOfBytesNeeded [O] Receives number of bytes required for the
 *                               next log entry.
 *
 * RETURNS
 *  Success: nonzero
 *  Failure: zero
 */
BOOL WINAPI ReadEventLogA( HANDLE hEventLog, DWORD dwReadFlags, DWORD dwRecordOffset,
    LPVOID lpBuffer, DWORD nNumberOfBytesToRead, DWORD *pnBytesRead, DWORD *pnMinNumberOfBytesNeeded )
{
    FIXME("(%p,0x%08x,0x%08x,%p,0x%08x,%p,%p) stub\n", hEventLog, dwReadFlags,
          dwRecordOffset, lpBuffer, nNumberOfBytesToRead, pnBytesRead, pnMinNumberOfBytesNeeded);

    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}

/******************************************************************************
 * ReadEventLogW [ADVAPI32.@]
 *
 * See ReadEventLogA.
 */
BOOL WINAPI ReadEventLogW( HANDLE hEventLog, DWORD dwReadFlags, DWORD dwRecordOffset,
    LPVOID lpBuffer, DWORD nNumberOfBytesToRead, DWORD *pnBytesRead, DWORD *pnMinNumberOfBytesNeeded )
{
    FIXME("(%p,0x%08x,0x%08x,%p,0x%08x,%p,%p) stub\n", hEventLog, dwReadFlags,
          dwRecordOffset, lpBuffer, nNumberOfBytesToRead, pnBytesRead, pnMinNumberOfBytesNeeded);

    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}

/******************************************************************************
 * RegisterEventSourceA [ADVAPI32.@]
 *
 * Returns a registered handle to an event log.
 *
 * PARAMS
 *  lpUNCServerName [I] UNC name of the source server.
 *  lpSourceName    [I] Specifies the name of the event source to retrieve.
 *
 * RETURNS
 *  Success: Handle to the event log.
 *  Failure: NULL. Returns ERROR_INVALID_HANDLE if lpSourceName specifies the
 *           Security event log.
 */
HANDLE WINAPI RegisterEventSourceA( LPCSTR lpUNCServerName, LPCSTR lpSourceName )
{
    UNICODE_STRING lpUNCServerNameW;
    UNICODE_STRING lpSourceNameW;
    HANDLE ret;

    FIXME("(%s,%s): stub\n", debugstr_a(lpUNCServerName), debugstr_a(lpSourceName));

    RtlCreateUnicodeStringFromAsciiz(&lpUNCServerNameW, lpUNCServerName);
    RtlCreateUnicodeStringFromAsciiz(&lpSourceNameW, lpSourceName);
    ret = RegisterEventSourceW(lpUNCServerNameW.Buffer,lpSourceNameW.Buffer);
    RtlFreeUnicodeString (&lpUNCServerNameW);
    RtlFreeUnicodeString (&lpSourceNameW);
    return ret;
}

/******************************************************************************
 * RegisterEventSourceW [ADVAPI32.@]
 *
 * See RegisterEventSourceA.
 */
HANDLE WINAPI RegisterEventSourceW( LPCWSTR lpUNCServerName, LPCWSTR lpSourceName )
{
    FIXME("(%s,%s): stub\n", debugstr_w(lpUNCServerName), debugstr_w(lpSourceName));
    return (HANDLE)0xcafe4242;
}

/******************************************************************************
 * ReportEventA [ADVAPI32.@]
 *
 * Writes an entry at the end of an event log.
 *
 * PARAMS
 *  hEventLog   [I] Handle of an event log.
 *  wType       [I] See MSDN doc.
 *  wCategory   [I] Event category.
 *  dwEventID   [I] Event identifier.
 *  lpUserSid   [I] Current user's security identifier.
 *  wNumStrings [I] Number of insert strings in lpStrings.
 *  dwDataSize  [I] Size of event-specific raw data to write.
 *  lpStrings   [I] Buffer containing an array of string to be merged.
 *  lpRawData   [I] Buffer containing the binary data.
 *
 * RETURNS
 *  Success: nonzero. Entry was written to the log.
 *  Failure: zero.
 *
 * NOTES
 *  The ReportEvent function adds the time, the entry's length, and the
 *  offsets before storing the entry in the log. If lpUserSid != NULL, the
 *  username is also logged.
 */
BOOL WINAPI ReportEventA ( HANDLE hEventLog, WORD wType, WORD wCategory, DWORD dwEventID,
    PSID lpUserSid, WORD wNumStrings, DWORD dwDataSize, LPCSTR *lpStrings, LPVOID lpRawData)
{
    LPWSTR *wideStrArray;
    UNICODE_STRING str;
    UINT i;
    BOOL ret;

    FIXME("(%p,0x%04x,0x%04x,0x%08x,%p,0x%04x,0x%08x,%p,%p): stub\n", hEventLog,
          wType, wCategory, dwEventID, lpUserSid, wNumStrings, dwDataSize, lpStrings, lpRawData);

    if (wNumStrings == 0) return TRUE;
    if (!lpStrings) return TRUE;

    wideStrArray = HeapAlloc(GetProcessHeap(), 0, sizeof(LPWSTR) * wNumStrings);
    for (i = 0; i < wNumStrings; i++)
    {
        RtlCreateUnicodeStringFromAsciiz(&str, lpStrings[i]);
        wideStrArray[i] = str.Buffer;
    }
    ret = ReportEventW(hEventLog, wType, wCategory, dwEventID, lpUserSid,
                       wNumStrings, dwDataSize, (LPCWSTR *)wideStrArray, lpRawData);
    for (i = 0; i < wNumStrings; i++)
    {
        HeapFree( GetProcessHeap(), 0, wideStrArray[i] );
    }
    HeapFree(GetProcessHeap(), 0, wideStrArray);
    return ret;
}

/******************************************************************************
 * ReportEventW [ADVAPI32.@]
 *
 * See ReportEventA.
 */
BOOL WINAPI ReportEventW( HANDLE hEventLog, WORD wType, WORD wCategory, DWORD dwEventID,
    PSID lpUserSid, WORD wNumStrings, DWORD dwDataSize, LPCWSTR *lpStrings, LPVOID lpRawData )
{
    UINT i;

    FIXME("(%p,0x%04x,0x%04x,0x%08x,%p,0x%04x,0x%08x,%p,%p): stub\n", hEventLog,
          wType, wCategory, dwEventID, lpUserSid, wNumStrings, dwDataSize, lpStrings, lpRawData);

    /* partial stub */

    if (wNumStrings == 0) return TRUE;
    if (!lpStrings) return TRUE;

    for (i = 0; i < wNumStrings; i++)
    {
        switch (wType)
        {
        case EVENTLOG_SUCCESS:
            TRACE_(eventlog)("%s\n", debugstr_w(lpStrings[i]));
            break;
        case EVENTLOG_ERROR_TYPE:
            ERR_(eventlog)("%s\n", debugstr_w(lpStrings[i]));
            break;
        case EVENTLOG_WARNING_TYPE:
            WARN_(eventlog)("%s\n", debugstr_w(lpStrings[i]));
            break;
        default:
            TRACE_(eventlog)("%s\n", debugstr_w(lpStrings[i]));
            break;
        }
    }
    return TRUE;
}

/******************************************************************************
 * RegisterTraceGuidsW [ADVAPI32.@]
 *
 * Register an event trace provider and the event trace classes that it uses
 * to generate events.
 *
 * PARAMS
 *  RequestAddress     [I]   ControlCallback function
 *  RequestContext     [I]   Optional provider-defined context
 *  ControlGuid        [I]   GUID of the registering provider
 *  GuidCount          [I]   Number of elements in the TraceGuidReg array
 *  TraceGuidReg       [I/O] Array of TRACE_GUID_REGISTRATION structures
 *  MofImagePath       [I]   not supported, set to NULL
 *  MofResourceName    [I]   not supported, set to NULL
 *  RegistrationHandle [O]   Provider's registration handle
 *
 * RETURNS
 *  Success: ERROR_SUCCESS
 *  Failure: System error code
 *
 * FIXME
 *  Stub.
 */
ULONG WINAPI RegisterTraceGuidsW( WMIDPREQUEST RequestAddress,
                PVOID RequestContext, LPCGUID ControlGuid, ULONG GuidCount,
                PTRACE_GUID_REGISTRATION TraceGuidReg, LPCWSTR MofImagePath,
                LPCWSTR MofResourceName, PTRACEHANDLE RegistrationHandle )
{
    FIXME("(%p, %p, %s, %u, %p, %s, %s, %p): stub\n", RequestAddress, RequestContext,
          debugstr_guid(ControlGuid), GuidCount, TraceGuidReg, debugstr_w(MofImagePath),
          debugstr_w(MofResourceName), RegistrationHandle);
    return ERROR_SUCCESS;
}

/******************************************************************************
 * RegisterTraceGuidsA [ADVAPI32.@]
 *
 * See RegisterTraceGuidsW.
 *
 * FIXME
 *  Stub.
 */
ULONG WINAPI RegisterTraceGuidsA( WMIDPREQUEST RequestAddress,
                PVOID RequestContext, LPCGUID ControlGuid, ULONG GuidCount,
                PTRACE_GUID_REGISTRATION TraceGuidReg, LPCSTR MofImagePath,
                LPCSTR MofResourceName, PTRACEHANDLE RegistrationHandle )
{
    FIXME("(%p, %p, %s, %u, %p, %s, %s, %p): stub\n", RequestAddress, RequestContext,
          debugstr_guid(ControlGuid), GuidCount, TraceGuidReg, debugstr_a(MofImagePath),
          debugstr_a(MofResourceName), RegistrationHandle);
    return ERROR_SUCCESS;
}

/******************************************************************************
 * StartTraceW [ADVAPI32.@]
 *
 * Register and start an event trace session
 *
 */
ULONG WINAPI StartTraceW( PTRACEHANDLE pSessionHandle, LPCWSTR SessionName, PEVENT_TRACE_PROPERTIES Properties )
{
    FIXME("(%p, %s, %p) stub\n", pSessionHandle, debugstr_w(SessionName), Properties);
    if (pSessionHandle) *pSessionHandle = 0xcafe4242;
    return ERROR_SUCCESS;
}

/******************************************************************************
 * StartTraceA [ADVAPI32.@]
 *
 * See StartTraceW.
 *
 */
ULONG WINAPI StartTraceA( PTRACEHANDLE pSessionHandle, LPCSTR SessionName, PEVENT_TRACE_PROPERTIES Properties )
{
    FIXME("(%p, %s, %p) stub\n", pSessionHandle, debugstr_a(SessionName), Properties);
    if (pSessionHandle) *pSessionHandle = 0xcafe4242;
    return ERROR_SUCCESS;
}

/******************************************************************************
 * StopTraceW [ADVAPI32.@]
 *
 * Stop an event trace session
 *
 */
ULONG WINAPI StopTraceW( TRACEHANDLE session, LPCWSTR session_name, PEVENT_TRACE_PROPERTIES properties )
{
    FIXME("(%s, %s, %p) stub\n", wine_dbgstr_longlong(session), debugstr_w(session_name), properties);
    return ERROR_SUCCESS;
}

/******************************************************************************
 * StopTraceA [ADVAPI32.@]
 *
 * See StopTraceW.
 *
 */
ULONG WINAPI StopTraceA( TRACEHANDLE session, LPCSTR session_name, PEVENT_TRACE_PROPERTIES properties )
{
    FIXME("(%s, %s, %p) stub\n", wine_dbgstr_longlong(session), debugstr_a(session_name), properties);
    return ERROR_SUCCESS;
}

/******************************************************************************
 * TraceEvent [ADVAPI32.@]
 */
ULONG WINAPI TraceEvent( TRACEHANDLE SessionHandle, PEVENT_TRACE_HEADER EventTrace )
{
    FIXME("%s %p\n", wine_dbgstr_longlong(SessionHandle), EventTrace);
    return ERROR_CALL_NOT_IMPLEMENTED;
}

/******************************************************************************
 * UnregisterTraceGuids [ADVAPI32.@]
 *
 * See RegisterTraceGuids
 *
 * FIXME
 *  Stub.
 */
ULONG WINAPI UnregisterTraceGuids( TRACEHANDLE RegistrationHandle )
{
    FIXME("%s: stub\n", wine_dbgstr_longlong(RegistrationHandle));
    return ERROR_CALL_NOT_IMPLEMENTED;
}

/******************************************************************************
 * EventRegister [ADVAPI32.@]
 */
ULONG WINAPI EventRegister( LPCGUID provider, PENABLECALLBACK callback, PVOID context, PREGHANDLE handle )
{
    FIXME("%s, %p, %p, %p\n", debugstr_guid(provider), callback, context, handle);

    *handle = 0xdeadbeef;
    return ERROR_SUCCESS;
}

/******************************************************************************
 * EventUnregister [ADVAPI32.@]
 */
ULONG WINAPI EventUnregister( REGHANDLE handle )
{
    FIXME("%s: stub\n", wine_dbgstr_longlong(handle));
    return ERROR_SUCCESS;
}

/******************************************************************************
 * EventEnabled [ADVAPI32.@]
 *
 */
BOOLEAN WINAPI EventEnabled( REGHANDLE handle, PCEVENT_DESCRIPTOR descriptor )
{
    FIXME("(%s, %p): stub\n", wine_dbgstr_longlong(handle), descriptor);
    return FALSE;
}

/******************************************************************************
 * EventWrite [ADVAPI32.@]
 */
ULONG WINAPI EventWrite( REGHANDLE handle, PCEVENT_DESCRIPTOR descriptor, ULONG count,
                         PEVENT_DATA_DESCRIPTOR data )
{
    FIXME("%s, %p, %u, %p: stub\n", wine_dbgstr_longlong(handle), descriptor, count, data);
    return ERROR_SUCCESS;
}

/******************************************************************************
 * QueryTraceW [ADVAPI32.@]
 */
ULONG WINAPI QueryTraceW( TRACEHANDLE handle, LPCWSTR sessionname, PEVENT_TRACE_PROPERTIES properties )
{
    FIXME("%s %s %p: stub\n", wine_dbgstr_longlong(handle), debugstr_w(sessionname), properties);
    return ERROR_CALL_NOT_IMPLEMENTED;
}

/******************************************************************************
 * OpenTraceA [ADVAPI32.@]
 */
TRACEHANDLE WINAPI OpenTraceA( PEVENT_TRACE_LOGFILEA logfile )
{
    FIXME("%p: stub\n", logfile);
    SetLastError(ERROR_ACCESS_DENIED);
    return INVALID_PROCESSTRACE_HANDLE;
}

/******************************************************************************
 * OpenTraceW [ADVAPI32.@]
 */
TRACEHANDLE WINAPI OpenTraceW( PEVENT_TRACE_LOGFILEW logfile )
{
    FIXME("%p: stub\n", logfile);
    SetLastError(ERROR_ACCESS_DENIED);
    return INVALID_PROCESSTRACE_HANDLE;
}

/******************************************************************************
 * ProcessTrace [ADVAPI32.@]
 */
ULONG WINAPI ProcessTrace( PTRACEHANDLE HandleArray, ULONG HandleCount, LPFILETIME StartTime, LPFILETIME EndTime)
{
    FIXME("%p %u %p %p: stub\n", HandleArray, HandleCount, StartTime, EndTime);
    return ERROR_CALL_NOT_IMPLEMENTED;
}

/******************************************************************************
 * TraceMessage [ADVAPI32.@]
 */
ULONG WINAPIV TraceMessage( TRACEHANDLE handle, ULONG flags, LPGUID guid, USHORT number, ... )
{
    __ms_va_list valist;
    ULONG ret;

    __ms_va_start( valist, number );
    ret = TraceMessageVa( handle, flags, guid, number, valist );
    __ms_va_end( valist );
    return ret;
}

/******************************************************************************
 * TraceMessageVa [ADVAPI32.@]
 */
ULONG WINAPI TraceMessageVa( TRACEHANDLE handle, ULONG flags, LPGUID guid, USHORT number,
                            __ms_va_list args )
{
    FIXME("(%s %x %s %d) : stub\n", wine_dbgstr_longlong(handle), flags, debugstr_guid(guid), number);
    return ERROR_SUCCESS;
}

/******************************************************************************
 * CloseTrace [ADVAPI32.@]
 */
ULONG WINAPI CloseTrace( TRACEHANDLE handle )
{
    FIXME("%s: stub\n", wine_dbgstr_longlong(handle));
    return ERROR_INVALID_HANDLE;
}

/******************************************************************************
 * EnumerateTraceGuids [ADVAPI32.@]
 */
ULONG WINAPI EnumerateTraceGuids(PTRACE_GUID_PROPERTIES *propertiesarray,
                                 ULONG arraycount, PULONG guidcount)
{
    FIXME("%p %d %p: stub\n", propertiesarray, arraycount, guidcount);
    return ERROR_INVALID_PARAMETER;
}


text:
/*
 * fiberalgos.cpp
 *
 * Created on: 09.07.2012
 * @author Ralph Schurade
 */
#include "fiberalgos.h"

#include "fibers.h"

#include "../data/datasets/datasetfibers.h"
#include "../data/datasets/datasetscalar.h"
#include "../data/datasets/dataset3d.h"

#include <QDebug>

FiberAlgos::FiberAlgos()
{
}

FiberAlgos::~FiberAlgos()
{
}

QList<Dataset*> FiberAlgos::thinOut( Dataset* ds )
{
    Fibers* fa = new Fibers( dynamic_cast<DatasetFibers*>( ds ) );
    DatasetFibers* out = fa->thinOut();
    QList<Dataset*> l;
    l.push_back( out );
    return l;
}

QList<Dataset*> FiberAlgos::tractDensity( Dataset* ds )
{
    Fibers* fa = new Fibers( dynamic_cast<DatasetFibers*>( ds ) );
    DatasetScalar* out = fa->tractDensity();
    QList<Dataset*> l;
    l.push_back( out );
    return l;
}

QList<Dataset*> FiberAlgos::tractColor( Dataset* ds )
{
    Fibers* fa = new Fibers( dynamic_cast<DatasetFibers*>( ds ) );
    Dataset3D* out = fa->tractColor();
    QList<Dataset*> l;
    l.push_back( out );
    return l;
}

QList<Dataset*> FiberAlgos::cutSelecteded( Dataset* ds )
{
    DatasetFibers* f = dynamic_cast<DatasetFibers*>( ds );
    std::vector<Fib>selected = f->getSelectedFibs();

    QList<QString>dataNames = f->getDataNames();

    QList<Dataset*> l;

    DatasetFibers* out = new DatasetFibers( QDir( "new fibers" ), selected, dataNames );
    out->setDataMins( f->getDataMins() );
    out->setDataMaxes( f->getDataMaxes() );
    l.push_back( out );

    return l;
}

QList<Dataset*> FiberAlgos::downSample( Dataset* ds )
{
    Fibers* fa = new Fibers( dynamic_cast<DatasetFibers*>( ds ) );
    DatasetFibers* out = fa->downSample();
    QList<Dataset*> l;
    l.push_back( out );
    return l;
}


text:
require "spec_helper"
require "uri"

describe Lita::Handlers::Makeitrain, lita_handler: true do
  it { routes_command("makeitrain").to(:makeitrain) }

  describe "makeitrain" do
    it "should return a url" do
      send_command("makeitrain")
      expect(replies.last).to match(URI.regexp)
    end
  end

end
describe Lita::Handlers::JsonGifs, lita_handler: true do
  it { routes_command("test").to(:jsongifs) }

  describe "jsongifs" do
    it "should return a url" do
      send_command("test")
      expect(replies.last).to match('found')
    end
  end
end