text:
#import "ORKTextFieldView.h"

#import "ORKAccessibility.h"
#import "ORKSkin.h"

static NSString *const EmptyBulletString = @"\u25CB";
static NSString *const FilledBulletString = @"\u25CF";

@implementation ORKCaretOptionalTextField

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    _hitClearButton = NO;
    if ([self allowsSelection]) {
        return [super hitTest:point withEvent:event];
    } else {
        // Make exception for clear button, which is hittable
        if ( CGRectContainsPoint([self clearButtonRectForBounds:self.bounds], point)) {
            UIView *hitView = [super hitTest:point withEvent:event];
            // Where we are using a picker for date, time interval, and choice
            // Turn on flag to avoid bring up the keyboard when the field is not active.
            _hitClearButton = [hitView isKindOfClass:[UIButton class]];
            return hitView;
        }
        return nil;
    }
}

- (CGRect)caretRectForPosition:(UITextPosition *)position {
    if (_allowsSelection) {
        return [super caretRectForPosition:position];
    } else {
        return CGRectZero;
    }
}

@end

@implementation ORKPasscodeTextField

- (instancetype)init {
    self = [super init];
    if (self) {
        self.font = [UIFont fontWithName:@"Courier" size:35.0];
        self.textAlignment = NSTextAlignmentCenter;
    }
    return self;
}

- (UIKeyboardType)keyboardType {
    return UIKeyboardTypeNumberPad;
}

- (BOOL)allowsSelection {
    return NO;
}

- (void)updateTextWithNumberOfFilledBullets:(NSInteger)filledBullets {
    // Error checking.
    if (filledBullets > self.numberOfDigits) {
        @throw [NSException exceptionWithName:NSInvalidArgumentException
                                       reason:@"The number of filled bullets cannot exceed the number of pin digits."
                                     userInfo:nil];
    }

    // Append the string with the correct number of filled and empty bullets.
    NSString *text = [NSString new];
    text = [text stringByPaddingToLength:filledBullets withString:FilledBulletString startingAtIndex:0];
    text = [text stringByPaddingToLength:self.numberOfDigits withString:EmptyBulletString startingAtIndex:0];

    // Apply spacing attribute to string.
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text];
    [attributedText addAttribute:NSKernAttributeName
                             value:@(20.0f)
                             range:NSMakeRange(0, [text length]-1)];

    // Set the textfield's text property.
    self.attributedText = attributedText;
}

- (void)setNumberOfDigits:(NSInteger)numberOfDigits {
    _numberOfDigits = numberOfDigits;
    [self updateTextWithNumberOfFilledBullets:0];
}

#pragma mark - Accessibility

- (NSString *)accessibilityLabel {
    return ORKLocalizedString(@"PASSCODE_TEXTFIELD_ACCESSIBILITY_LABEL", nil);
}

- (NSString *)accessibilityValue {
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:FilledBulletString options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger numberOfFilledBullets = [regularExpression numberOfMatchesInString:self.text options:0 range:NSMakeRange(0, [self.text length])];
    return [NSString stringWithFormat:ORKLocalizedString(@"PASSCODE_TEXTFIELD_ACCESSIBILTIY_VALUE", nil), ORKLocalizedStringFromNumber(@(numberOfFilledBullets)), ORKLocalizedStringFromNumber(@([self.text length]))];
}

- (UIAccessibilityTraits)accessibilityTraits {
    return UIAccessibilityTraitNone;
}

@end

@implementation ORKUnitTextField {
    NSString *_managedPlaceholder;

    NSString *_unitWithNumber;

    UIColor *_unitRegularColor;
    UIColor *_unitActiveColor;

    UIColor *_savedSuffixColor;
    NSString *_savedSuffixText;

    UILabel *_suffixLabel;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(textFieldTextDidBeginEditing:) name:UITextFieldTextDidBeginEditingNotification object:self];
        [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(textFieldTextDidEndEditing:) name:UITextFieldTextDidEndEditingNotification object:self];
        [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:self];

    }
    return self;
}

- (id)ork_createTextLabelWithTextColor:(UIColor *)textColor {
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    textLabel.font = [UIFont systemFontOfSize:17];
    [textLabel setOpaque:NO];
    [textLabel setBackgroundColor:nil];
    textLabel.contentMode = UIViewContentModeRedraw;
    if (textColor != nil) {
        textLabel.textColor = textColor;
    }
    return textLabel;
}

- (void)ork_setSuffix:(NSString *)suffix withColor:(UIColor *)color {
    CGRect previousSuffixFrame = CGRectZero;
    if (_suffixLabel) {
        previousSuffixFrame = _suffixLabel.frame;
        [_suffixLabel removeFromSuperview];
        _suffixLabel = nil;
        [self setNeedsLayout];
    } else {
        previousSuffixFrame.size.height = CGRectGetHeight(self.bounds);
    }
    if (suffix.length == 0) {
        return;
    }
    if (@available(iOS 13.0, *)) {
        _suffixLabel = [self ork_createTextLabelWithTextColor:(color ? : [UIColor placeholderTextColor])];
    } else {
        _suffixLabel = [self ork_createTextLabelWithTextColor:(color ? : [UIColor ork_midGrayTintColor])];
    }
    _suffixLabel.text = suffix;
    _suffixLabel.font = self.font;
    _suffixLabel.textAlignment = NSTextAlignmentLeft;
    _suffixLabel.userInteractionEnabled = NO;
    _suffixLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    _suffixLabel.frame = previousSuffixFrame;

    // re-layout to position the suffix
    [self setNeedsLayout];
}

- (void)ork_updateSuffix:(NSString *)suffix {
    if (!_suffixLabel) {
        [self ork_setSuffix:suffix withColor:nil];
    } else {
        _suffixLabel.text = suffix;
        [self setNeedsLayout];
    }
}

- (void)ork_updateSuffix:(NSString *)suffix withColor:(UIColor *)color {
    if (NO == [color isEqual:_savedSuffixColor]) {
        if (suffix != nil) {
            _savedSuffixColor = color;
        }
        _savedSuffixText = suffix;
        [self ork_setSuffix:suffix withColor:color];
        return;
    }

    if (NO == [suffix isEqualToString:_savedSuffixText]) {
        _savedSuffixText = suffix;
        [self ork_updateSuffix:suffix];
    }
}

- (void)setManageUnitAndPlaceholder:(BOOL)manageUnitAndPlaceholder {
    _manageUnitAndPlaceholder = manageUnitAndPlaceholder;
    [self updateManagedUnitAndPlaceholder];
}

- (void)setPlaceholder:(NSString *)placeholder {
    _managedPlaceholder = placeholder;
    [self updateManagedUnitAndPlaceholder];
}

- (void)ork_setPlaceholder:(NSString *)placeholder {
    [super setPlaceholder:placeholder];
}

- (void)setUnit:(NSString *)unit {
    _unit = unit;

    if (_unit.length > 0) {
        _unitWithNumber = [NSString stringWithFormat:@" %@", unit];

        if (@available(iOS 13.0, *)) {
            _unitRegularColor = [UIColor placeholderTextColor];
            _unitActiveColor = [UIColor placeholderTextColor];
        } else {
            _unitRegularColor = [UIColor blackColor];
            _unitActiveColor = [UIColor ork_midGrayTintColor];
        }
    } else {
        _unitWithNumber = nil;
    }

    [self updateManagedUnitAndPlaceholder];
}

- (void)updateManagedUnitAndPlaceholder {
    if (_manageUnitAndPlaceholder) {
        BOOL isEditing = self.isEditing;

        UIColor *suffixColor = isEditing ? _unitActiveColor : _unitRegularColor;
            if (_managedPlaceholder.length > 0) {
                [self ork_setPlaceholder:((isEditing && _unit.length > 0) ? nil : _managedPlaceholder)];
                if (!(_hideUnitWhenAnswerEmpty && !isEditing && self.text.length == 0)) {
                    [self ork_updateSuffix:_unitWithNumber withColor:suffixColor];
                } else {
                    [self ork_updateSuffix:nil withColor:suffixColor];
                }
            } else {
                if (self.text.length > 0 || isEditing) {
                    [self ork_setPlaceholder:nil];
                    [self ork_updateSuffix:_unitWithNumber withColor:suffixColor];
                } else {
                    if (!(_hideUnitWhenAnswerEmpty && !isEditing && self.text.length == 0)) {
                        [self ork_setPlaceholder:_unit];
                        [self ork_updateSuffix:nil withColor:suffixColor];
                    } else {
                        [self ork_setPlaceholder:nil];
                        [self ork_updateSuffix:nil withColor:suffixColor];
                    }
                }
        }
    } else {
        // remove unit string
        if (_savedSuffixText.length > 0) {
            [self ork_updateSuffix:nil withColor:nil];
        }
        // put back unit string
        if ([self.placeholder isEqualToString:_managedPlaceholder] == NO) {
            [self ork_setPlaceholder:_managedPlaceholder];
        }
    }
    [self invalidateIntrinsicContentSize];
    [self layoutIfNeeded]; // layout immediatly to avoid animation glitch in which the unit label frame grows from left to right
}

- (void)textFieldTextDidBeginEditing:(NSNotification *)notification {
    [self updateManagedUnitAndPlaceholder];
}

- (void)textFieldTextDidEndEditing:(NSNotification *)notification {
    [self updateManagedUnitAndPlaceholder];

}

- (void)textFieldTextDidChange:(NSNotification *)notification {
    [self updateManagedUnitAndPlaceholder];
}

- (void)setText:(NSString *)text {
    [super setText:text];
    [self updateManagedUnitAndPlaceholder];
}

- (BOOL)isPlaceholderVisible {
    BOOL isEditing = self.isEditing;
    return (self.placeholder.length > 0) &&
            ((!isEditing && self.text.length == 0) || (isEditing && self.text.length == 0 && _unit.length == 0));
}

- (CGFloat)suffixWidthForBounds:(CGRect)bounds {
    CGFloat suffixWidth = [_suffixLabel.text sizeWithAttributes:@{NSFontAttributeName: _suffixLabel.font}].width;
    suffixWidth = MIN(suffixWidth, bounds.size.width / 2);
    return suffixWidth;
}

static const UIEdgeInsets paddingGuess = (UIEdgeInsets){.left = 2, .right = 6};

- (CGRect)textRectForBounds:(CGRect)bounds {
    CGRect textRect = [super textRectForBounds:bounds];

    // Leave room for the suffix label
    if (_suffixLabel.text.length) {
        CGFloat suffixWidth = [self suffixWidthForBounds:bounds];
        if (suffixWidth > 0) {
            suffixWidth += paddingGuess.right;
        }
        textRect.size.width = MAX(0, textRect.size.width - suffixWidth);
    }
    return textRect;
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    CGRect rect = [super editingRectForBounds:bounds];

    // Leave room for the suffix label
    if (_suffixLabel.text.length) {
        CGFloat suffixWidth = [self suffixWidthForBounds:bounds];
        if (suffixWidth > 0) {
            suffixWidth += paddingGuess.right;
        }
        rect.size.width = MAX(0, rect.size.width - suffixWidth);
    }

    return rect;
}

- (CGRect)ork_suffixFrame {
    // Get the text currently 'in' the edit field
    NSString *textToMeasure = [self isPlaceholderVisible] ? self.placeholder : self.text;
    CGSize sizeOfText = [textToMeasure sizeWithAttributes:[self defaultTextAttributes]];

    // Get the maximum size of the actual editable area (taking into account prefix/suffix/views/clear button
    CGRect textFrame = [self textRectForBounds:self.bounds];

    // Work out the size of our suffix frame
    CGRect suffixFrame = [super placeholderRectForBounds:self.bounds];
    suffixFrame.size.width = [self suffixWidthForBounds:self.bounds];

    // Take padding into account
    CGFloat xMaximum = CGRectGetMaxX(textFrame);
    if (sizeOfText.width < (textFrame.size.width - (paddingGuess.left + paddingGuess.right))) {
        // Adjust the rectangle to include the padding
        textFrame.origin.x += paddingGuess.left;
        textFrame.size.width -= paddingGuess.left + paddingGuess.right;
    } else {
        // Cover the fringe case where the padding is not applied, but the field editor has not scrolled, so the prefix/suffix could
        // overlap the text slightly.
        sizeOfText.width += paddingGuess.left + paddingGuess.right;
    }

    // Calculate position for alignment
    CGFloat xOffset = CGRectGetMinX(textFrame) + sizeOfText.width;

    // Make sure it can't escape out the right of the view
    suffixFrame.origin.x = MIN(xOffset, xMaximum);

    suffixFrame.size.height = CGRectGetHeight(self.bounds);
    suffixFrame.origin.y = 0;

    return suffixFrame;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    if (_suffixLabel) {
        [self addSubview:_suffixLabel];
        _suffixLabel.frame = [self ork_suffixFrame];
        [_suffixLabel setNeedsDisplay];
    }
}

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

#pragma mark Accessibility

- (NSString *)accessibilityValue {
    if (self.text.length > 0) {
        return ORKAccessibilityStringForVariables([super accessibilityValue], _unitWithNumber);

    }
    else if ( _managedPlaceholder ) {
        return ORKAccessibilityStringForVariables(_managedPlaceholder, _unitWithNumber);
    }

    return [super accessibilityValue];
}

- (BOOL)accessibilityActivate
{
    return [self becomeFirstResponder];
}

@end

@implementation ORKTextFieldView {

    NSMutableArray<NSLayoutConstraint *> *_errorLabelConstraints;

}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _textField = [[ORKUnitTextField alloc] init];
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _textField.translatesAutoresizingMaskIntoConstraints = NO;

        [self addSubview:_textField];
        [self setUpConstraints];
    }
    return self;
}

- (void)setUpConstraints {
    NSMutableArray *constraints = [NSMutableArray new];

    NSDictionary *views = NSDictionaryOfVariableBindings(_textField);

    [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_textField]|"
                                                                             options:NSLayoutFormatDirectionLeadingToTrailing
                                                                             metrics:nil
                                                                               views:views]];

    [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_textField]|"
                                                                             options:NSLayoutFormatDirectionLeadingToTrailing
                                                                             metrics:nil
                                                                               views:views]];

    NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:self
                                                             attribute:NSLayoutAttributeBottom
                                                             relatedBy:NSLayoutRelationEqual
                                                                toItem:_textField
                                                             attribute:NSLayoutAttributeBottom
                                                            multiplier:1.0
                                                              constant:0.0];

    // Ask to fill the available horizontal space
    NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:_textField
                                                                       attribute:NSLayoutAttributeWidth
                                                                       relatedBy:NSLayoutRelationEqual
                                                                          toItem:nil
                                                                       attribute:NSLayoutAttributeNotAnAttribute
                                                                      multiplier:1.0
                                                                        constant:ORKScreenMetricMaxDimension];

    widthConstraint.priority = UILayoutPriorityDefaultLow;
    [constraints addObject:bottomConstraint];
    [constraints addObject:widthConstraint];

    [NSLayoutConstraint activateConstraints:constraints];
}

- (CGFloat)estimatedWidth {

    NSString *placeholderAndUnit = self.textField.placeholder;
    NSString *textAndUnit = self.textField.text;

    if (self.textField.unit.length > 0) {
        NSString *unitString = [NSString stringWithFormat:@"  %@", self.textField.unit];
        placeholderAndUnit = [placeholderAndUnit stringByAppendingString:unitString];
        textAndUnit = [textAndUnit stringByAppendingString:unitString];
    }

    NSDictionary *attributes = @{ NSFontAttributeName : self.textField.font };
    CGFloat fieldWidth = MAX([placeholderAndUnit sizeWithAttributes:attributes].width,
                             [textAndUnit sizeWithAttributes:attributes].width);

    return fieldWidth;
}

- (void)setHideUnitWhenAnswerEmpty:(BOOL)hideUnitWhenAnswerEmpty {
    _textField.hideUnitWhenAnswerEmpty = hideUnitWhenAnswerEmpty;
}

- (BOOL)hideUnitWhenAnswerEmpty {
    return _textField.hideUnitWhenAnswerEmpty;
}

@end


text:
// Author: Matt Ferraro
// Description: Utility file that contains an rk4 integration function
// Date: Originally sometime in spring 2012. Revised Sept 22, 2013

/*
	Utility function, basically a for loop, that takes in a vector,
	a delta to that vector, and a gain by which to multiple the delta
	before adding it to the vector.

	Inputs:
	x_hat 		Array		Some vector
	x_dot		Array		The derivative of x_hat
	gain		float		The gain by which to multiply x_dot before adding

	Outputs:
	new_x_hat	Array		The new vector

	Mutations to Inputs:
	None
*/
function scalar_add(x_hat, x_dot, gain)
{
	var new_x_hat = [];
	for (var i = 0; i<x_hat.length; i++)
	{
		new_x_hat[i] = x_hat[i] + x_dot[i] * gain;
	}
	return new_x_hat;
}

/*
	An implementation of the Euler 1st order integration method
	as described here http://en.wikipedia.org/wiki/Euler%27s_method
	Note that this is here only as a comparison with RK4.

	Inputs:
	x_hat 		Array		the vector of all variables in the state
	deriv_func	function	a function which takes in x_hat and returns x_dot, the
							derivative of the state
	dt 			float		the total amount of time you want me to integrate over

	Outputs:
	new_x_hat	Array		the new vector of all variables in the state

	Mutations to Inputs:
	None

*/
function euler(x_hat, deriv_func, dt)
{
	// First, find the derivative of the state, yielding x_dot
	var x_dot = deriv_func(x_hat);

	// Second, multiply x_dot by dt and add it to x_hat
	var new_x_hat = scalar_add(x_hat, x_dot, dt);

	return new_x_hat;
}

/*
	An implementation of the Runge-Kutta 4th order integration method
	as described here http://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods

	Inputs:
	x_hat 		Array		the vector of all variables in the state
	deriv_func	function	a function which takes in x_hat and returns x_dot, the
							derivative of the state
	dt 			float		the total amount of time you want me to integrate over

	Outputs:
	new_x_hat	Array		the new vector of all variables in the state

	Mutations to Inputs:
	None
*/
function rk4(x_hat, deriv_func, dt)
{
	// Find the derivative of course, just like euler
	var k1 = deriv_func(x_hat);

	// Imagine euler is correct, but only for dt/2.
	// Jump to that position with that derivative, and
	// then grab the derivative there
	var x_hat_at_midpoint_k1 = scalar_add(x_hat, k1, dt/2);
	var k2 = deriv_func(x_hat_at_midpoint_k1);

	// Now go back to the beginning and move to the midpoint again,
	// But this time using k2 as x_dot. Once there, pull a
	// third estimate of x_dot
	var x_hat_at_midpoint_k2 = scalar_add(x_hat, k2, dt/2);
	var k3 = deriv_func(x_hat_at_midpoint_k2);

	// Lastly we go back to the beginning and fast forward all
	// the way to the end, using k3 as our estimated x_dot
	// Once there, pull a fourth estimate of x_dot
	var x_hat_at_end_k3 = scalar_add(x_hat, k3, dt);
	var k4 = deriv_func(x_hat_at_end_k3);

	// Now that the hard math is done, we have four different
	// estimates of what the derivative should be. All we do
	// is pull a weighted average of the 4 different estimates
	// And voila, we have our overall RK4 estimate of the derivative.
	var k_final = new Array();
	for(var i = 0; i<k1.length; i++)
	{
		k_final[i] = 1/6 * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]);
	}

	// With our estimate of the derivative in hand, all we do
	// is multiply the deriv by dt and add it to the state,
	// Then return our answer

	var new_x_hat = scalar_add(x_hat, k_final, dt);
	return new_x_hat;
}

redpajama_set_name: RedPajamaGithub


text:
package com.artclod.common.collect.base;

import java.util.Collection;
import java.util.function.Function;

/**
 * Represent one of two possible values, either a left or a right.
 * This can be thought of as an expaned {@link Option} where the none can also have a value.
 * By convention the left version is usually considered to be the failure case and the right is success.
 * Either is considered to be right biased.
 * This means operations like contains, map, and toOption assume a left value is "empty".
 *
 * @param <L> Type of left value
 * @param <R> Type of Right value
 */
public interface Either<L, R> extends Collection<R>, UnsupportMutationCollectionMixIn<R>{

	public static <L, R> Left<L, R> left(L value) {
		return new Left<>(value);
	}

	public static <L, R> Right<L, R> right(R value) {
		return new Right<>(value);
	}

	/**
	 * Returns true if this is a Left, false otherwise.
	 *
	 * @return indicates if this is left
	 */
	public boolean isLeft();

	/**
	 * Returns true if this is a Right, false otherwise.
	 *
	 * @return indicates if this is right
	 */
	public boolean isRight();

	/**
	 * Returns left value if it exists, otherwise throws
	 *
	 * @return left value
	 */
	public L left();

	/**
	 * Returns right value if it exists, otherwise throws
	 *
	 * @return right value
	 */
	public R right();

	/**
	 * If right returns value as a some, otherwise returns none
	 *
	 * @return this as an option of right value
	 */
	public Option<R> toOption();

	/**
	 * Applies fa if this is a Left or fb if this is a Right.
	 *
	 * @param fa function that will be applied if this is a left
	 * @param fb function that will be applied if this is a right
	 *
	 * @param <O> Return type result
	 * @return the results of applying the appropriate function
	 */
	public <O> O fold(Function<L, O> fa, Function<R, O> fb);

	/**
	 * Applies f if this is a right or leaves left values unchanged.
	 *
	 * @param fb function that will be applied if this is a right
	 * @param <B> Type of Right value after folding
	 * @return transformed either
	 */
	public <B> Either<L,B> map(Function<R, B> fb);

	public <LL extends L, Y> Either<LL, Y> flatMap(Function<R, Either<LL, Y>> f);

}


text:
package org.wso2.carbon.ml.core.spark.models;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.apache.spark.mllib.linalg.Vector;

import water.Key;
import water.fvec.Frame;
import water.fvec.Vec;
import water.serial.ObjectTreeBinarySerializer;
import water.util.FileUtils;
import hex.deeplearning.DeepLearningModel;

/**
 * Wraps an H2O DeeplearningModel object
 */
public class MLDeeplearningModel implements Externalizable {

    private DeepLearningModel dlModel;
    private HashMap<Double, Double> labelToH2OEnumMap;
    // string location is required because custom deserialization doesn't work
    private String storageLocation;

    public MLDeeplearningModel() {
    }

    public MLDeeplearningModel(DeepLearningModel dlModel) {
        this.dlModel = dlModel;
    }

    public void setStorageLocation(String location) {
        storageLocation = location;
    }

    /**
     * Returns the model
     *
     * @return model
     */
    public DeepLearningModel getDeepLearningModel() {
        return this.dlModel;
    }

    /**
     * Set the model
     *
     * @param model model
     */
    public void setDeepLearningModel(DeepLearningModel model) {
        this.dlModel = model;
    }

    /**
     * Predicts the label of a given input
     *
     * @param input input to predict as a vector
     * @return prediction
     */
    public double predict(Vector input) {
        double predVal = dlModel.score(input.toArray());
        return predVal;
    }

    public double[] predict(Frame inputs) {
        Frame predsFrame = dlModel.score(inputs);
        int numRows = (int) inputs.numRows();
        Vec predsVector = predsFrame.vec(0);
        double[] predVals = new double[numRows];
        for (int i = 0; i < numRows; i++) {
            predVals[i] = predsVector.at(i);
        }
        return predVals;
    }

    public String getURIStringForLocation(String loc) {
        return "file" + loc.substring(1).replace("\\", "/");
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(storageLocation);
        out.writeObject(labelToH2OEnumMap);
        @SuppressWarnings("rawtypes")
        List<Key> keys = new LinkedList<Key>();
        // cannot add published keys, gives nullpointer
        keys.add(dlModel._key);
        new ObjectTreeBinarySerializer().save(keys, FileUtils.getURI(storageLocation));
    }

    @SuppressWarnings("unchecked")
    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        storageLocation = (String) in.readObject();
        labelToH2OEnumMap = (HashMap<Double, Double>) in.readObject();
        @SuppressWarnings("rawtypes")
        List<Key> keys = new ObjectTreeBinarySerializer().load(FileUtils.getURI(storageLocation));
        this.dlModel = (DeepLearningModel) keys.get(0).get();
    }

    public DeepLearningModel getDlModel() {
        return dlModel;
    }

}


text:
namespace Ma.EntityFramework.GraphManager.Models
{
    public enum FilterType
    {
        OnlyId, OnlyUnique, IdAndUnique, IdOrUnique, IdOptionalUnique
    }
}


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

  var modules = require('modules');

  modules.get('a4c-applications', ['ngResource']).factory('applicationVersionServices', ['$resource',
    function($resource) {
      var searchVersionResource = $resource('rest/applications/:delegateId/versions/search', {}, {
        'search': {
          method: 'POST',
          isArray: false,
          headers: {
            'Content-Type': 'application/json; charset=UTF-8'
          }
        }
      });

      var applicationVersionResource = $resource('rest/applications/:delegateId/versions', {}, {
        'create': {
          method: 'POST',
          isArray: false,
          headers: {
            'Content-Type': 'application/json; charset=UTF-8'
          }
        },
        'get': {
          method: 'GET'
        }
      });

      var applicationVersionMiscResource = $resource('rest/applications/:delegateId/versions/:versionId', {}, {
        'get': {
          method: 'GET'
        },
        'delete': {
          method: 'DELETE'
        },
        'update': {
          method: 'PUT'
        }
      });

      return {
        'getFirst': applicationVersionResource.get,
        'create': applicationVersionResource.create,
        'get': applicationVersionMiscResource.get,
        'delete': applicationVersionMiscResource.delete,
        'update': applicationVersionMiscResource.update,
        'searchVersion': searchVersionResource.search
      };
    }
  ]);
});


text:
#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_DEVICE_RESOLVER_DISTRIBUTED_H_
#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_DEVICE_RESOLVER_DISTRIBUTED_H_

#include <string>
#include <vector>

#include "absl/container/flat_hash_map.h"
#include "tensorflow/core/framework/collective.h"
#include "tensorflow/core/framework/device_attributes.pb.h"

namespace tensorflow {
class DeviceMgr;
class WorkerCacheInterface;

class DeviceResolverDistributed : public DeviceResolverInterface {
 public:
  DeviceResolverDistributed(const DeviceMgr* dev_mgr,
                            WorkerCacheInterface* worker_cache,
                            const string& task_name);

  virtual ~DeviceResolverDistributed() {}

  void GetAllDeviceAttributesAsync(const std::vector<string>& devices,
                                   const std::vector<string>& tasks,
                                   std::vector<DeviceAttributes>* attributes,
                                   const StatusCallback& done) override;

  void GetDeviceAttributesAsync(const string& device, const string& task,
                                DeviceAttributes* attributes,
                                const StatusCallback& done) override;

  Status GetTaskCached(const string& task,
                       std::vector<DeviceAttributes>* attributes) override;

 protected:
  // Loads attr_table_ with device attributes retrieved from remote task.
  void RefreshRemoteAttributes(const string& device, const string& task,
                               const StatusCallback& done)
      TF_LOCKS_EXCLUDED(mu_);

  // Subroutine used by GetAllDeviceAttributesAsync.  Recursively extends
  // *attributes with DeviceAttributes of the corresponding device named
  // by inst_params.instance.device_names.
  void GetAllDeviceAttributesRecursive(
      const std::vector<string>& devices, const std::vector<string>& tasks,
      std::vector<DeviceAttributes>* attributes, const StatusCallback& done);

  const DeviceMgr* dev_mgr_;            // Not owned
  WorkerCacheInterface* worker_cache_;  // Not owned
  const string task_name_;
  mutex mu_;
  absl::flat_hash_map<string, DeviceAttributes> attr_table_ TF_GUARDED_BY(mu_);
};

}  // namespace tensorflow
#endif  // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_DEVICE_RESOLVER_DISTRIBUTED_H_


text:
package uk.stqa.mantis.model;

/**
 * Created by natla on 16/07/2016.
 */
public class MailMessage {
  public String to;
  public String text;

  public MailMessage(String to, String text){
    this.to = to;
    this.text = text;
  }
}


text:
'use strict';
var Filter = require('broccoli-filter');
var RSVP = require('rsvp');
var tempWrite = require('temp-write');
var cc = require('closurecompiler');

function CCFilter(inputTree, options) {
	if (!(this instanceof CCFilter)) {
		return new CCFilter(inputTree, options);
	}

	Filter.call(this, inputTree);

	this.inputTree = inputTree;
	this.options = options || {};
}

CCFilter.prototype = Object.create(Filter.prototype);
CCFilter.prototype.constructor = CCFilter;

CCFilter.prototype.extensions = ['js'];
CCFilter.prototype.targetExtension = 'js';

CCFilter.prototype.processString = function (str) {
	var opts = this.options;

	return tempWrite(str).then(function (tempFile) {
		return new RSVP.Promise(function (resolve, reject) {
			cc.compile(tempFile, opts, function (err, data) {
				if (err) {
					// it's only an error if no data. weird API...
					if (!data) {
						reject(err);
					}

					console.log(err);
				}

				resolve(data);
			});
		});
	});
};

module.exports = CCFilter;


text:
import {Scheme}  from "src/client/poid.js"
import PolymorphicIdentifier  from "src/client/poid.js"
import focalStorage from "src/external/focalStorage.js"
import {parseQuery, getDeepProperty} from 'utils'

var lastTokenPromted
var todoistData

/*MD

[API documentation](https://developer.todoist.com/sync/v8)

MD*/

export class TodoistScheme extends Scheme {

  get scheme() {
    return "todoist"
  }

  async todoistToken() {
    var token = await focalStorage.getItem("todoist-token")
    if(!token && (!lastTokenPromted || ((Date.now() - lastTokenPromted) > 1000 * 5))) {
      // don't ask again for 5 seconds...
      lastTokenPromted = Date.now()
      token = await lively.prompt("todoist token required: ")
      if (token) {
        focalStorage.setItem("todoist-token", token)
      }
    }
    return token
  }

  resolve() {
    return true
  }

  async fetchData() {
    return await fetch(`https://todoist.com/api/v8/sync`+
      `?token=${await this.todoistToken()}`+
      `&sync_token=*`+
      `&resource_types=${encodeURI(JSON.stringify(["all"]))}`, {
          method: 'POST',
      }).then(r => r.json())
  }

  async getData() {
    if (!todoistData)  todoistData = await this.fetchData()
    return todoistData
  }

 async renderHTML(result) {
   return "<pre>" + JSON.stringify(result, undefined, 2) + "</pre>"
 }

  async GET(options) {
    let data = await this.getData()
    let urlObj = new URL(this.url)
    let m = urlObj.pathname.match(/^\/*([^/]+)\/?([^/]+)?$/)
    let type = m && m[1]
    let id = m && m[2]
     let result;
    if (!type ) {
      result =  data
    } else {
      let list = data[type]
      if (!id) {
       result =  list
      } else {
       let item = list.find(ea => ea.id == id)
       result =  item
      }
    }
    if (urlObj.search == "?html") {
      return new Response(await this.renderHTML(result), {status: 200})
    }
    return new Response(JSON.stringify(result, undefined, 2), {status: 200})
  }

  itemToFile(type, item) {
    return {
      name: "" + item.id,
      title: item.name ||
        (item.content ? ("" + item.content).slice(0, 30) : undefined),
      parent: this.scheme + "://" + type + "/",
      type: "file",
    }
  }

  async OPTIONS() {
    let data = await this.getData()
    let urlObj = new URL(this.url)
    let m = urlObj.pathname.match(/^\/*([^/]+)\/?([^/]+)?$/)
    let type = m && m[1]
    let id = m && m[2]
    lively.notify("path" +urlObj.pathname+"type: " + type + " id:" + id)
    let result;
    if (!type ) {
      result =  {
        name: "root",
        type: "directory",
        parent: this.scheme + "://",
        contents: Object.keys(data).map(ea => ({
          name: ea,
          type: data[ea].map ? "directory" : "file"
        }))
      }
    } else {
      let list = data[type]
      if (!id) {
       result =  {
          name: type,
          type: list.map ? "directory" : "file",
          parent: this.scheme + "://",
          contents:  list.map ? list.map(ea => this.itemToFile(type, ea)) : undefined
       }
      } else {
       let item = list.find(ea => ea.id == id)
       result =  this.itemToFile(type, item)
      }
    }
    return new Response(JSON.stringify(result), {status: 200})
  }
}

PolymorphicIdentifier.register(TodoistScheme)


text:
casper.test.begin('Config Input', 12, function suite(test) {
  casper.start('demo/demo1.html', function() {
  });

  casper.on('remote.message', function(message) {
    this.echo(message);
  });

  casper.then(function() {
    test.assertExists('input[aria-describedby="fnameValidations"][data-validation="fname"][maxlength="15"][autocorrect="off"][autocapitalize="true"]');
    test.assertExists('input[aria-describedby="hphoneValidations"][data-validation="phone"][maxlength="14"][autocorrect="off"][autocapitalize="off"][placeholder="(XXX) XXX-XXXX"]');
    test.assertExists('input[aria-describedby="wphoneValidations"][data-validation="phone"][maxlength="14"][autocorrect="off"][autocapitalize="off"][placeholder="(XXX) XXX-XXXX"]');
    test.assertExists('input[aria-describedby="dobValidations"][data-validation="true"][maxlength="2"][autocorrect="off"][autocapitalize="off"]');
    test.assertExists('input[aria-describedby="abartnValidations"][data-validation="abartn"][maxlength="9"][autocorrect="off"][autocapitalize="off"]');
    test.assertExists('select[aria-describedby="genderValidations"][data-validation="true"]');

    test.assertExists('#fnameValidations');
    test.assertExists('#hphoneValidations');
    test.assertExists('#wphoneValidations');
    test.assertExists('#dobValidations');
    test.assertExists('#abartnValidations');
    test.assertExists('#genderValidations');

    // Possible test for Placeholder Text
    /*
    test.assertEvalEquals(function() {
      var inputList = document.getElementsByTagName('input');
      var badInputNum = 0;

      for(var i=0;i<inputList.length;i++) {
        if(!inputList.item(i).getAttribute('maxlength') || !inputList.item(i).getAttribute('autocorrect') || !inputList.item(i).getAttribute('autocapitalize') ) {
          badInputNum +=1;
        }

        if($(inputList.item(i)).data('validatedInput').validator.placeholder) {
          var placeholderTxt = $(inputList.item(i)).data('validatedInput').validator.placeholder;
          if($(inputList.item(i)).attr('placeholder') !== placeholderTxt) {
            badInputNum+=1;
          }
        }
      }
      return badInputNum;
    },0);
    */
  });

  casper.run(function() {
    test.done();
  });
});


text: {{ partial "large_icon.html" "exclamation-mark" }}


text:
@extends('layouts.warehouse')

@section('content')

Welcome to the Warehouse System

<button type="button" class="btn btn-primary">Add main Category</button>

<button type="button" class="btn btn-primary">Add sub Category</button>

<button type="button" class="btn btn-primary">Add Storage</button>

<button type="button" class="btn btn-primary">Add Storage building</button>

<button type="button" class="btn btn-primary">Add Wares</button>

<button type="button" class="btn btn-primary">Search Wares</button>

<button type="button" class="btn btn-primary">Show Categories</button>

<button type="button" class="btn btn-primary">Show Storage</button>

<button type="button" class="btn btn-primary">Show Wares</button>

@endsection


text:
package com.thoughtworks.go.plugin.api;

@GoPluginApiMarker
public interface TestGoPluginExtensionPoint {
}


text:
package com.opengamma.analytics.financial.horizon.rolldown;

import org.apache.commons.lang.NotImplementedException;

import com.opengamma.analytics.financial.horizon.RolldownFunction;
import com.opengamma.analytics.financial.provider.description.interestrate.BlackSTIRFuturesProviderInterface;
import com.opengamma.analytics.financial.provider.description.interestrate.BlackSTIRFuturesSmileProvider;
import com.opengamma.analytics.financial.provider.description.interestrate.BlackSTIRFuturesSmileProviderDiscount;
import com.opengamma.analytics.financial.provider.description.interestrate.MulticurveProviderDiscount;
import com.opengamma.analytics.financial.provider.description.interestrate.ParameterProviderInterface;
import com.opengamma.analytics.math.surface.Surface;

/**
 * Produces a {@link BlackSTIRFuturesProviderInterface} that has been shifted forward in time with slide. That is, it moves in such a way
 * that the vol or rate requested for the same maturity DATE will be equal for the original market data bundle and the shifted one.
 */
public final class StirFutureOptionBlackDataForwardSlideRolldown implements RolldownFunction<BlackSTIRFuturesProviderInterface> {
  /**
   * A static instance.
   */
  public static final StirFutureOptionBlackDataForwardSlideRolldown INSTANCE = new StirFutureOptionBlackDataForwardSlideRolldown();

  /**
   * Private constructor
   */
  private StirFutureOptionBlackDataForwardSlideRolldown() {
  }

  @Override
  public BlackSTIRFuturesProviderInterface rollDown(final BlackSTIRFuturesProviderInterface data, final double time) {
    if (!(data instanceof BlackSTIRFuturesSmileProvider)) {
      throw new NotImplementedException("Unhandled data type " + data.getClass());
    }
    final ParameterProviderInterface shiftedCurves = CurveProviderForwardSlideRolldown.INSTANCE.rollDown(data, time);
    final Surface<Double, Double, Double> surface = ((BlackSTIRFuturesSmileProvider) data).getBlackParameters();
    final Surface<Double, Double, Double> shiftedVolatilitySurface = SurfaceForwardSlideRolldown.INSTANCE.rollDown(surface, time);
    if (shiftedCurves instanceof MulticurveProviderDiscount) {
      return new BlackSTIRFuturesSmileProviderDiscount((MulticurveProviderDiscount) shiftedCurves, shiftedVolatilitySurface,
          data.getFuturesIndex());
    }
    throw new NotImplementedException("Unhandled data type " + shiftedCurves.getClass());
  }
}


text:
Units
=====

This document will try to describe what units are, why they are a useful concept, and how to use and create them.

* [Why](#why)
* [How they work](#how-they-work)
* [Why they are named Units](#why-they-are-named-units)
* [RxCocoa units](#rxcocoa-units)
* [Driver unit](#driver-unit)
    * [Why it's named Driver](#why-its-named-driver)
    * [Practical usage example](#practical-usage-example)

## Why

Swift has a powerful type system that can be used to improve correctness and stability of applications and make using Rx a more intuitive and straightforward experience.

**Units are specific only to the [RxCocoa](https://github.com/ReactiveX/RxSwift/tree/master/RxCocoa) project. However, the same principles could easily be implemented in other Rx implementations, if necessary. There is no private API magic needed.**

**Units are totally optional. You can use raw observable sequences everywhere in your program and all RxCocoa APIs work with observable sequences.**

Units also help communicate and ensure observable sequence properties across interface boundaries.

Here are some of the properties that are important when writing Cocoa/UIKit applications.

* Can't error out
* Observe on main scheduler
* Subscribe on main scheduler
* Sharing side effects

## How they work

At its core, it's just a struct with a reference to observable sequence.

You can think of them as a kind of builder pattern for observable sequences. When a sequence is built, calling `.asObservable()` will transform a unit into a vanilla observable sequence.

## Why they are named Units

Using a couple analogies will help us reason about unfamiliar concepts. Here are some analogies showing how units in physics and RxCocoa (Rx units) are similar.

Analogies:

| Physical units                      | Rx units                                                            |
|-------------------------------------|---------------------------------------------------------------------|
| number (one value)                  | observable sequence (sequence of values)                            |
| dimensional unit (m, s, m/s, N ...) | Swift struct (Driver, ControlProperty, ControlEvent, ...) |

A physical unit is a pair of a number and a corresponding dimensional unit.

An Rx unit is a pair of an observable sequence and a corresponding struct that describes observable sequence properties.

Numbers are the basic compositional glue when working with physical units: usually real or complex numbers.

Observable sequences are the basic compositional glue when working with Rx units.

Physical units and [dimensional analysis](https://en.wikipedia.org/wiki/Dimensional_analysis#Checking_equations_that_involve_dimensions) can alleviate certain classes of errors during complex calculations.

Type checking Rx units can alleviate certain classes of logic errors when writing reactive programs.

Numbers have operators: `+`, `-`, `*`, `/`.

Observable sequences also have operators: `map`, `filter`, `flatMap` ...

Physics units define operations by using corresponding number operations. E.g.

`/` operation on physical units is defined using `/` operation on numbers.

11 m / 0.5 s = ...
* First, convert the unit to **numbers** and **apply** `/` **operator** `11 / 0.5 = 22`
* Then, calculate the unit (m / s)
* Lastly, combine the result = 22 m / s

Rx units define operations by using corresponding observable sequence operations (this is how operators work internally). E.g.

The `map` operation on `Driver` is defined using the `map` operation on its observable sequence.

```swift
let d: Driver<Int> = Driver.just(11)
driver.map { $0 / 0.5 } = ...
```

* First, convert `Driver` to **observable sequence** and **apply** `map` **operator**
```swift
let mapped = driver.asObservable().map { $0 / 0.5 } // this `map` is defined on observable sequence
```

* Then, combine that to get the unit value
```swift
let result = Driver(mapped)
```

There is a set of basic units in physics [(`m`, `kg`, `s`, `A`, `K`, `cd`, `mol`)](https://en.wikipedia.org/wiki/SI_base_unit) that is orthogonal.

There is a set of basic interesting properties for observable sequences in `RxCocoa` that is orthogonal.

    * Can't error out
    * Observe on main scheduler
    * Subscribe on main scheduler
    * Sharing side effects

Derived units in physics sometimes have special names.

E.g.
```
N (Newton) = kg * m / s / s
C (Coulomb) = A * s
T (Tesla) = kg / A / s / s
```

Rx derived units also have special names.

E.g.
```
Driver = (can't error out) * (observe on main scheduler) * (sharing side effects)
ControlProperty = (sharing side effects) * (subscribe on main scheduler)
```

Conversion between different units in physics is done with the help of operators defined on numbers `*`, `/`.

Conversion between different Rx units in done with the help of observable sequence operators.

E.g.

```
Can't error out = catchError
Observe on main scheduler = observeOn(MainScheduler.instance)
Subscribe on main scheduler = subscribeOn(MainScheduler.instance)
Sharing side effects = share* (one of the `share` operators)
```

## RxCocoa units

### Driver unit

* Can't error out
* Observe on main scheduler
* Sharing side effects (`shareReplayLatestWhileConnected`)

### ControlProperty / ControlEvent

* Can't error out
* Subscribe on main scheduler
* Observe on main scheduler
* Sharing side effects

## Driver

This is the most elaborate unit. Its intention is to provide an intuitive way to write reactive code in the UI layer.

### Why it's named Driver

Its intended use case was to model sequences that drive your application.

E.g.
* Drive UI from CoreData model
* Drive UI using values from other UI elements (bindings)
...

Like normal operating system drivers, in case a sequence errors out, your application will stop responding to user input.

It is also extremely important that those elements are observed on the main thread because UI elements and application logic are usually not thread safe.

Also, `Driver` unit builds an observable sequence that shares side effects.

E.g.

### Practical usage example

This is a typical beginner example.

```swift
let results = query.rx.text
    .throttle(0.3, scheduler: MainScheduler.instance)
    .flatMapLatest { query in
        fetchAutoCompleteItems(query)
    }

results
    .map { "\($0.count)" }
    .bindTo(resultCount.rx.text)
    .addDisposableTo(disposeBag)

results
    .bindTo(resultsTableView.rx.itemsWithCellIdentifier("Cell")) { (_, result, cell) in
        cell.textLabel?.text = "\(result)"
    }
    .addDisposableTo(disposeBag)
```

The intended behavior of this code was to:
* Throttle user input
* Contact server and fetch a list of user results (once per query)
* Bind the results to two UI elements: results table view and a label that displays the number of results

So, what are the problems with this code?:
* If the `fetchAutoCompleteItems` observable sequence errors out (connection failed or parsing error), this error would unbind everything and the UI wouldn't respond any more to new queries.
* If `fetchAutoCompleteItems` returns results on some background thread, results would be bound to UI elements from a background thread which could cause non-deterministic crashes.
* Results are bound to two UI elements, which means that for each user query, two HTTP requests would be made, one for each UI element, which is not the intended behavior.

A more appropriate version of the code would look like this:

```swift
let results = query.rx.text
    .throttle(0.3, scheduler: MainScheduler.instance)
    .flatMapLatest { query in
        fetchAutoCompleteItems(query)
            .observeOn(MainScheduler.instance)  // results are returned on MainScheduler
            .catchErrorJustReturn([])           // in the worst case, errors are handled
    }
    .shareReplay(1)                             // HTTP requests are shared and results replayed
                                                // to all UI elements

results
    .map { "\($0.count)" }
    .bindTo(resultCount.rx.text)
    .addDisposableTo(disposeBag)

results
    .bindTo(resultTableView.rx.itemsWithCellIdentifier("Cell")) { (_, result, cell) in
        cell.textLabel?.text = "\(result)"
    }
    .addDisposableTo(disposeBag)
```

Making sure all of these requirements are properly handled in large systems can be challenging, but there is a simpler way of using the compiler and units to prove these requirements are met.

The following code looks almost the same:

```swift
let results = query.rx.text.asDriver()        // This converts a normal sequence into a `Driver` sequence.
    .throttle(0.3, scheduler: MainScheduler.instance)
    .flatMapLatest { query in
        fetchAutoCompleteItems(query)
            .asDriver(onErrorJustReturn: [])  // Builder just needs info about what to return in case of error.
    }

results
    .map { "\($0.count)" }
    .drive(resultCount.rx.text)               // If there is a `drive` method available instead of `bindTo`,
    .addDisposableTo(disposeBag)              // that means that the compiler has proven that all properties
                                              // are satisfied.
results
    .drive(resultTableView.rx.itemsWithCellIdentifier("Cell")) { (_, result, cell) in
        cell.textLabel?.text = "\(result)"
    }
    .addDisposableTo(disposeBag)
```

So what is happening here?

This first `asDriver` method converts the `ControlProperty` unit to a `Driver` unit.

```swift
query.rx.text.asDriver()
```

Notice that there wasn't anything special that needed to be done. `Driver` has all of the properties of the `ControlProperty` unit, plus some more. The underlying observable sequence is just wrapped as a `Driver` unit, and that's it.

The second change is:

```swift
.asDriver(onErrorJustReturn: [])
```

Any observable sequence can be converted to `Driver` unit, as long as it satisfies 3 properties:
* Can't error out
* Observe on main scheduler
* Sharing side effects (`shareReplayLatestWhileConnected`)

So how do you make sure those properties are satisfied? Just use normal Rx operators. `asDriver(onErrorJustReturn: [])` is equivalent to following code.

```
let safeSequence = xs
  .observeOn(MainScheduler.instance)       // observe events on main scheduler
  .catchErrorJustReturn(onErrorJustReturn) // can't error out
  .shareReplayLatestWhileConnected         // side effects sharing
return Driver(raw: safeSequence)           // wrap it up
```

The final piece is using `drive` instead of using `bindTo`.

`drive` is defined only on the `Driver` unit. This means that if you see `drive` somewhere in code, that observable sequence can never error out and it observes on the main thread, which is safe for binding to a UI element.

Note however that, theoretically, someone could still define a `drive` method to work on `ObservableType` or some other interface, so to be extra safe, creating a temporary definition with `let results: Driver<[Results]> = ...` before binding to UI elements would be necessary for complete proof. However, we'll leave it up to the reader to decide whether this is a realistic scenario or not.


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="QuadMesh" inherits="PlaneMesh" version="4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../class.xsd">
	<brief_description>
		Class representing a square mesh facing the camera.
	</brief_description>
	<description>
		Class representing a square [PrimitiveMesh]. This flat mesh does not have a thickness. By default, this mesh is aligned on the X and Y axes; this rotation is more suited for use with billboarded materials. A [QuadMesh] is equivalent to a [PlaneMesh] except its default [member PlaneMesh.orientation] is [constant PlaneMesh.FACE_Z].
	</description>
	<tutorials>
		<link title="GUI in 3D Demo">https://godotengine.org/asset-library/asset/127</link>
		<link title="2D in 3D Demo">https://godotengine.org/asset-library/asset/129</link>
	</tutorials>
	<members>
		<member name="orientation" type="int" setter="set_orientation" getter="get_orientation" overrides="PlaneMesh" enum="PlaneMesh.Orientation" default="2" />
		<member name="size" type="Vector2" setter="set_size" getter="get_size" overrides="PlaneMesh" default="Vector2(1, 1)" />
	</members>
</class>


text:
MACRO(VTK_WRAP_JAVA2 TARGET SOURCE_LIST_NAME)
  # convert to the WRAP3 signature
  vtk_wrap_java3(${TARGET} ${SOURCE_LIST_NAME} "${ARGN}")
ENDMACRO(VTK_WRAP_JAVA2)

macro(vtk_wrap_java3 TARGET SRC_LIST_NAME SOURCES)
  IF(NOT VTK_PARSE_JAVA_EXE)
    MESSAGE(SEND_ERROR "VTK_PARSE_JAVA_EXE not specified when calling VTK_WRAP_JAVA3")
  ENDIF(NOT VTK_PARSE_JAVA_EXE)
  IF(NOT VTK_WRAP_JAVA_EXE)
    MESSAGE(SEND_ERROR "VTK_WRAP_JAVA_EXE not specified when calling VTK_WRAP_JAVA3")
  ENDIF(NOT VTK_WRAP_JAVA_EXE)

  IF(CMAKE_GENERATOR MATCHES "NMake Makefiles")
    SET(verbatim "")
    SET(quote "\"")
  ELSE(CMAKE_GENERATOR MATCHES "NMake Makefiles")
    SET(verbatim "VERBATIM")
    SET(quote "")
  ENDIF(CMAKE_GENERATOR MATCHES "NMake Makefiles")

  # Initialize the custom target counter.
  IF(VTK_WRAP_JAVA_NEED_CUSTOM_TARGETS)
    SET(VTK_WRAP_JAVA_CUSTOM_COUNT "")
    SET(VTK_WRAP_JAVA_CUSTOM_NAME ${TARGET})
    SET(VTK_WRAP_JAVA_CUSTOM_LIST)
  ENDIF(VTK_WRAP_JAVA_NEED_CUSTOM_TARGETS)

  GET_DIRECTORY_PROPERTY(TMP_DEF_LIST DEFINITION COMPILE_DEFINITIONS)
  SET(TMP_DEFINITIONS)
  FOREACH(TMP_DEF ${TMP_DEF_LIST})
    SET(TMP_DEFINITIONS ${TMP_DEFINITIONS} -D "${quote}${TMP_DEF}${quote}")
  ENDFOREACH(TMP_DEF ${TMP_DEF_LIST})

  IF(VTK_WRAP_INCLUDE_DIRS)
    SET(TMP_INCLUDE_DIRS ${VTK_WRAP_INCLUDE_DIRS})
  ELSE(VTK_WRAP_INCLUDE_DIRS)
    SET(TMP_INCLUDE_DIRS ${VTK_INCLUDE_DIRS})
  ENDIF(VTK_WRAP_INCLUDE_DIRS)
  SET(TMP_INCLUDE)
  FOREACH(INCLUDE_DIR ${TMP_INCLUDE_DIRS})
    SET(TMP_INCLUDE ${TMP_INCLUDE} -I "${quote}${INCLUDE_DIR}${quote}")
  ENDFOREACH(INCLUDE_DIR ${TMP_INCLUDE_DIRS})

  IF (VTK_WRAP_HINTS)
    SET(TMP_HINTS "--hints" "${quote}${VTK_WRAP_HINTS}${quote}")
  ELSE (VTK_WRAP_HINTS)
    SET(TMP_HINTS)
  ENDIF (VTK_WRAP_HINTS)

  IF (KIT_HIERARCHY_FILE)
    SET(TMP_HIERARCHY "--types" "${quote}${KIT_HIERARCHY_FILE}${quote}")
  ELSE (KIT_HIERARCHY_FILE)
    SET(TMP_HIERARCHY)
  ENDIF (KIT_HIERARCHY_FILE)

  SET(VTK_JAVA_DEPENDENCIES)
  SET(VTK_JAVA_DEPENDENCIES_FILE)
  # For each class
  FOREACH(FILE ${SOURCES})
    # should we wrap the file?
    get_source_file_property(TMP_WRAP_EXCLUDE ${FILE} WRAP_EXCLUDE)

    # we don't wrap the headers in Java
    get_source_file_property(TMP_WRAP_HEADER ${FILE} WRAP_HEADER)

    # some wrapped files need to be compiled as objective C++
    get_source_file_property(TMP_WRAP_OBJC ${FILE} WRAP_JAVA_OBJC)

    # if we should wrap it
    IF (NOT TMP_WRAP_EXCLUDE AND NOT TMP_WRAP_HEADER)

      # what is the filename without the extension
      GET_FILENAME_COMPONENT(TMP_FILENAME ${FILE} NAME_WE)

      # the input file might be full path so handle that
      GET_FILENAME_COMPONENT(TMP_FILEPATH ${FILE} PATH)

      # compute the input filename
      IF (TMP_FILEPATH)
        SET(TMP_INPUT ${TMP_FILEPATH}/${TMP_FILENAME}.h)
      ELSE (TMP_FILEPATH)
        SET(TMP_INPUT ${CMAKE_CURRENT_SOURCE_DIR}/${TMP_FILENAME}.h)
      ENDIF (TMP_FILEPATH)

      # is it abstract?
      GET_SOURCE_FILE_PROPERTY(TMP_ABSTRACT ${FILE} ABSTRACT)
      IF (TMP_ABSTRACT)
        SET(TMP_CONCRETE "--abstract")
      ELSE (TMP_ABSTRACT)
        SET(TMP_CONCRETE "--concrete")
      ENDIF (TMP_ABSTRACT)

      # use ".mm" suffix if file must be compiled with objective C++
      IF(TMP_WRAP_OBJC)
        SET(TMP_WRAPPED_FILENAME ${TMP_FILENAME}Java.mm)
      ELSE(TMP_WRAP_OBJC)
        SET(TMP_WRAPPED_FILENAME ${TMP_FILENAME}Java.cxx)
      ENDIF(TMP_WRAP_OBJC)

      # new source file is nameJava.cxx, add to resulting list
      SET(${SRC_LIST_NAME} ${${SRC_LIST_NAME}}
        ${TMP_WRAPPED_FILENAME})

      # add custom command to output
      ADD_CUSTOM_COMMAND(
        OUTPUT ${VTK_JAVA_HOME}/${TMP_FILENAME}.java
        DEPENDS ${VTK_PARSE_JAVA_EXE} ${VTK_WRAP_HINTS} ${TMP_INPUT}
        ${KIT_HIERARCHY_FILE}
        COMMAND ${VTK_PARSE_JAVA_EXE}
        ARGS
        ${TMP_CONCRETE}
        ${TMP_HINTS}
        ${TMP_HIERARCHY}
        ${TMP_DEFINITIONS}
        ${TMP_INCLUDE}
        "${quote}${TMP_INPUT}${quote}"
        "${quote}${VTK_JAVA_HOME}/${TMP_FILENAME}.java${quote}"
        COMMENT "Java Wrappings - generating ${TMP_FILENAME}.java"
        )

      # add custom command to output
      ADD_CUSTOM_COMMAND(
        OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${TMP_WRAPPED_FILENAME}
        DEPENDS ${VTK_WRAP_JAVA_EXE} ${VTK_WRAP_HINTS} ${TMP_INPUT}
        ${KIT_HIERARCHY_FILE}
        COMMAND ${VTK_WRAP_JAVA_EXE}
        ARGS
        ${TMP_CONCRETE}
        ${TMP_HINTS}
        ${TMP_HIERARCHY}
        ${TMP_DEFINITIONS}
        ${TMP_INCLUDE}
        "${quote}${TMP_INPUT}${quote}"
        "${quote}${CMAKE_CURRENT_BINARY_DIR}/${TMP_WRAPPED_FILENAME}${quote}"
        COMMENT "Java Wrappings - generating ${TMP_WRAPPED_FILENAME}"
        )

      SET(VTK_JAVA_DEPENDENCIES ${VTK_JAVA_DEPENDENCIES} "${VTK_JAVA_HOME}/${TMP_FILENAME}.java")
      SET(VTK_JAVA_DEPENDENCIES_FILE
        "${VTK_JAVA_DEPENDENCIES_FILE}\n  \"${VTK_JAVA_HOME}/${TMP_FILENAME}.java\"")

      # Add this output to a custom target if needed.
      IF(VTK_WRAP_JAVA_NEED_CUSTOM_TARGETS)
        SET(VTK_WRAP_JAVA_CUSTOM_LIST ${VTK_WRAP_JAVA_CUSTOM_LIST}
          ${CMAKE_CURRENT_BINARY_DIR}/${TMP_WRAPPED_FILENAME}
          )
        SET(VTK_WRAP_JAVA_CUSTOM_COUNT ${VTK_WRAP_JAVA_CUSTOM_COUNT}x)
        IF(VTK_WRAP_JAVA_CUSTOM_COUNT MATCHES "^${VTK_WRAP_JAVA_CUSTOM_LIMIT}$")
          SET(VTK_WRAP_JAVA_CUSTOM_NAME ${VTK_WRAP_JAVA_CUSTOM_NAME}Hack)
          ADD_CUSTOM_TARGET(${VTK_WRAP_JAVA_CUSTOM_NAME} DEPENDS ${VTK_WRAP_JAVA_CUSTOM_LIST})
          SET(KIT_JAVA_DEPS ${VTK_WRAP_JAVA_CUSTOM_NAME})
          SET(VTK_WRAP_JAVA_CUSTOM_LIST)
          SET(VTK_WRAP_JAVA_CUSTOM_COUNT)
        ENDIF(VTK_WRAP_JAVA_CUSTOM_COUNT MATCHES "^${VTK_WRAP_JAVA_CUSTOM_LIMIT}$")
      ENDIF(VTK_WRAP_JAVA_NEED_CUSTOM_TARGETS)
    ENDIF ()
  ENDFOREACH(FILE)

  ADD_CUSTOM_TARGET("${TARGET}JavaClasses" ALL DEPENDS ${VTK_JAVA_DEPENDENCIES})
  SET(dir ${CMAKE_CURRENT_SOURCE_DIR})
  IF(VTK_WRAP_JAVA3_INIT_DIR)
    SET(dir ${VTK_WRAP_JAVA3_INIT_DIR})
  ENDIF(VTK_WRAP_JAVA3_INIT_DIR)
  CONFIGURE_FILE("${dir}/JavaDependencies.cmake.in"
    "${CMAKE_CURRENT_BINARY_DIR}/JavaDependencies.cmake" IMMEDIATE @ONLY)
endmacro()

# VS 6 does not like needing to run a huge number of custom commands
# when building a single target.  Generate some extra custom targets
# that run the custom commands before the main target is built.  This
# is a hack to work-around the limitation.  The test to enable it is
# done here since it does not need to be done for every macro
# invocation.
IF(CMAKE_GENERATOR MATCHES "^Visual Studio 6$")
  SET(VTK_WRAP_JAVA_NEED_CUSTOM_TARGETS 1)
  SET(VTK_WRAP_JAVA_CUSTOM_LIMIT x)
  # Limit the number of custom commands in each target
  # to 2^7.
  FOREACH(t 1 2 3 4 5 6 7)
    SET(VTK_WRAP_JAVA_CUSTOM_LIMIT
      ${VTK_WRAP_JAVA_CUSTOM_LIMIT}${VTK_WRAP_JAVA_CUSTOM_LIMIT})
  ENDFOREACH(t)
ENDIF(CMAKE_GENERATOR MATCHES "^Visual Studio 6$")

MACRO(VTK_GENERATE_JAVA_DEPENDENCIES TARGET)

  SET (javaPath "${VTK_BINARY_DIR}/java")
  IF (USER_JAVA_CLASSPATH)
    SET (javaPath "${USER_JAVA_PATH};${VTK_BINARY_DIR}/java")
  ENDIF (USER_JAVA_CLASSPATH)

  SET (OUT_TEXT)
  SET (sources)

  # get the classes for this lib
  FOREACH(srcName ${ARGN})

    # what is the filename without the extension
    GET_FILENAME_COMPONENT(srcNameWe "${srcName}" NAME_WE)

    # the input file might be full path so handle that
    GET_FILENAME_COMPONENT(srcPath "${srcName}" PATH)

    SET (OUT_TEXT ${OUT_TEXT} "\n    dummy = new ${srcNameWe}()")
    SET (sources ${sources} "${srcName}")
  ENDFOREACH(srcName)

  # each lib will have an associated driver class
  SET (driverSrc "${javaPath}/vtk/vtk${TARGET}Driver.java")
  SET (driverClass "${javaPath}/vtk/vtk${TARGET}Driver.class")

  # generate vtk${TARGET}Driver.java using TARGET_NAME and OUT_TEXT
  SET (TARGET_NAME ${TARGET})
  CONFIGURE_FILE(
    "${VTK_CMAKE_DIR}/vtkJavaDriver.java.in"
    "${driverSrc}"
    COPY_ONLY
    IMMEDIATE
    )

  # add a custom command to compile the generated file
  ADD_CUSTOM_COMMAND(
    OUTPUT "${driverClass}"
    COMMAND "${JAVA_COMPILE}"
      -source 5 -classpath "${javaPath}" "${driverSrc}"
    DEPENDS ${sources}
    )

  # make the library target depend on vtk${TARGET}Driver.class
  ADD_CUSTOM_COMMAND(TARGET ${TARGET} SOURCE ${TARGET} DEPENDS "${driverClass}")

ENDMACRO()


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.VisualStudio.LanguageServices.Telemetry;
using Microsoft.VisualStudio.Telemetry;

namespace Microsoft.CodeAnalysis.ErrorReporting
{
    /// <summary>
    /// Controls whether or not we actually report the failure.
    /// There are situations where we know we're in a bad state and any further reports are unlikely to be
    /// helpful, so we shouldn't send them.
    /// </summary>
    internal static class WatsonDisabled
    {
        // we have it this way to make debugging easier since VS debugger can't reach
        // static type with same fully qualified name in multiple dlls.
        public static bool s_reportWatson = true;
    }

    internal static class WatsonReporter
    {
        /// <summary>
        /// The default callback to pass to <see cref="TelemetrySessionExtensions.PostFault(TelemetrySession, string, string, Exception, Func{IFaultUtility, int})"/>.
        /// Returning "0" signals that we should send data to Watson; any other value will cancel the Watson report.
        /// </summary>
        private static Func<IFaultUtility, int> s_defaultCallback = _ => 0;

        /// <summary>
        /// Report Non-Fatal Watson
        /// </summary>
        /// <param name="exception">Exception that triggered this non-fatal error</param>
        public static void Report(Exception exception)
        {
            Report("Roslyn NonFatal Watson", exception, WatsonSeverity.Default);
        }

        /// <summary>
        /// Report Non-Fatal Watson
        /// </summary>
        /// <param name="exception">Exception that triggered this non-fatal error</param>
        /// <param name="severity">indicate <see cref="WatsonSeverity"/> of NFW</param>
        public static void Report(Exception exception, WatsonSeverity severity)
        {
            Report("Roslyn NonFatal Watson", exception, severity);
        }

        /// <summary>
        /// Report Non-Fatal Watson
        /// </summary>
        /// <param name="description">any description you want to save with this watson report</param>
        /// <param name="exception">Exception that triggered this non-fatal error</param>
        /// <param name="severity">indicate <see cref="WatsonSeverity"/> of NFW</param>
        public static void Report(string description, Exception exception, WatsonSeverity severity = WatsonSeverity.Default)
        {
            Report(description, exception, s_defaultCallback, severity);
        }

        /// <summary>
        /// Report Non-Fatal Watson
        /// </summary>
        /// <param name="description">any description you want to save with this watson report</param>
        /// <param name="exception">Exception that triggered this non-fatal error</param>
        /// <param name="callback">Callback to include extra data with the NFW. Note that we always collect
        /// a dump of the current process, but this can be used to add further information or files to the
        /// CAB.</param>
        /// <param name="severity">indicate <see cref="WatsonSeverity"/> of NFW</param>
        public static void Report(string description, Exception exception, Func<IFaultUtility, int> callback, WatsonSeverity severity = WatsonSeverity.Default)
        {
            var critical = severity == WatsonSeverity.Critical;
            var emptyCallstack = exception.SetCallstackIfEmpty();

            if (!WatsonDisabled.s_reportWatson ||
                !exception.ShouldReport())
            {
                return;
            }

            var faultEvent = new FaultEvent(
                eventName: FunctionId.NonFatalWatson.GetEventName(),
                description: description,
                critical ? FaultSeverity.Critical : FaultSeverity.Diagnostic,
                exceptionObject: exception,
                gatherEventDetails: arg =>
                {
                    // always add current processes dump
                    arg.AddProcessDump(System.Diagnostics.Process.GetCurrentProcess().Id);

                    return callback(arg);
                });

            // add extra bucket parameters to bucket better in NFW
            // we do it here so that it gets bucketted better in both
            // watson and telemetry.
            faultEvent.SetExtraParameters(exception, emptyCallstack);

            TelemetryService.DefaultSession.PostEvent(faultEvent);

            if (exception is OutOfMemoryException || critical)
            {
                // Once we've encountered one OOM or Critial NFW,
                // we're likely to see more. There will probably be other
                // failures as a direct result of the OOM or critical NFW, as well.
                // These aren't helpful so we should just stop reporting failures.
                WatsonDisabled.s_reportWatson = false;
            }
        }
    }

    internal enum WatsonSeverity
    {
        /// <summary>
        /// Indicate that this watson is informative and not urgent
        /// </summary>
        Default,

        /// <summary>
        /// Indicate that this watson is critical and need to be addressed soon
        /// </summary>
        Critical,
    }
}


text:
#pragma once

#include <OgreString.h>

#include "fmod.hpp"

class NBID;

/* Declares NBID* varname and getter function */
#define ID_DECL(varname) \
	private:\
		NBID* varname;\
	public:\
		NBID* getID() const { return varname;}

/*
* Abstract class that encapsulates low-level FMOD API's audio source and channels.
* To be derived by @SoundEffect and @Music that use the exposed general audio functionality.
*/
class Audio
{
public:
	Audio(const Ogre::String& name);
	virtual ~Audio();

	/* Play FMOD sound source */
	virtual void play() = 0;

	/* Pause FMOD sound source */
	virtual void pause() = 0;

	/* Stop FMOD sound source */
	virtual void stop() = 0;

	bool isPlaying() const { return m_playing; }

	const Ogre::String& getResourceName() const { return m_resourceName; }

	void setAudioSource(FMOD::Sound* sound) { m_audioSource = sound; }
	FMOD::Sound* getAudioSource() const { return m_audioSource; }

	void setVolume(float v) { m_audioChannel->setVolume(v); }
	float getVolume() const { float volume; m_audioChannel->getVolume(&volume); return volume; }

	void setPitch(float v) { m_audioChannel->setPitch(v); }
	float getPitch() const { float pitch; m_audioChannel->getPitch(&pitch); return pitch; }

	ID_DECL(m_id);

protected:
	FMOD::Sound* m_audioSource;
	FMOD::Channel* m_audioChannel;

	const Ogre::String m_resourceName;

	bool m_playing;
};


text:
.class public final Landroid/printservice/PrintJob;
.super Ljava/lang/Object;
.source "PrintJob.java"

# static fields
.field private static final LOG_TAG:Ljava/lang/String; = "PrintJob"

# instance fields
.field private mCachedInfo:Landroid/print/PrintJobInfo;

.field private final mDocument:Landroid/printservice/PrintDocument;

.field private final mPrintServiceClient:Landroid/printservice/IPrintServiceClient;

# direct methods
.method constructor <init>(Landroid/print/PrintJobInfo;Landroid/printservice/IPrintServiceClient;)V
    .registers 6
    .param p1, "jobInfo"    # Landroid/print/PrintJobInfo;
    .param p2, "client"    # Landroid/printservice/IPrintServiceClient;

    .prologue
    .line 44
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 45
    iput-object p1, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    .line 46
    iput-object p2, p0, Landroid/printservice/PrintJob;->mPrintServiceClient:Landroid/printservice/IPrintServiceClient;

    .line 47
    new-instance v0, Landroid/printservice/PrintDocument;

    iget-object v1, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v1}, Landroid/print/PrintJobInfo;->getId()Landroid/print/PrintJobId;

    move-result-object v1

    .line 48
    invoke-virtual {p1}, Landroid/print/PrintJobInfo;->getDocumentInfo()Landroid/print/PrintDocumentInfo;

    move-result-object v2

    .line 47
    invoke-direct {v0, v1, p2, v2}, Landroid/printservice/PrintDocument;-><init>(Landroid/print/PrintJobId;Landroid/printservice/IPrintServiceClient;Landroid/print/PrintDocumentInfo;)V

    iput-object v0, p0, Landroid/printservice/PrintJob;->mDocument:Landroid/printservice/PrintDocument;

    .line 44
    return-void
.end method

.method private isInImmutableState()Z
    .registers 4

    .prologue
    const/4 v1, 0x1

    .line 371
    iget-object v2, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v2}, Landroid/print/PrintJobInfo;->getState()I

    move-result v0

    .line 372
    .local v0, "state":I
    const/4 v2, 0x5

    if-eq v0, v2, :cond_d

    .line 373
    const/4 v2, 0x7

    if-ne v0, v2, :cond_e

    .line 372
    :cond_d
    :goto_d
    return v1

    .line 374
    :cond_e
    const/4 v2, 0x6

    if-eq v0, v2, :cond_d

    const/4 v1, 0x0

    goto :goto_d
.end method

.method private setState(ILjava/lang/String;)Z
    .registers 7
    .param p1, "state"    # I
    .param p2, "error"    # Ljava/lang/String;

    .prologue
    .line 379
    :try_start_0
    iget-object v1, p0, Landroid/printservice/PrintJob;->mPrintServiceClient:Landroid/printservice/IPrintServiceClient;

    iget-object v2, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v2}, Landroid/print/PrintJobInfo;->getId()Landroid/print/PrintJobId;

    move-result-object v2

    invoke-interface {v1, v2, p1, p2}, Landroid/printservice/IPrintServiceClient;->setPrintJobState(Landroid/print/PrintJobId;ILjava/lang/String;)Z

    move-result v1

    if-eqz v1, :cond_3b

    .line 383
    iget-object v1, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v1, p1}, Landroid/print/PrintJobInfo;->setState(I)V

    .line 384
    iget-object v1, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v1, p2}, Landroid/print/PrintJobInfo;->setStateReason(Ljava/lang/String;)V
    :try_end_18
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_18} :catch_1a

    .line 385
    const/4 v1, 0x1

    return v1

    .line 387
    :catch_1a
    move-exception v0

    .line 388
    .local v0, "re":Landroid/os/RemoteException;
    const-string/jumbo v1, "PrintJob"

    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v3, "Error setting the state of job: "

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    iget-object v3, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v3}, Landroid/print/PrintJobInfo;->getId()Landroid/print/PrintJobId;

    move-result-object v3

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-static {v1, v2, v0}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    .line 390
    .end local v0    # "re":Landroid/os/RemoteException;
    :cond_3b
    const/4 v1, 0x0

    return v1
.end method

# virtual methods
.method public block(Ljava/lang/String;)Z
    .registers 6
    .param p1, "reason"    # Ljava/lang/String;

    .prologue
    const/4 v3, 0x4

    .line 214
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 215
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->getInfo()Landroid/print/PrintJobInfo;

    move-result-object v0

    .line 216
    .local v0, "info":Landroid/print/PrintJobInfo;
    invoke-virtual {v0}, Landroid/print/PrintJobInfo;->getState()I

    move-result v1

    .line 217
    .local v1, "state":I
    const/4 v2, 0x3

    if-eq v1, v2, :cond_1d

    .line 218
    if-ne v1, v3, :cond_1b

    .line 219
    invoke-virtual {v0}, Landroid/print/PrintJobInfo;->getStateReason()Ljava/lang/String;

    move-result-object v2

    invoke-static {v2, p1}, Landroid/text/TextUtils;->equals(Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Z

    move-result v2

    if-eqz v2, :cond_1d

    .line 222
    :cond_1b
    const/4 v2, 0x0

    return v2

    .line 220
    :cond_1d
    invoke-direct {p0, v3, p1}, Landroid/printservice/PrintJob;->setState(ILjava/lang/String;)Z

    move-result v2

    return v2
.end method

.method public cancel()Z
    .registers 3

    .prologue
    .line 275
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 276
    invoke-direct {p0}, Landroid/printservice/PrintJob;->isInImmutableState()Z

    move-result v0

    if-nez v0, :cond_10

    .line 277
    const/4 v0, 0x7

    const/4 v1, 0x0

    invoke-direct {p0, v0, v1}, Landroid/printservice/PrintJob;->setState(ILjava/lang/String;)Z

    move-result v0

    return v0

    .line 279
    :cond_10
    const/4 v0, 0x0

    return v0
.end method

.method public complete()Z
    .registers 3

    .prologue
    .line 234
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 235
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->isStarted()Z

    move-result v0

    if-eqz v0, :cond_10

    .line 236
    const/4 v0, 0x5

    const/4 v1, 0x0

    invoke-direct {p0, v0, v1}, Landroid/printservice/PrintJob;->setState(ILjava/lang/String;)Z

    move-result v0

    return v0

    .line 238
    :cond_10
    const/4 v0, 0x0

    return v0
.end method

.method public equals(Ljava/lang/Object;)Z
    .registers 6
    .param p1, "obj"    # Ljava/lang/Object;

    .prologue
    const/4 v3, 0x0

    .line 352
    if-ne p0, p1, :cond_5

    .line 353
    const/4 v1, 0x1

    return v1

    .line 355
    :cond_5
    if-nez p1, :cond_8

    .line 356
    return v3

    .line 358
    :cond_8
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->getClass()Ljava/lang/Class;

    move-result-object v1

    invoke-virtual {p1}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v2

    if-eq v1, v2, :cond_13

    .line 359
    return v3

    :cond_13
    move-object v0, p1

    .line 361
    check-cast v0, Landroid/printservice/PrintJob;

    .line 362
    .local v0, "other":Landroid/printservice/PrintJob;
    iget-object v1, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v1}, Landroid/print/PrintJobInfo;->getId()Landroid/print/PrintJobId;

    move-result-object v1

    iget-object v2, v0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v2}, Landroid/print/PrintJobInfo;->getId()Landroid/print/PrintJobId;

    move-result-object v2

    invoke-virtual {v1, v2}, Landroid/print/PrintJobId;->equals(Ljava/lang/Object;)Z

    move-result v1

    return v1
.end method

.method public fail(Ljava/lang/String;)Z
    .registers 3
    .param p1, "error"    # Ljava/lang/String;

    .prologue
    .line 255
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 256
    invoke-direct {p0}, Landroid/printservice/PrintJob;->isInImmutableState()Z

    move-result v0

    if-nez v0, :cond_f

    .line 257
    const/4 v0, 0x6

    invoke-direct {p0, v0, p1}, Landroid/printservice/PrintJob;->setState(ILjava/lang/String;)Z

    move-result v0

    return v0

    .line 259
    :cond_f
    const/4 v0, 0x0

    return v0
.end method

.method public getAdvancedIntOption(Ljava/lang/String;)I
    .registers 3
    .param p1, "key"    # Ljava/lang/String;

    .prologue
    .line 346
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 347
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->getInfo()Landroid/print/PrintJobInfo;

    move-result-object v0

    invoke-virtual {v0, p1}, Landroid/print/PrintJobInfo;->getAdvancedIntOption(Ljava/lang/String;)I

    move-result v0

    return v0
.end method

.method public getAdvancedStringOption(Ljava/lang/String;)Ljava/lang/String;
    .registers 3
    .param p1, "key"    # Ljava/lang/String;

    .prologue
    .line 323
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 324
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->getInfo()Landroid/print/PrintJobInfo;

    move-result-object v0

    invoke-virtual {v0, p1}, Landroid/print/PrintJobInfo;->getAdvancedStringOption(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public getDocument()Landroid/printservice/PrintDocument;
    .registers 2

    .prologue
    .line 94
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 95
    iget-object v0, p0, Landroid/printservice/PrintJob;->mDocument:Landroid/printservice/PrintDocument;

    return-object v0
.end method

.method public getId()Landroid/print/PrintJobId;
    .registers 2

    .prologue
    .line 57
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 58
    iget-object v0, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v0}, Landroid/print/PrintJobInfo;->getId()Landroid/print/PrintJobId;

    move-result-object v0

    return-object v0
.end method

.method public getInfo()Landroid/print/PrintJobInfo;
    .registers 6

    .prologue
    .line 72
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 73
    invoke-direct {p0}, Landroid/printservice/PrintJob;->isInImmutableState()Z

    move-result v2

    if-eqz v2, :cond_c

    .line 74
    iget-object v2, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    return-object v2

    .line 76
    :cond_c
    const/4 v0, 0x0

    .line 78
    .local v0, "info":Landroid/print/PrintJobInfo;
    :try_start_d
    iget-object v2, p0, Landroid/printservice/PrintJob;->mPrintServiceClient:Landroid/printservice/IPrintServiceClient;

    iget-object v3, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v3}, Landroid/print/PrintJobInfo;->getId()Landroid/print/PrintJobId;

    move-result-object v3

    invoke-interface {v2, v3}, Landroid/printservice/IPrintServiceClient;->getPrintJobInfo(Landroid/print/PrintJobId;)Landroid/print/PrintJobInfo;
    :try_end_18
    .catch Landroid/os/RemoteException; {:try_start_d .. :try_end_18} :catch_20

    move-result-object v0

    .line 82
    .end local v0    # "info":Landroid/print/PrintJobInfo;
    :goto_19
    if-eqz v0, :cond_1d

    .line 83
    iput-object v0, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    .line 85
    :cond_1d
    iget-object v2, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    return-object v2

    .line 79
    .restart local v0    # "info":Landroid/print/PrintJobInfo;
    :catch_20
    move-exception v1

    .line 80
    .local v1, "re":Landroid/os/RemoteException;
    const-string/jumbo v2, "PrintJob"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v4, "Couldn\'t get info for job: "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    iget-object v4, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v4}, Landroid/print/PrintJobInfo;->getId()Landroid/print/PrintJobId;

    move-result-object v4

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_19
.end method

.method public getTag()Ljava/lang/String;
    .registers 2

    .prologue
    .line 312
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 313
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->getInfo()Landroid/print/PrintJobInfo;

    move-result-object v0

    invoke-virtual {v0}, Landroid/print/PrintJobInfo;->getTag()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public hasAdvancedOption(Ljava/lang/String;)Z
    .registers 3
    .param p1, "key"    # Ljava/lang/String;

    .prologue
    .line 335
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 336
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->getInfo()Landroid/print/PrintJobInfo;

    move-result-object v0

    invoke-virtual {v0, p1}, Landroid/print/PrintJobInfo;->hasAdvancedOption(Ljava/lang/String;)Z

    move-result v0

    return v0
.end method

.method public hashCode()I
    .registers 2

    .prologue
    .line 367
    iget-object v0, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v0}, Landroid/print/PrintJobInfo;->getId()Landroid/print/PrintJobId;

    move-result-object v0

    invoke-virtual {v0}, Landroid/print/PrintJobId;->hashCode()I

    move-result v0

    return v0
.end method

.method public isBlocked()Z
    .registers 3

    .prologue
    .line 138
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 139
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->getInfo()Landroid/print/PrintJobInfo;

    move-result-object v0

    invoke-virtual {v0}, Landroid/print/PrintJobInfo;->getState()I

    move-result v0

    const/4 v1, 0x4

    if-ne v0, v1, :cond_10

    const/4 v0, 0x1

    :goto_f
    return v0

    :cond_10
    const/4 v0, 0x0

    goto :goto_f
.end method

.method public isCancelled()Z
    .registers 3

    .prologue
    .line 177
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 178
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->getInfo()Landroid/print/PrintJobInfo;

    move-result-object v0

    invoke-virtual {v0}, Landroid/print/PrintJobInfo;->getState()I

    move-result v0

    const/4 v1, 0x7

    if-ne v0, v1, :cond_10

    const/4 v0, 0x1

    :goto_f
    return v0

    :cond_10
    const/4 v0, 0x0

    goto :goto_f
.end method

.method public isCompleted()Z
    .registers 3

    .prologue
    .line 151
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 152
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->getInfo()Landroid/print/PrintJobInfo;

    move-result-object v0

    invoke-virtual {v0}, Landroid/print/PrintJobInfo;->getState()I

    move-result v0

    const/4 v1, 0x5

    if-ne v0, v1, :cond_10

    const/4 v0, 0x1

    :goto_f
    return v0

    :cond_10
    const/4 v0, 0x0

    goto :goto_f
.end method

.method public isFailed()Z
    .registers 3

    .prologue
    .line 164
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 165
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->getInfo()Landroid/print/PrintJobInfo;

    move-result-object v0

    invoke-virtual {v0}, Landroid/print/PrintJobInfo;->getState()I

    move-result v0

    const/4 v1, 0x6

    if-ne v0, v1, :cond_10

    const/4 v0, 0x1

    :goto_f
    return v0

    :cond_10
    const/4 v0, 0x0

    goto :goto_f
.end method

.method public isQueued()Z
    .registers 3

    .prologue
    .line 108
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 109
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->getInfo()Landroid/print/PrintJobInfo;

    move-result-object v0

    invoke-virtual {v0}, Landroid/print/PrintJobInfo;->getState()I

    move-result v0

    const/4 v1, 0x2

    if-ne v0, v1, :cond_10

    const/4 v0, 0x1

    :goto_f
    return v0

    :cond_10
    const/4 v0, 0x0

    goto :goto_f
.end method

.method public isStarted()Z
    .registers 3

    .prologue
    .line 123
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 124
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->getInfo()Landroid/print/PrintJobInfo;

    move-result-object v0

    invoke-virtual {v0}, Landroid/print/PrintJobInfo;->getState()I

    move-result v0

    const/4 v1, 0x3

    if-ne v0, v1, :cond_10

    const/4 v0, 0x1

    :goto_f
    return v0

    :cond_10
    const/4 v0, 0x0

    goto :goto_f
.end method

.method public setTag(Ljava/lang/String;)Z
    .registers 7
    .param p1, "tag"    # Ljava/lang/String;

    .prologue
    const/4 v4, 0x0

    .line 292
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 293
    invoke-direct {p0}, Landroid/printservice/PrintJob;->isInImmutableState()Z

    move-result v1

    if-eqz v1, :cond_b

    .line 294
    return v4

    .line 297
    :cond_b
    :try_start_b
    iget-object v1, p0, Landroid/printservice/PrintJob;->mPrintServiceClient:Landroid/printservice/IPrintServiceClient;

    iget-object v2, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v2}, Landroid/print/PrintJobInfo;->getId()Landroid/print/PrintJobId;

    move-result-object v2

    invoke-interface {v1, v2, p1}, Landroid/printservice/IPrintServiceClient;->setPrintJobTag(Landroid/print/PrintJobId;Ljava/lang/String;)Z
    :try_end_16
    .catch Landroid/os/RemoteException; {:try_start_b .. :try_end_16} :catch_18

    move-result v1

    return v1

    .line 298
    :catch_18
    move-exception v0

    .line 299
    .local v0, "re":Landroid/os/RemoteException;
    const-string/jumbo v1, "PrintJob"

    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v3, "Error setting tag for job: "

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    iget-object v3, p0, Landroid/printservice/PrintJob;->mCachedInfo:Landroid/print/PrintJobInfo;

    invoke-virtual {v3}, Landroid/print/PrintJobInfo;->getId()Landroid/print/PrintJobId;

    move-result-object v3

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    invoke-static {v1, v2, v0}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    .line 301
    return v4
.end method

.method public start()Z
    .registers 4

    .prologue
    .line 192
    invoke-static {}, Landroid/printservice/PrintService;->throwIfNotCalledOnMainThread()V

    .line 193
    invoke-virtual {p0}, Landroid/printservice/PrintJob;->getInfo()Landroid/print/PrintJobInfo;

    move-result-object v1

    invoke-virtual {v1}, Landroid/print/PrintJobInfo;->getState()I

    move-result v0

    .line 194
    .local v0, "state":I
    const/4 v1, 0x2

    if-eq v0, v1, :cond_11

    .line 195
    const/4 v1, 0x4

    if-ne v0, v1, :cond_18

    .line 196
    :cond_11
    const/4 v1, 0x3

    const/4 v2, 0x0

    invoke-direct {p0, v1, v2}, Landroid/printservice/PrintJob;->setState(ILjava/lang/String;)Z

    move-result v1

    return v1

    .line 198
    :cond_18
    const/4 v1, 0x0

    return v1
.end method


text:
#ifndef FLENS_STORAGE_PACKEDSTORAGE_CONSTPACKEDSTORAGEVIEW_H
#define FLENS_STORAGE_PACKEDSTORAGE_CONSTPACKEDSTORAGEVIEW_H 1

#include <cxxblas/typedefs.h>
#include <flens/typedefs.h>
#include <flens/storage/indexoptions.h>

namespace flens {

template <typename T, typename I, typename A>
    class Array;

template <typename T, typename I, typename A>
    class ArrayView;

template <typename T, typename I, typename A>
    class ConstArrayView;

template <typename T, StorageOrder Order, typename I, typename A>
    class PackedStorage;

template <typename T, StorageOrder Order, typename I, typename A>
    class PackedStorageView;

template <typename T,
          StorageOrder Order = ColMajor,
          typename I = IndexOptions<>,
          typename A = std::allocator<T> >
class ConstPackedStorageView
{
    public:
        typedef T                       ElementType;
        typedef typename I::IndexType   IndexType;
        typedef A                       Allocator;

        static const StorageOrder       order = Order;
        static const IndexType          defaultIndexBase = I::defaultIndexBase;

        typedef ConstPackedStorageView               ConstView;
        typedef PackedStorageView<T, Order, I, A>    View;
        typedef PackedStorage<T, Order, I, A>        NoView;

        typedef flens::ConstArrayView<T, I, A>       ConstArrayView;
        typedef flens::ArrayView<T, I, A>            ArrayView;
        typedef flens::Array<T, I, A>                Array;

        ConstPackedStorageView(IndexType dim,
                               const ElementType *data,
                               IndexType indexBase = I::defaultIndexBase,
                               const Allocator &allocator = Allocator());

        template <typename ARRAY>
            ConstPackedStorageView(IndexType dim,
                                   ARRAY &array,
                                   IndexType indexBase = I::defaultIndexBase,
                                   const Allocator &allocator = Allocator());

        ConstPackedStorageView(const ConstPackedStorageView &rhs);

        template <typename RHS>
            ConstPackedStorageView(const RHS &rhs);

        ~ConstPackedStorageView();

        //-- operators ---------------------------------------------------------

        const ElementType &
        operator()(StorageUpLo upLo, IndexType row, IndexType col) const;

        //-- methods -----------------------------------------------------------

        IndexType
        indexBase() const;

        IndexType
        numNonZeros() const;

        IndexType
        dim() const;

        const ElementType *
        data() const;

        const Allocator &
        allocator() const;

        void
        changeIndexBase(IndexType indexBase);

    private:
        const ElementType    *data_;
        Allocator            allocator_;
        IndexType            dim_;
        IndexType            indexBase_;
};

} // namespace flens

#endif // FLENS_STORAGE_PACKEDSTORAGE_CONSTPACKEDSTORAGEVIEW_H


text:
var GooglePlayParser = require('./google_play_parser')
var iTunesParser = require('./itunes_parser')

function* getAndroidApp(appPackage) {
    var parser = new GooglePlayParser()
    return yield parser.parse(appPackage)
}

function* getiOSApp(appId) {
    var parser = new iTunesParser()
    return yield parser.parse(appId)
}

module.exports.getAndroidApp = getAndroidApp
module.exports.getiOSApp = getiOSApp


text:
package braunse.webpackexecute

import sbt._
import Keys._
import sys.{process => P}

object WebpackExecutePlugin extends AutoPlugin {
  object autoImport {
    object Webpack {
      val configurationFile = SettingKey[File]("webpack-configuration-file", "Path to the webpack configuration file")
      val webpackExecutable = SettingKey[File]("webpack-executable", "Path to the webpack executable")
      val npmExecutable = SettingKey[String]("webpack-npm-executable", "NPM executable to use")
      val environment = SettingKey[String]("webpack-env", "Environment to pass to webpack")
      val environmentVariable = SettingKey[String]("webpack-env-variable", "Environment variable to pass environment in")
      val npmPackageJSON = SettingKey[File]("webpack-package-json", "Path to package.json file")
      val resourceDir = SettingKey[File]("webpack-resource-dir", "Path to generated resource directory")
      val outputPath = SettingKey[String]("webpack-output-path", "Path to webpack output (within generated resource folder)")
      val inputDirs = SettingKey[Seq[File]]("webpack-input-dirs", "Path where webpack input files are searched")

      val ensureNPMInstalled = TaskKey[NPMUpToDate]("webpack-ensure-npm-uptodate", "Ensure that npm install has been called")
      val generate = TaskKey[Seq[File]]("webpack-generate", "Generate webpack output files")
    }

  }

  import autoImport._

  case class NPMUpToDate(skipped: Boolean)

  private[this] def defaultBuildWebpackSettings: Seq[Def.Setting[_]] = Seq(
    Webpack.npmExecutable := "npm"
  )

  private[this] val defaultProjectWebpackSettings: Seq[Def.Setting[_]] = Seq(
    Webpack.environment := "development",
    Webpack.environmentVariable := "WEBPACK_ENV",
    Webpack.configurationFile := baseDirectory.value / "webpack.config.js",
    Webpack.webpackExecutable := baseDirectory.value / "node_modules/webpack/bin/webpack.js",
    Webpack.npmPackageJSON := baseDirectory.value / "package.json",
    Webpack.resourceDir := resourceManaged.value / "webpack",
    Webpack.inputDirs := Nil,
    Webpack.inputDirs ++= Seq(
      baseDirectory.value / "src/main/frontend",
      baseDirectory.value / "node_modules",
      baseDirectory.value / "bower_components"
    ),

    Webpack.ensureNPMInstalled := { npmInstallTask(Webpack.ensureNPMInstalled).value },
    Webpack.generate := { resourceGeneratorTask(Webpack.generate).dependsOn(Webpack.ensureNPMInstalled).value },
    resourceGenerators += Webpack.generate.taskValue,

    managedResourceDirectories += Webpack.resourceDir.value
  )

  override def requires: Plugins = plugins.JvmPlugin

  override def buildSettings: Seq[_root_.sbt.Def.Setting[_]] = defaultBuildWebpackSettings

  override def projectSettings: Seq[_root_.sbt.Def.Setting[_]] =
    inConfig(Compile)(defaultProjectWebpackSettings)

  private[this] def npmInstallTask(key: TaskKey[NPMUpToDate]) = Def.task {
    val logs = (streams in key).value.log
    val packageJson = (Webpack.npmPackageJSON in key).value
    val npmExe = (Webpack.npmExecutable in key).value
    val baseDir = (baseDirectory in key).value
    if(packageJson.exists()) {
      val command = List(npmExe, "install")
      logs.info("npm install")
      val retval = mkProcess(command, Some(baseDir)).!
      if(retval != 0) {
        sys.error(s"npm install returned $retval")
      }
      NPMUpToDate(skipped = false)
    } else {
      logs.debug("Skipping npm install")
      NPMUpToDate(skipped = true)
    }
  }

  private[this] def resourceGeneratorTask(key: TaskKey[Seq[File]]) = Def.task {
    val packageJson = (Webpack.npmPackageJSON in key).value
    val webpackConfig = (Webpack.configurationFile in key).value
    val logs = (streams in key).value.log
    val potentialInputs = (Webpack.inputDirs in key).value.filter(_.isDirectory()).flatMap(dir => (dir ** ExistsFileFilter).get).toSet +
      (Webpack.configurationFile in key).value
    val outputDirectory = (Webpack.resourceDir in key).value
    val outputPath = (Webpack.outputPath in key).value
    val envVar = (Webpack.environmentVariable in key).value
    val envVal = (Webpack.environment in key).value
    val exe = (Webpack.webpackExecutable in key).value
    val cwd = (baseDirectory in key).value
    val webpackCacheDir = (streams in key).value.cacheDirectory / "webpack"

    if(!packageJson.exists() || !webpackConfig.exists()) {
      logs.info("Skipping webpack call")
      Seq()
    }
    else {
      val cachedCompilation = FileFunction.cached(webpackCacheDir, FilesInfo.lastModified, FilesInfo.exists) { (in: Set[File]) =>
        IO.delete(outputDirectory)
        outputDirectory.mkdirs()

        val command = List(
          "node", exe.absolutePath,
          "--output-path", (outputDirectory / outputPath).absolutePath,
          "--config", webpackConfig.absolutePath
        )

        logs.info("Executing webpack")
        logs.debug(s"Calling webpack: `${command.mkString("", " ", "")}'")

        val exitVal = mkProcess(command, Some(cwd), envVar -> envVal).!
        if (exitVal != 0) {
          sys.error(s"webpack returned exit code ${exitVal}")
        }

        (outputDirectory ** ExistsFileFilter).get.filter(_.isFile()).toSet
      }

      val generatedFiles = cachedCompilation(potentialInputs).toSeq
      logs.debug(s"Generated files: ${generatedFiles.mkString("\n * ", "\n * ", "")}")
      generatedFiles
    }
  }

  private def mkProcess(command: Seq[String], cwd: Option[File], extraEnv: (String, String)*): P.ProcessBuilder = {
    val isWindows = sys.props("os.name").contains("Windows")
    val wrappedCommand =
      if (isWindows) Seq("cmd", "/c") ++ command
      else command
    P.Process(wrappedCommand, cwd, extraEnv: _*)
  }
}


text:
package controllers

import play.api.mvc._
import actors.{WebSocketActor, ClientConnection, Actors}
import play.api.Play.current
import actors.ClientConnection.ClientEvent

object Application extends Controller {

	/**
	 * The index page.
	 */
	def index = Action { implicit req =>
		Ok(views.html.index())
	}

	/**
	 * The WebSocket
	 */
	def stream(email: String) = WebSocketActor.actorOf[ClientEvent] { _ => upstream =>
		ClientConnection.props(email, upstream, Actors.regionManagerClient)
	}
}


text:
Merb::Generators::ModelGenerator.template :model_relaxdb, :orm => :relaxdb do |template|
  template.source = File.dirname(__FILE__) / "templates/model/app/models/%file_name%.rb"
  template.destination = "app/models" / base_path / "#{file_name}.rb"
end


text:
using namespace nanosoft;

DoublePool pool("pool", 16 * 1024 * 1024, 12);

int main()
{
	printf("busy: %d\ndepth: %d\n", pool.getBusySize(), pool.getStackDepth());
	pool.enter();
		pool.alloc(1024);
		pool.enter();
			pool.alloc(100);
			pool.tempAlloc(12);
		pool.leave();
		printf("  busy: %d\n  depth: %d\n", pool.getBusySize(), pool.getStackDepth());
	pool.leave();
	printf(" busy: %d\n depth: %d\n", pool.getBusySize(), pool.getStackDepth());
	printf("peak memory: %d\npeak depth: %d\n", pool.getPeakMemory(), pool.getPeakDepth());
	pool.leave();
	return 0;
}