text:
package org.apache.hadoop.hive.ql.exec;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.exec.mapjoin.MapJoinMemoryExhaustionHandler;
import org.apache.hadoop.hive.ql.exec.persistence.HashMapWrapper;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinKeyObject;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinObjectSerDeContext;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinPersistableTableContainer;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinEagerRowContainer;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinRowContainer;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinTableContainer;
import org.apache.hadoop.hive.ql.exec.persistence.MapJoinTableContainerSerDe;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.plan.HashTableSinkDesc;
import org.apache.hadoop.hive.ql.plan.TableDesc;
import org.apache.hadoop.hive.ql.plan.api.OperatorType;
import org.apache.hadoop.hive.ql.session.SessionState.LogHelper;
import org.apache.hadoop.hive.serde2.SerDe;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.SerDeUtils;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils.ObjectInspectorCopyOption;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.util.ReflectionUtils;

public class HashTableSinkOperator extends TerminalOperator<HashTableSinkDesc> implements
    Serializable {
  private static final long serialVersionUID = 1L;
  protected static final Log LOG = LogFactory.getLog(HashTableSinkOperator.class.getName());

  /**
   * The expressions for join inputs's join keys.
   */
  private transient List<ExprNodeEvaluator>[] joinKeys;
  /**
   * The ObjectInspectors for the join inputs's join keys.
   */
  private transient List<ObjectInspector>[] joinKeysObjectInspectors;

  private transient int posBigTableAlias = -1; // one of the tables that is not in memory

  /**
   * The filters for join
   */
  private transient List<ExprNodeEvaluator>[] joinFilters;

  private transient int[][] filterMaps;

  /**
   * The expressions for join outputs.
   */
  private transient List<ExprNodeEvaluator>[] joinValues;
  /**
   * The ObjectInspectors for the join inputs.
   */
  private transient List<ObjectInspector>[] joinValuesObjectInspectors;
  /**
   * The ObjectInspectors for join filters.
   */
  private transient List<ObjectInspector>[] joinFilterObjectInspectors;

  private transient Byte[] order; // order in which the results should
  protected Configuration hconf;

  protected transient MapJoinPersistableTableContainer[] mapJoinTables;
  protected transient MapJoinTableContainerSerDe[] mapJoinTableSerdes;

  private final Object[] emptyObjectArray = new Object[0];
  private final MapJoinEagerRowContainer emptyRowContainer = new MapJoinEagerRowContainer();

  private long rowNumber = 0;
  protected transient LogHelper console;
  private long hashTableScale;
  private MapJoinMemoryExhaustionHandler memoryExhaustionHandler;

  public HashTableSinkOperator() {
  }

  public HashTableSinkOperator(MapJoinOperator mjop) {
    this.conf = new HashTableSinkDesc(mjop.getConf());
  }

  @Override
  @SuppressWarnings("unchecked")
  protected void initializeOp(Configuration hconf) throws HiveException {
    boolean isSilent = HiveConf.getBoolVar(hconf, HiveConf.ConfVars.HIVESESSIONSILENT);
    console = new LogHelper(LOG, isSilent);
    memoryExhaustionHandler = new MapJoinMemoryExhaustionHandler(console, conf.getHashtableMemoryUsage());
    emptyRowContainer.addRow(emptyObjectArray);

    // for small tables only; so get the big table position first
    posBigTableAlias = conf.getPosBigTable();

    order = conf.getTagOrder();

    // initialize some variables, which used to be initialized in CommonJoinOperator
    this.hconf = hconf;

    filterMaps = conf.getFilterMap();

    int tagLen = conf.getTagLength();

    // process join keys
    joinKeys = new List[tagLen];
    JoinUtil.populateJoinKeyValue(joinKeys, conf.getKeys(), posBigTableAlias);
    joinKeysObjectInspectors = JoinUtil.getObjectInspectorsFromEvaluators(joinKeys,
        inputObjInspectors, posBigTableAlias, tagLen);

    // process join values
    joinValues = new List[tagLen];
    JoinUtil.populateJoinKeyValue(joinValues, conf.getExprs(), posBigTableAlias);
    joinValuesObjectInspectors = JoinUtil.getObjectInspectorsFromEvaluators(joinValues,
        inputObjInspectors, posBigTableAlias, tagLen);

    // process join filters
    joinFilters = new List[tagLen];
    JoinUtil.populateJoinKeyValue(joinFilters, conf.getFilters(), posBigTableAlias);
    joinFilterObjectInspectors = JoinUtil.getObjectInspectorsFromEvaluators(joinFilters,
        inputObjInspectors, posBigTableAlias, tagLen);

    if (!conf.isNoOuterJoin()) {
      for (Byte alias : order) {
        if (alias == posBigTableAlias || joinValues[alias] == null) {
          continue;
        }
        List<ObjectInspector> rcOIs = joinValuesObjectInspectors[alias];
        if (filterMaps != null && filterMaps[alias] != null) {
          // for each alias, add object inspector for filter tag as the last element
          rcOIs = new ArrayList<ObjectInspector>(rcOIs);
          rcOIs.add(PrimitiveObjectInspectorFactory.writableShortObjectInspector);
        }
      }
    }
    mapJoinTables = new MapJoinPersistableTableContainer[tagLen];
    mapJoinTableSerdes = new MapJoinTableContainerSerDe[tagLen];
    hashTableScale = HiveConf.getLongVar(hconf, HiveConf.ConfVars.HIVEHASHTABLESCALE);
    if (hashTableScale <= 0) {
      hashTableScale = 1;
    }
    try {
      TableDesc keyTableDesc = conf.getKeyTblDesc();
      SerDe keySerde = (SerDe) ReflectionUtils.newInstance(keyTableDesc.getDeserializerClass(),
          null);
      SerDeUtils.initializeSerDe(keySerde, null, keyTableDesc.getProperties(), null);
      MapJoinObjectSerDeContext keyContext = new MapJoinObjectSerDeContext(keySerde, false);
      for (Byte pos : order) {
        if (pos == posBigTableAlias) {
          continue;
        }
        mapJoinTables[pos] = new HashMapWrapper(hconf, -1);
        TableDesc valueTableDesc = conf.getValueTblFilteredDescs().get(pos);
        SerDe valueSerDe = (SerDe) ReflectionUtils.newInstance(valueTableDesc.getDeserializerClass(), null);
        SerDeUtils.initializeSerDe(valueSerDe, null, valueTableDesc.getProperties(), null);
        mapJoinTableSerdes[pos] = new MapJoinTableContainerSerDe(keyContext, new MapJoinObjectSerDeContext(
            valueSerDe, hasFilter(pos)));
      }
    } catch (SerDeException e) {
      throw new HiveException(e);
    }
  }

  public MapJoinTableContainer[] getMapJoinTables() {
    return mapJoinTables;
  }

  private static List<ObjectInspector>[] getStandardObjectInspectors(
      List<ObjectInspector>[] aliasToObjectInspectors, int maxTag) {
    @SuppressWarnings("unchecked")
    List<ObjectInspector>[] result = new List[maxTag];
    for (byte alias = 0; alias < aliasToObjectInspectors.length; alias++) {
      List<ObjectInspector> oiList = aliasToObjectInspectors[alias];
      if (oiList == null) {
        continue;
      }
      ArrayList<ObjectInspector> fieldOIList = new ArrayList<ObjectInspector>(oiList.size());
      for (int i = 0; i < oiList.size(); i++) {
        fieldOIList.add(ObjectInspectorUtils.getStandardObjectInspector(oiList.get(i),
            ObjectInspectorCopyOption.WRITABLE));
      }
      result[alias] = fieldOIList;
    }
    return result;

  }

  /*
   * This operator only process small tables Read the key/value pairs Load them into hashtable
   */
  @Override
  public void processOp(Object row, int tag) throws HiveException {
    byte alias = (byte)tag;
    // compute keys and values as StandardObjects. Use non-optimized key (MR).
    Object[] currentKey = new Object[joinKeys[alias].size()];
    for (int keyIndex = 0; keyIndex < joinKeys[alias].size(); ++keyIndex) {
      currentKey[keyIndex] = joinKeys[alias].get(keyIndex).evaluate(row);
    }
    MapJoinKeyObject key = new MapJoinKeyObject();
    key.readFromRow(currentKey, joinKeysObjectInspectors[alias]);

    Object[] value = emptyObjectArray;
    if((hasFilter(alias) && filterMaps[alias].length > 0) || joinValues[alias].size() > 0) {
      value = JoinUtil.computeMapJoinValues(row, joinValues[alias],
        joinValuesObjectInspectors[alias], joinFilters[alias], joinFilterObjectInspectors[alias],
        filterMaps == null ? null : filterMaps[alias]);
    }
    MapJoinPersistableTableContainer tableContainer = mapJoinTables[alias];
    MapJoinRowContainer rowContainer = tableContainer.get(key);
    if (rowContainer == null) {
      if(value.length != 0) {
        rowContainer = new MapJoinEagerRowContainer();
        rowContainer.addRow(value);
      } else {
        rowContainer = emptyRowContainer;
      }
      rowNumber++;
      if (rowNumber > hashTableScale && rowNumber % hashTableScale == 0) {
        memoryExhaustionHandler.checkMemoryStatus(tableContainer.size(), rowNumber);
      }
      tableContainer.put(key, rowContainer);
    } else if (rowContainer == emptyRowContainer) {
      rowContainer = rowContainer.copy();
      rowContainer.addRow(value);
      tableContainer.put(key, rowContainer);
    } else {
      rowContainer.addRow(value);
    }
  }
  private boolean hasFilter(int alias) {
    return filterMaps != null && filterMaps[alias] != null;
  }

  @Override
  public void closeOp(boolean abort) throws HiveException {
    try {
      if (mapJoinTables == null) {
	if (isLogDebugEnabled) {
	  LOG.debug("mapJoinTables is null");
	}
      } else {
        flushToFile();
      }
      super.closeOp(abort);
    } catch (HiveException e) {
      throw e;
    } catch (Exception e) {
      throw new HiveException(e);
    }
  }

  protected void flushToFile() throws IOException, HiveException {
    // get tmp file URI
    Path tmpURI = getExecContext().getLocalWork().getTmpPath();
    if (isLogInfoEnabled) {
      LOG.info("Temp URI for side table: " + tmpURI);
    }
    for (byte tag = 0; tag < mapJoinTables.length; tag++) {
      // get the key and value
      MapJoinPersistableTableContainer tableContainer = mapJoinTables[tag];
      if (tableContainer == null) {
        continue;
      }
      // get current input file name
      String bigBucketFileName = getExecContext().getCurrentBigBucketFile();
      String fileName = getExecContext().getLocalWork().getBucketFileName(bigBucketFileName);
      // get the tmp URI path; it will be a hdfs path if not local mode
      String dumpFilePrefix = conf.getDumpFilePrefix();
      Path path = Utilities.generatePath(tmpURI, dumpFilePrefix, tag, fileName);
      console.printInfo(Utilities.now() + "\tDump the side-table for tag: " + tag +
          " with group count: " + tableContainer.size() + " into file: " + path);
      // get the hashtable file and path
      FileSystem fs = path.getFileSystem(hconf);
      ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fs.create(path), 4096));
      try {
        mapJoinTableSerdes[tag].persist(out, tableContainer);
      } finally {
        out.close();
      }
      tableContainer.clear();
      FileStatus status = fs.getFileStatus(path);
      console.printInfo(Utilities.now() + "\tUploaded 1 File to: " + path +
          " (" + status.getLen() + " bytes)");
    }
  }

  /**
   * Implements the getName function for the Node Interface.
   *
   * @return the name of the operator
   */
  @Override
  public String getName() {
    return getOperatorName();
  }

  static public String getOperatorName() {
    return "HASHTABLESINK";
  }

  @Override
  public OperatorType getType() {
    return OperatorType.HASHTABLESINK;
  }
}


text:
var CreateFooterView = require('../../../../../../javascripts/cartodb/common/dialogs/create/create_footer');
var CreateModel = require('../../../../../../javascripts/cartodb/common/dialogs/create/create_map_model');
var MapTemplates = require('../../../../../../javascripts/cartodb/common/map_templates');

describe('common/dialogs/create/create_footer_view', function() {
  beforeEach(function() {
    this.user = new cdb.admin.User({
      base_url: 'http://paco.cartodb.com',
      username: 'paco'
    });

    this.model = new CreateModel({
      type: "dataset",
      option: "listing"
    }, {
      user: this.user
    });

    this.view = new CreateFooterView({
      user: this.user,
      createModel: this.model,
      currentUserUrl: this.currentUserUrl
    });

    spyOn(this.model, 'bind').and.callThrough();

    this.view.render();
  });

  it('should bind createModel attribute changes', function() {
    this.view._initBinds();
    var args = this.model.bind.calls.argsFor(0);
    expect(args[0]).toEqual('change');
    var args0 = this.model.bind.calls.argsFor(1);
    expect(args0[0]).toEqual('change:upload');
    var args1 = this.model.bind.calls.argsFor(2);
    expect(args1[0]).toEqual('change:option');
    var args2 = this.model.bind.calls.argsFor(3);
    expect(args2[0]).toEqual('change:listing');
  });

  describe('guessing toggler', function() {
    it('should not change guessing model when upload changes', function() {
      expect(this.view.guessingModel.get('guessing')).toBeTruthy();
      expect(this.model.upload.get('type_guessing')).toBeTruthy();
      expect(this.model.upload.get('content_guessing')).toBeTruthy();
      this.model.upload.setGuessing(false);
      expect(this.view.guessingModel.get('guessing')).toBeTruthy();
      expect(this.model.upload.get('type_guessing')).toBeFalsy();
      expect(this.model.upload.get('content_guessing')).toBeFalsy();
    });

    it('should change guessing values when upload is ready to start', function() {
      this.view.guessingModel.set('guessing', true);
      this.model.upload.set({
        type: 'url',
        value: 'https://cartodb.com/csv.example'
      });
      this.model.upload.setGuessing(false);
      this.view._connectDataset();
      expect(this.model.upload.get('type_guessing')).toBeTruthy();
      expect(this.model.upload.get('content_guessing')).toBeTruthy();
    });
  });

  describe('privacy toggler', function() {

    beforeEach(function() {
      this.model.set({
        listing: 'import',
        type: 'datasets'
      });
    });

    it('should not change privacy model when upload changes', function() {
      expect(this.view.privacyModel.get('privacy')).toBe('PUBLIC');
      this.model.upload.set('privacy', 'PRIVATE');
      expect(this.view.privacyModel.get('privacy')).toBe('PUBLIC');
      expect(this.model.upload.get('privacy')).toBe('PRIVATE');
    });

    it('should change privacy value when upload is ready to start', function() {
      this.view.privacyModel.set('privacy', 'PRIVATE');
      this.model.upload.set({
        type: 'url',
        value: 'https://cartodb.com/csv.example',
        privacy: 'PUBLIC'
      });
      this.view._connectDataset();
      expect(this.model.upload.get('privacy')).toBe('PRIVATE');
    });

    it('should not change privacy value if create model is not in import state', function() {
      this.model.set({
        listing: '',
        type: 'maps'
      });
      this.view.privacyModel.set('privacy', 'PRIVATE');
      this.model.upload.set({
        type: 'url',
        value: 'https://cartodb.com/csv.example',
        privacy: 'PUBLIC'
      });
      this.view._connectDataset();
      expect(this.model.upload.get('privacy')).not.toBe('PRIVATE');
    });

  });

  it('should show start tutorial link when there is no datasets selected', function() {
    this.model.selectedDatasets.reset();
    this.view.render();
    expect(this.view.$el.text()).toContain('start with a video tutorial');
    expect(this.view.$('.js-videoTutorial').length).toBe(1);
    this.model.selectedDatasets.reset([{ hola: "hola" }]);
    this.view.render();
    expect(this.view.$el.text()).not.toContain('start with a video tutorial');
    expect(this.view.$('.js-videoTutorial').length).toBe(0);
  });

  it('should have no leaks', function() {
    expect(this.view).toHaveNoLeaks();
  });

  afterEach(function() {
    this.view.clean();
  });
});

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by huanghx on 2017/6/21.
 */
class Config {
    constructor() {
        this.isDebug = process && process.isDebug
        this.apiHost = this.isDebug ? '//localhost:16240' : ''
        this.apiHostName = this.apiHost.replace('//', '')
        this.showPageTab = false // 是否增加tab页
    }
}

export default new Config()


text:
import {
	Component,
	OnInit,
	Input,
	OnChanges,
	Output,
	EventEmitter,
	OnDestroy
} from '@angular/core';
import {
	FormGroup,
	FormBuilder,
	Validators
} from '@angular/forms';
import {
	InjectUser
} from 'angular2-meteor-accounts-ui';
import {
	Mongo
} from 'meteor/mongo';
import {
	Meteor
} from 'meteor/meteor';
import {
	Observable
} from 'rxjs/Observable';
import {
	Subscription
} from 'rxjs/Subscription';
import {
	MeteorObservable
} from 'meteor-rxjs';
import {
	Productcategory,
	Subcategory
} from '../../../../../../../../both/collections/csvdata.collection';
import * as _ from 'lodash';
import template from './category.html';

@Component({
	selector: 'category',
	template
})
@InjectUser('user')
export class CategoryComponent implements OnInit, OnDestroy, OnChanges {
	user: Meteor.User;
	@Input() id: string;
	@Input() assigned_category_id: string;
	@Input() is_processed: number;
	@Input() Cr_Dr: string;
	@Input() parent_category_list: any;
	@Input() child_category_list: any;
	@Output() change: EventEmitter<any> = new EventEmitter<any>();
	subcategorySub: Subscription;
	addForm: FormGroup; // form group instance
	show_category: any;
	parent_category: any;
	selectedparent_id: any;
	select_parent: boolean;
	child_list: any;
	Choose_Cateogry: string = "Choose Category";
	eventdata: Object = {};
	constructor(private _formBuilder: FormBuilder) {}
	ngOnInit() {
		// Angular form to add new category
		this.addForm = this._formBuilder.group({
			category: ['', Validators.required],
		});
		if (this.assigned_category_id != "not assigned") {
			this.show_category = _.filter(this.child_category_list, {
				"_id": this.assigned_category_id
			});
			if (this.show_category != '') {
				this.parent_category = _.filter(this.parent_category_list, {
					"_id": this.show_category[0].parent_id
				});
			}
		}
		this.select_parent = true;
		this.subcategorySub = MeteorObservable.subscribe('Subcategory').subscribe();
	}
	// angular lifecycle hook to get new category list if there is any change
	ngOnChanges(changes: {
		[propName: string]: any
	}) {
		if (changes["assigned_category_id"] && changes["child_category_list"]) {
			if (changes["assigned_category_id"].currentValue != "not assigned") {
				this.show_category = _.filter(this.child_category_list, {
					"_id": this.assigned_category_id
				});
				if (this.show_category != '') {
					this.parent_category = _.filter(this.parent_category_list, {
						"_id": this.show_category[0].parent_id
					});
				}
			}
		}

		if(this.show_category!=undefined && this.show_category.length){
		 	this.change.emit({category:this.parent_category[0].category,subCategory:this.show_category[0].category});
		 }

	}
	// code to select parent category and extract all its children in child_list
	ParentSelected(selected_parent) {
		this.child_list = _.filter(this.child_category_list, {
			"parent_id": selected_parent._id
		});
		this.Choose_Cateogry = selected_parent.category;
		this.selectedparent_id = selected_parent._id;
		this.select_parent = false;
	}
	trackByFn(index, item) {
        return item._id || index;
    }
	// code to change already assigned category to any transaction note
	changeCategory(id, category_id) {
		Meteor.call('changeCategory', id, this.selectedparent_id, category_id, (error, response) => {
			if (error) {
				console.log(error.reason);
			} else {
				console.log(response);
			}
		});
		this.select_parent = true;
		this.selectedparent_id = undefined;
		this.Choose_Cateogry = "Choose Cateogry";
	}
	// code to add new category into system from csvtimeline category dropdown list
	addNewCategory() {
		if (this.addForm.valid) {
			Productcategory.insert(this.addForm.value);
			// to empty the input box
			this.addForm.reset();
		}
	}
	// code to add new subcategory into our sytem from csvtimeline subcategory input box
	addNewsubCategory() {
		console.log(this.selectedparent_id);
		console.log(this.addForm.controls['category'].value);
		if (this.addForm.valid && this.selectedparent_id) {
			Subcategory.insert({
				"parent_id": this.selectedparent_id,
				"category": this.addForm.controls['category'].value
			});
			this.addForm.reset();
			this.Choose_Cateogry = "Choose Cateogry";
			this.selectedparent_id = undefined;
			this.select_parent = true;
		}
	}
	// In ngOnDestroy we are unsubscribing our subcategory list to save system from memory leak
	ngOnDestroy() {
		this.subcategorySub.unsubscribe();
	}
}


text:
<?php

class Braintree_Payments_Model_System_Config_Backend_Credentials extends Mage_Core_Model_Config_Data
{
    // Fields which enable Braintree payment methods
    protected $_activeField = array(
        'active',
        'paypal_active',
    );

    /**
     * Prepare data before save
     *
     * If field does not have value and method is enabled throw exception
     */
    protected function _beforeSave()
    {
        if (!$this->getValue() && $this->isValueChanged()) {
            $data = $this->getData();
            foreach ($this->_activeField as $field) {
                $fieldData = $data['groups']['braintree']['fields'][$field];
                if ((isset($fieldData['value']) && $fieldData['value']) ||
                    (isset($fieldData['inherit']) && $fieldData['inherit'] &&
                    ((string) Mage::getConfig()->getNode('default/payment/braintree/' . $field)))) {

                    Mage::throwException(
                        Mage::helper('braintree_payments')->__(
                            'The following fields are required to be completed to save the configuration: ' .
                            'Merchant ID, Merchant Account ID, Public Key and Private Key. No changes were saved'
                        )
                    );
                }
            }
        }
    }
}


text:
SVGPathSegLinetoHorizontalRel object

Defines a SVGPathSeg command with relative horizontal lineto path data.

Members

The SVGPathSegLinetoHorizontalRel object has these types of members:

Properties

Properties

The SVGPathSegLinetoHorizontalRel object has these properties.

Property	Description

pathSegType

Gets the type of the path segment.

pathSegTypeAsLetter

Gets the type of the path segment, specified by the corresponding one-character command name.

x

Gets or sets the x-coordinate value.

Standards information

Scalable Vector Graphics: Paths, Section 8.5.14

Remarks

Note  In addition to the attributes, properties, events, methods, and styles listed above, SVG elements also inherit core HTML attributes, properties, events, methods, and styles.

The h object uses relative coordinates to draw a horizontal line from the current point (cpx, cpy) to (x, cpy). You can provide multiple x-coordinate values (typically, multiple coordinates do not make sense). At the end of the command, the new current point becomes (x, cpy) for the final value of x.

Build date: 1/13/2014


text:
function [] =plot3Images(luminance,luminance2,filename,lossFactor)
h=figure;

[~,name,~]=fileparts(filename);
a=suptitle([name, ': Loss Factor = ', num2str(lossFactor)]);
a.Position(2)=-0.1;

subplot(1,3,1);
imshow(luminance,'border','tight');
title('Original Image');

subplot(1,3,3);
imshow(luminance2,'border','tight');
title('Reconstructed image');

k=255-imabsdiff(luminance,luminance2);
subplot(1,3,2);
imshow(k,'border','tight');
title('Difference');

h.Position=[h.Position(1), h.Position(2), 560,260];
saveas(h,[name,'L',num2str(lossFactor),'_dct.png']);
close(h);
end


text:
using namespace MaxSDK::AssetManagement;

IObjParam *AlembicCameraModifier::ip              = NULL;
AlembicCameraModifier *AlembicCameraModifier::editMod         = NULL;

static AlembicCameraModifierClassDesc AlembicCameraModifierDesc;
ClassDesc2* GetAlembicCameraModifierClassDesc() {return &AlembicCameraModifierDesc;}

//--- Properties block -------------------------------

static const int ALEMBIC_CAMERA_MODIFIER_VERSION = 1;

static ParamBlockDesc2 AlembicCameraModifierParams(
	0,
	_T(ALEMBIC_CAMERA_MODIFIER_SCRIPTNAME),
	0,
	GetAlembicCameraModifierClassDesc(),
	P_AUTO_CONSTRUCT | P_AUTO_UI | P_VERSION,
	ALEMBIC_CAMERA_MODIFIER_VERSION,
	0,

	// rollout description
	IDD_ALEMBIC_CAMERA_PARAMS, IDS_ALEMBIC, 0, 0, NULL,

    // params
	AlembicCameraModifier::ID_PATH, _T("path"), TYPE_FILENAME, P_RESET_DEFAULT, IDS_PATH,
	    p_default, "",
	    p_ui,        TYPE_EDITBOX,		IDC_PATH_EDIT,
		p_assetTypeID,	kExternalLink,
		p_end,

	AlembicCameraModifier::ID_IDENTIFIER, _T("identifier"), TYPE_STRING, P_RESET_DEFAULT, IDS_IDENTIFIER,
	    p_default, "",
	    p_ui,        TYPE_EDITBOX,		IDC_IDENTIFIER_EDIT,
		p_end,

   //set UI for display of floats.
   //Notes:
   //You cannot display a float type as a textfield directly. You must use a spinner. Also, every entry
   //must have a unique param ID value, string table value, text field value (you CANNOT share spinners or string table entries)
   //Might be better to use MAXSCRIPT next time. Unless there is way to write a generic property display in C++.

	AlembicCameraModifier::ID_HFOV, _T("hfov"), TYPE_FLOAT, P_ANIMATABLE, IDS_HFOV,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_HFOV_EDIT,    IDC_HFOV_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_VFOV, _T("vfov"), TYPE_FLOAT, P_ANIMATABLE, IDS_VFOV,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_VFOV_EDIT,    IDC_VFOV_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_FOCAL, _T("focallength"), TYPE_FLOAT, P_ANIMATABLE, IDS_FOCAL_LENGTH,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_FOCAL_LENGTH_EDIT,    IDC_FOCAL_LENGTH_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_HAPERATURE, _T("haperature"), TYPE_FLOAT, P_ANIMATABLE, IDS_HAPERATURE,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_HAPERATURE_EDIT,    IDC_HAPERATURE_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_VAPERATURE, _T("vaperature"), TYPE_FLOAT, P_ANIMATABLE, IDS_VAPERATURE,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_VAPERATURE_EDIT2,    IDC_VAPERATURE_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_HFILMOFFSET, _T("hfilmoffset"), TYPE_FLOAT, P_ANIMATABLE, IDS_HFILMOFFSET,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_HFILMOFFSET_EDIT,    IDC_HFILMOFFSET_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_VFILMOFFSET, _T("vfilmoffset"), TYPE_FLOAT, P_ANIMATABLE, IDS_VFILMOFFSET,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_VFILMOFFSET_EDIT,    IDC_VFILMOFFSET_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_LSRATIO, _T("lsratio"), TYPE_FLOAT, P_ANIMATABLE, IDS_LSRATIO,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_LSRATIO_EDIT,    IDC_LSRATIO_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_OVERSCANL, _T("loverscan"), TYPE_FLOAT, P_ANIMATABLE, IDS_OVERSCANL,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_OVERSCANL_EDIT,    IDC_OVERSCANL_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_OVERSCANR, _T("roverscan"), TYPE_FLOAT, P_ANIMATABLE, IDS_OVERSCANR,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_OVERSCANR_EDIT,    IDC_OVERSCANR_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_OVERSCANT, _T("toverscan"), TYPE_FLOAT, P_ANIMATABLE, IDS_OVERSCANT,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_OVERSCANT_EDIT,    IDC_OVERSCANT_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_OVERSCANB, _T("boverscan"), TYPE_FLOAT, P_ANIMATABLE, IDS_OVERSCANB,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_OVERSCANB_EDIT,    IDC_OVERSCANB_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_FSTOP, _T("fstop"), TYPE_FLOAT, P_ANIMATABLE, IDS_FSTOP,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_FSTOP_EDIT,    IDC_FSTOP_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_FOCUSDIST, _T("focusdistance"), TYPE_FLOAT, P_ANIMATABLE, IDS_FOCUSDIST,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_FOCUSDIST_EDIT,    IDC_FOCUSDIST_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_SHUTTEROPEN, _T("shutteropen"), TYPE_FLOAT, P_ANIMATABLE, IDS_SHUTTEROPEN,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_SHUTTEROPEN_EDIT,    IDC_SHUTTEROPEN_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_SHUTTERCLOSE, _T("shutterclose"), TYPE_FLOAT, P_ANIMATABLE, IDS_SHUTTERCLOSE,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_SHUTTERCLOSE_EDIT,    IDC_SHUTTERCLOSE_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_NEARCLIPPINGPLANE, _T("nclippingplane"), TYPE_FLOAT, P_ANIMATABLE, IDS_NEARCLIPPINGPLANE,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_NEARCLIPPINGPLANE_EDIT,    IDC_NEARCLIPPINGPLANE_SPIN,  0.01f,
		p_end,

	AlembicCameraModifier::ID_FARCLIPPINGPLANE, _T("fclippingplane"), TYPE_FLOAT, P_ANIMATABLE, IDS_FARCLIPPINGPLANE,
		p_default,       0.0f,
		p_range,         0.0f, 1000.0f,
		p_ui,            TYPE_SPINNER,       EDITTYPE_FLOAT, IDC_FAR_CLIPPING_PLANE_EDIT,    IDC_FARCLIPPINGPLANE_SPIN,  0.01f,
		p_end,

	p_end
);

//--- Modifier methods -------------------------------

AlembicCameraModifier::AlembicCameraModifier()
{
    pblock = NULL;
    m_CachedAbcFile = "";

	GetAlembicCameraModifierClassDesc()->MakeAutoParamBlocks(this);
}

AlembicCameraModifier::~AlembicCameraModifier()
{
   delRefArchive(m_CachedAbcFile);
}

RefTargetHandle AlembicCameraModifier::Clone(RemapDir& remap)
{
	AlembicCameraModifier *mod = new AlembicCameraModifier();

    mod->ReplaceReference (0, remap.CloneRef(pblock));

    BaseClone(this, mod, remap);
	return mod;
}

void AlembicCameraModifier::EnumAuxFiles(AssetEnumCallback& nameEnum, DWORD flags)  {
	if ((flags&FILE_ENUM_CHECK_AWORK1)&&TestAFlag(A_WORK1)) return; // LAM - 4/11/03

	if (!(flags&FILE_ENUM_INACTIVE)) return; // not needed by renderer

	if(flags & FILE_ENUM_ACCESSOR_INTERFACE)	{
		IEnumAuxAssetsCallback* callback = static_cast<IEnumAuxAssetsCallback*>(&nameEnum);
		callback->DeclareAsset(AlembicPathAccessor(this));
	}
	//else {
	//	IPathConfigMgr::GetPathConfigMgr()->RecordInputAsset( this->GetParamBlockByID( 0 )->GetAssetUser( GetParamIdByName( this, 0, "path" ), 0 ), nameEnum, flags);
	//}

	ReferenceTarget::EnumAuxFiles(nameEnum, flags);
}

extern bool getCameraSampleVal(AbcG::ICamera& objCamera, SampleInfo& sampleInfo, AbcG::CameraSample sample, const char* name, double& sampleVal);

void AlembicCameraModifier::ModifyObject (TimeValue t, ModContext &mc, ObjectState *os, INode *node)
{
 //  Interval interval = FOREVER;

 //  MCHAR const* strPath = NULL;
	//this->pblock->GetValue( ID_PATH, t, strPath, interval);

	//MCHAR const* strIdentifier = NULL;
	//this->pblock->GetValue( ID_IDENTIFIER, t, strIdentifier, interval);
 //
	//float fTime;
	//this->pblock->GetValue( ID_TIME, t, fTime, interval);

	//std::string szPath = EC_MCHAR_to_UTF8( strPath );
	//std::string szIdentifier = EC_MCHAR_to_UTF8( strIdentifier );

	//if( szPath.size() == 0 ) {
	//   ESS_LOG_ERROR( "No filename specified." );
	//   return;
	//}
	//if( szIdentifier.size() == 0 ) {
	//   ESS_LOG_ERROR( "No path specified." );
	//   return;
	//}

 //  AbcG::IObject iObj = getObjectFromArchive(szPath, szIdentifier);

 //  if(!iObj.valid() || !AbcG::ICamera::matches(iObj.getMetaData())) {
 //     return;
 //  }

 //  AbcG::ICamera objCamera = AbcG::ICamera(iObj, Abc::kWrapExisting);

 //  TimeValue dTicks = GetTimeValueFromSeconds( fTime );
 //  double sampleTime = GetSecondsFromTimeValue(dTicks);

 //  SampleInfo sampleInfo = getSampleInfo(sampleTime,
 //                             objCamera.getSchema().getTimeSampling(),
 //                             objCamera.getSchema().getNumSamples());
 //  AbcG::CameraSample sample;
 //  objCamera.getSchema().get(sample, sampleInfo.floorIndex);

 //  double sampleVal = 0.0;
 //  if(::getCameraSampleVal(objCamera, sampleInfo, sample, "horizontalFOV", sampleVal)){
 //
 //  }

}
#if ( crate_Max_Version >= 2015 )
RefResult AlembicCameraModifier::NotifyRefChanged (const Interval& changeInt, RefTargetHandle hTarget,
										   PartID& partID, RefMessage message, BOOL propagate) {
#else
RefResult AlembicCameraModifier::NotifyRefChanged (Interval changeInt, RefTargetHandle hTarget,
										   PartID& partID, RefMessage message) {
#endif
	ESS_CPP_EXCEPTION_REPORTING_START

	switch (message)
    {
    case REFMSG_CHANGE:
        if (hTarget == pblock)
        {
            ParamID changing_param = pblock->LastNotifyParamID();
            switch(changing_param)
            {
            case ID_PATH:
                {
                    delRefArchive(m_CachedAbcFile);
                    MCHAR const* strPath = NULL;
                    TimeValue t = GetCOREInterface()->GetTime();
					Interval v;
                    pblock->GetValue( AlembicCameraModifier::ID_PATH, t, strPath, v);
                    m_CachedAbcFile = EC_MCHAR_to_UTF8( strPath );
                    addRefArchive(m_CachedAbcFile);
                }
                break;
            default:
                break;
            }

            AlembicCameraModifierParams.InvalidateUI(changing_param);
        }
        break;

    case REFMSG_WANT_SHOWPARAMLEVEL:

        break;
	}

	ESS_CPP_EXCEPTION_REPORTING_END

	return REF_SUCCEED;
}

void AlembicCameraModifier::BeginEditParams(IObjParam *ip,ULONG flags,Animatable *prev)
{
	this->ip = ip;
    editMod  = this;

	AlembicCameraModifierDesc.BeginEditParams(ip, this, flags, prev);
}

void AlembicCameraModifier::EndEditParams( IObjParam *ip, ULONG flags, Animatable *next )
{
	AlembicCameraModifierDesc.EndEditParams(ip, this, flags, next);

	this->ip = NULL;
    editMod  = NULL;
}


text:
package morfologik.fsa.builders;

import java.util.*;

import morfologik.fsa.FSA;
import static morfologik.fsa.builders.ConstantArcSizeFSA.*;

/**
 * Fast, memory-conservative finite state automaton builder, returning an
 * in-memory {@link FSA} that is a tradeoff between construction speed and
 * memory consumption. Use serializers to compress the returned automaton into
 * more compact form.
 *
 * @see FSASerializer
 */
public final class FSABuilder {
  /**
   * Debug and information constants.
   *
   * @see FSABuilder#getInfo()
   */
  public enum InfoEntry {
    SERIALIZATION_BUFFER_SIZE("Serialization buffer size"),
    SERIALIZATION_BUFFER_REALLOCATIONS("Serialization buffer reallocs"),
    CONSTANT_ARC_AUTOMATON_SIZE("Constant arc FSA size"),
    MAX_ACTIVE_PATH_LENGTH("Max active path"),
    STATE_REGISTRY_TABLE_SLOTS("Registry hash slots"),
    STATE_REGISTRY_SIZE("Registry hash entries"),
    ESTIMATED_MEMORY_CONSUMPTION_MB("Estimated mem consumption (MB)");

    private final String stringified;

    InfoEntry(String stringified) {
      this.stringified = stringified;
    }

    @Override
    public String toString() {
      return stringified;
    }
  }

  /** A megabyte. */
  private final static int MB = 1024 * 1024;

  /**
   * Internal serialized FSA buffer expand ratio.
   */
  private final static int BUFFER_GROWTH_SIZE = 5 * MB;

  /**
   * Maximum number of labels from a single state.
   */
  private final static int MAX_LABELS = 256;

  /**
   * A comparator comparing full byte arrays. Unsigned byte comparisons ('C'-locale).
   */
  public static final Comparator<byte[]> LEXICAL_ORDERING = new Comparator<byte[]>() {
    public int compare(byte[] o1, byte[] o2) {
      return FSABuilder.compare(o1, 0, o1.length, o2, 0, o2.length);
    }
  };

  /**
   * Internal serialized FSA buffer expand ratio.
   */
  private final int bufferGrowthSize;

  /**
   * Holds serialized and mutable states. Each state is a sequential list of
   * arcs, the last arc is marked with {@link #BIT_ARC_LAST}.
   */
  private byte[] serialized = new byte[0];

  /**
   * Number of bytes already taken in {@link #serialized}. Start from 1 to keep
   * 0 a sentinel value (for the hash set and final state).
   */
  private int size;

  /**
   * States on the "active path" (still mutable). Values are addresses of each
   * state's first arc.
   */
  private int[] activePath = new int[0];

  /**
   * Current length of the active path.
   */
  private int activePathLen;

  /**
   * The next offset at which an arc will be added to the given state on
   * {@link #activePath}.
   */
  private int[] nextArcOffset = new int[0];

  /**
   * Root state. If negative, the automaton has been built already and cannot be
   * extended.
   */
  private int root;

  /**
   * An epsilon state. The first and only arc of this state points either to the
   * root or to the terminal state, indicating an empty automaton.
   */
  private int epsilon;

  /**
   * Hash set of state addresses in {@link #serialized}, hashed by
   * {@link #hash(int, int)}. Zero reserved for an unoccupied slot.
   */
  private int[] hashSet = new int[2];

  /**
   * Number of entries currently stored in {@link #hashSet}.
   */
  private int hashSize = 0;

  /**
   * Previous sequence added to the automaton in {@link #add(byte[], int, int)}.
   * Used in assertions only.
   */
  private byte[] previous;

  /**
   * Information about the automaton and its compilation.
   */
  private TreeMap<InfoEntry, Object> info;

  /**
   * {@link #previous} sequence's length, used in assertions only.
   */
  private int previousLength;

  /** */
  public FSABuilder() {
    this(BUFFER_GROWTH_SIZE);
  }

  /**
   * @param bufferGrowthSize Buffer growth size (in bytes) when constructing the automaton.
   */
  public FSABuilder(int bufferGrowthSize) {
    this.bufferGrowthSize = Math.max(bufferGrowthSize, ARC_SIZE * MAX_LABELS);

    // Allocate epsilon state.
    epsilon = allocateState(1);
    serialized[epsilon + FLAGS_OFFSET] |= BIT_ARC_LAST;

    // Allocate root, with an initial empty set of output arcs.
    expandActivePath(1);
    root = activePath[0];
  }

  /**
   * Add a single sequence of bytes to the FSA. The input must be
   * lexicographically greater than any previously added sequence.
   *
   * @param sequence The array holding input sequence of bytes.
   * @param start Starting offset (inclusive)
   * @param len Length of the input sequence (at least 1 byte).
   */
  public void add(byte[] sequence, int start, int len) {
    assert serialized != null : "Automaton already built.";
    assert previous == null || len == 0 || compare(previous, 0, previousLength, sequence, start, len) <= 0 : "Input must be sorted: "
        + Arrays.toString(Arrays.copyOf(previous, previousLength))
        + " >= "
        + Arrays.toString(Arrays.copyOfRange(sequence, start, len));
    assert setPrevious(sequence, start, len);

    // Determine common prefix length.
    final int commonPrefix = commonPrefix(sequence, start, len);

    // Make room for extra states on active path, if needed.
    expandActivePath(len);

    // Freeze all the states after the common prefix.
    for (int i = activePathLen - 1; i > commonPrefix; i--) {
      final int frozenState = freezeState(i);
      setArcTarget(nextArcOffset[i - 1] - ARC_SIZE, frozenState);
      nextArcOffset[i] = activePath[i];
    }

    // Create arcs to new suffix states.
    for (int i = commonPrefix + 1, j = start + commonPrefix; i <= len; i++) {
      final int p = nextArcOffset[i - 1];

      serialized[p + FLAGS_OFFSET] = (byte) (i == len ? BIT_ARC_FINAL : 0);
      serialized[p + LABEL_OFFSET] = sequence[j++];
      setArcTarget(p, i == len ? TERMINAL_STATE : activePath[i]);

      nextArcOffset[i - 1] = p + ARC_SIZE;
    }

    // Save last sequence's length so that we don't need to calculate it again.
    this.activePathLen = len;
  }

  /** Number of serialization buffer reallocations. */
  private int serializationBufferReallocations;

  /**
   * @return Finalizes the construction of the automaton and returns it.
   */
  public FSA complete() {
    add(new byte[0], 0, 0);

    if (nextArcOffset[0] - activePath[0] == 0) {
      // An empty FSA.
      setArcTarget(epsilon, TERMINAL_STATE);
    } else {
      // An automaton with at least a single arc from root.
      root = freezeState(0);
      setArcTarget(epsilon, root);
    }

    info = new TreeMap<InfoEntry, Object>();
    info.put(InfoEntry.SERIALIZATION_BUFFER_SIZE, serialized.length);
    info.put(InfoEntry.SERIALIZATION_BUFFER_REALLOCATIONS, serializationBufferReallocations);
    info.put(InfoEntry.CONSTANT_ARC_AUTOMATON_SIZE, size);
    info.put(InfoEntry.MAX_ACTIVE_PATH_LENGTH, activePath.length);
    info.put(InfoEntry.STATE_REGISTRY_TABLE_SLOTS, hashSet.length);
    info.put(InfoEntry.STATE_REGISTRY_SIZE, hashSize);
    info.put(InfoEntry.ESTIMATED_MEMORY_CONSUMPTION_MB,
        (this.serialized.length + this.hashSet.length * 4) / (double) MB);

    final FSA fsa = new ConstantArcSizeFSA(java.util.Arrays.copyOf(this.serialized, this.size), epsilon);
    this.serialized = null;
    this.hashSet = null;
    return fsa;
  }

  /**
   * Build a minimal, deterministic automaton from a sorted list of byte
   * sequences.
   *
   * @param input Input sequences to build automaton from.
   * @return Returns the automaton encoding all input sequences.
   */
  public static FSA build(byte[][] input) {
    final FSABuilder builder = new FSABuilder();

    for (byte[] chs : input) {
      builder.add(chs, 0, chs.length);
    }

    return builder.complete();
  }

  /**
   * Build a minimal, deterministic automaton from an iterable list of byte
   * sequences.
   *
   * @param input Input sequences to build automaton from.
   * @return Returns the automaton encoding all input sequences.
   */
  public static FSA build(Iterable<byte[]> input) {
    final FSABuilder builder = new FSABuilder();

    for (byte[] chs : input) {
      builder.add(chs, 0, chs.length);
    }

    return builder.complete();
  }

  /**
   * @return Returns various statistics concerning the FSA and its compilation.
   * @see InfoEntry
   */
  public Map<InfoEntry, Object> getInfo() {
    return info;
  }

  /** Is this arc the state's last? */
  private boolean isArcLast(int arc) {
    return (serialized[arc + FLAGS_OFFSET] & BIT_ARC_LAST) != 0;
  }

  /** Is this arc final? */
  private boolean isArcFinal(int arc) {
    return (serialized[arc + FLAGS_OFFSET] & BIT_ARC_FINAL) != 0;
  }

  /** Get label's arc. */
  private byte getArcLabel(int arc) {
    return serialized[arc + LABEL_OFFSET];
  }

  /**
   * Fills the target state address of an arc.
   */
  private void setArcTarget(int arc, int state) {
    arc += ADDRESS_OFFSET + TARGET_ADDRESS_SIZE;
    for (int i = 0; i < TARGET_ADDRESS_SIZE; i++) {
      serialized[--arc] = (byte) state;
      state >>>= 8;
    }
  }

  /**
   * Returns the address of an arc.
   */
  private int getArcTarget(int arc) {
    arc += ADDRESS_OFFSET;
    return (serialized[arc]           ) << 24 |
           (serialized[arc + 1] & 0xff) << 16 |
           (serialized[arc + 2] & 0xff) << 8  |
           (serialized[arc + 3] & 0xff);
  }

  /**
   * @return The number of common prefix characters with the previous sequence.
   */
  private int commonPrefix(byte[] sequence, int start, int len) {
    // Empty root state case.
    final int max = Math.min(len, activePathLen);
    int i;
    for (i = 0; i < max; i++) {
      final int lastArc = nextArcOffset[i] - ARC_SIZE;
      if (sequence[start++] != getArcLabel(lastArc)) {
        break;
      }
    }

    return i;
  }

  /**
   * Freeze a state: try to find an equivalent state in the interned states
   * dictionary first, if found, return it, otherwise, serialize the mutable
   * state at activePathIndex and return it.
   */
  private int freezeState(final int activePathIndex) {
    final int start = activePath[activePathIndex];
    final int end = nextArcOffset[activePathIndex];
    final int len = end - start;

    // Set the last arc flag on the current active path's state.
    serialized[end - ARC_SIZE + FLAGS_OFFSET] |= BIT_ARC_LAST;

    // Try to locate a state with an identical content in the hash set.
    final int bucketMask = (hashSet.length - 1);
    int slot = hash(start, len) & bucketMask;
    for (int i = 0;;) {
      int state = hashSet[slot];
      if (state == 0) {
        state = hashSet[slot] = serialize(activePathIndex);
        if (++hashSize > hashSet.length / 2)
          expandAndRehash();
        return state;
      } else if (equivalent(state, start, len)) {
        return state;
      }

      slot = (slot + (++i)) & bucketMask;
    }
  }

  /**
   * Reallocate and rehash the hash set.
   */
  private void expandAndRehash() {
    final int[] newHashSet = new int[hashSet.length * 2];
    final int bucketMask = (newHashSet.length - 1);

    for (int j = 0; j < hashSet.length; j++) {
      final int state = hashSet[j];
      if (state > 0) {
        int slot = hash(state, stateLength(state)) & bucketMask;
        for (int i = 0; newHashSet[slot] > 0;) {
          slot = (slot + (++i)) & bucketMask;
        }
        newHashSet[slot] = state;
      }
    }
    this.hashSet = newHashSet;
  }

  /**
   * The total length of the serialized state data (all arcs).
   */
  private int stateLength(int state) {
    int arc = state;
    while (!isArcLast(arc)) {
      arc += ARC_SIZE;
    }
    return arc - state + ARC_SIZE;
  }

  /**
   * Return true if two regions in {@link #serialized} are
   * identical.
   */
  private boolean equivalent(int start1, int start2, int len) {
    if (start1 + len > size || start2 + len > size)
      return false;

    while (len-- > 0)
      if (serialized[start1++] != serialized[start2++])
        return false;

    return true;
  }

  /**
   * Serialize a given state on the active path.
   */
  private int serialize(final int activePathIndex) {
    expandBuffers();

    final int newState = size;
    final int start = activePath[activePathIndex];
    final int len = nextArcOffset[activePathIndex] - start;
    System.arraycopy(serialized, start, serialized, newState, len);

    size += len;
    return newState;
  }

  /**
   * Hash code of a fragment of {@link #serialized} array.
   */
  private int hash(int start, int byteCount) {
    assert byteCount % ARC_SIZE == 0 : "Not an arc multiply?";

    int h = 0;
    for (int arcs = byteCount / ARC_SIZE; --arcs >= 0; start += ARC_SIZE) {
      h = 17 * h + getArcLabel(start);
      h = 17 * h + getArcTarget(start);
      if (isArcFinal(start))
        h += 17;
    }

    return h;
  }

  /**
   * Append a new mutable state to the active path.
   */
  private void expandActivePath(int size) {
    if (activePath.length < size) {
      final int p = activePath.length;
      activePath = java.util.Arrays.copyOf(activePath, size);
      nextArcOffset = java.util.Arrays.copyOf(nextArcOffset, size);

      for (int i = p; i < size; i++) {
        nextArcOffset[i] = activePath[i] = allocateState(/* assume max labels count */MAX_LABELS);
      }
    }
  }

  /**
   * Expand internal buffers for the next state.
   */
  private void expandBuffers() {
    if (this.serialized.length < size + ARC_SIZE * MAX_LABELS) {
      serialized = java.util.Arrays.copyOf(serialized, serialized.length + bufferGrowthSize);
      serializationBufferReallocations++;
    }
  }

  /**
   * Allocate space for a state with the given number of outgoing labels.
   *
   * @return state offset
   */
  private int allocateState(int labels) {
    expandBuffers();
    final int state = size;
    size += labels * ARC_SIZE;
    return state;
  }

  /**
   * Copy current into an internal buffer.
   */
  private boolean setPrevious(byte[] sequence, int start, int length) {
    if (previous == null || previous.length < length) {
      previous = new byte[length];
    }

    System.arraycopy(sequence, start, previous, 0, length);
    previousLength = length;
    return true;
  }

  /**
   * Lexicographic order of input sequences. By default, consistent with the "C"
   * sort (absolute value of bytes, 0-255).
   */
  private static int compare(byte[] s1, int start1, int lens1, byte[] s2, int start2, int lens2) {
    final int max = Math.min(lens1, lens2);

    for (int i = 0; i < max; i++) {
      final byte c1 = s1[start1++];
      final byte c2 = s2[start2++];
      if (c1 != c2)
        return (c1 & 0xff) - (c2 & 0xff);
    }

    return lens1 - lens2;
  }
}


text:
require File.expand_path 'spec_helper.rb', __dir__

describe 'StringExtensions' do
  it 'can create a KeyPath instance from itself' do
    example_string = 'item.url'

    example_string.to_keypath.wont_be_nil
    example_string.to_keypath.must_be_kind_of KeyPath::Path

    # around and around we go
    example_string.to_keypath.to_s.must_equal example_string
  end

  it 'can make a set of strings plural' do
    %w(word rail dress business).each do |v|
      v.is_plural?.must_equal false
    end

    %w(words rails dresses businesses).each do |v|
      v.is_plural?.must_equal true
    end
  end

  it 'can make a set of string singular' do
    %w(word rail dress business).each do |v|
      v.is_singular?.must_equal true
    end

    %w(words rails dresses businesses).each do |v|
      v.is_singular?.must_equal false
    end
  end

  it 'can test if a string is actually a number' do
    '0'.is_number?.must_equal true
    '1234567890'.is_number?.must_equal true

    'item'.is_number?.must_equal false
  end
end


text:
package bugreports

type InterfaceUint8 interface {
	DoSomthingUint8()
}

// Call calls a method on an instance of generic interface.
// Targets github issue 49
func CallWithUint8(i InterfaceUint8) {
	i.DoSomthingUint8()
}


text:
#pragma once
#include <aws/machinelearning/MachineLearning_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <aws/machinelearning/model/EntityStatus.h>
#include <aws/machinelearning/model/PerformanceMetrics.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace MachineLearning
{
namespace Model
{

  /**
   *
 Represents the output of GetEvaluation operation.

The
   * content consists of the detailed metadata and data file information and the
   * current status of the Evaluation.

See Also:
   AWS
   * API Reference

   */
  class AWS_MACHINELEARNING_API Evaluation
  {
  public:
    Evaluation();
    Evaluation(const Aws::Utils::Json::JsonValue& jsonValue);
    Evaluation& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The ID that is assigned to the Evaluation at creation.

     */
    inline const Aws::String& GetEvaluationId() const{ return m_evaluationId; }

    /**
     *
The ID that is assigned to the Evaluation at creation.

     */
    inline void SetEvaluationId(const Aws::String& value) { m_evaluationIdHasBeenSet = true; m_evaluationId = value; }

    /**
     *
The ID that is assigned to the Evaluation at creation.

     */
    inline void SetEvaluationId(Aws::String&& value) { m_evaluationIdHasBeenSet = true; m_evaluationId = std::move(value); }

    /**
     *
The ID that is assigned to the Evaluation at creation.

     */
    inline void SetEvaluationId(const char* value) { m_evaluationIdHasBeenSet = true; m_evaluationId.assign(value); }

    /**
     *
The ID that is assigned to the Evaluation at creation.

     */
    inline Evaluation& WithEvaluationId(const Aws::String& value) { SetEvaluationId(value); return *this;}

    /**
     *
The ID that is assigned to the Evaluation at creation.

     */
    inline Evaluation& WithEvaluationId(Aws::String&& value) { SetEvaluationId(std::move(value)); return *this;}

    /**
     *
The ID that is assigned to the Evaluation at creation.

     */
    inline Evaluation& WithEvaluationId(const char* value) { SetEvaluationId(value); return *this;}

    /**
     *
The ID of the MLModel that is the focus of the evaluation.

     */
    inline const Aws::String& GetMLModelId() const{ return m_mLModelId; }

    /**
     *
The ID of the MLModel that is the focus of the evaluation.

     */
    inline void SetMLModelId(const Aws::String& value) { m_mLModelIdHasBeenSet = true; m_mLModelId = value; }

    /**
     *
The ID of the MLModel that is the focus of the evaluation.

     */
    inline void SetMLModelId(Aws::String&& value) { m_mLModelIdHasBeenSet = true; m_mLModelId = std::move(value); }

    /**
     *
The ID of the MLModel that is the focus of the evaluation.

     */
    inline void SetMLModelId(const char* value) { m_mLModelIdHasBeenSet = true; m_mLModelId.assign(value); }

    /**
     *
The ID of the MLModel that is the focus of the evaluation.

     */
    inline Evaluation& WithMLModelId(const Aws::String& value) { SetMLModelId(value); return *this;}

    /**
     *
The ID of the MLModel that is the focus of the evaluation.

     */
    inline Evaluation& WithMLModelId(Aws::String&& value) { SetMLModelId(std::move(value)); return *this;}

    /**
     *
The ID of the MLModel that is the focus of the evaluation.

     */
    inline Evaluation& WithMLModelId(const char* value) { SetMLModelId(value); return *this;}

    /**
     *
The ID of the DataSource that is used to evaluate the
     * MLModel.

     */
    inline const Aws::String& GetEvaluationDataSourceId() const{ return m_evaluationDataSourceId; }

    /**
     *
The ID of the DataSource that is used to evaluate the
     * MLModel.

     */
    inline void SetEvaluationDataSourceId(const Aws::String& value) { m_evaluationDataSourceIdHasBeenSet = true; m_evaluationDataSourceId = value; }

    /**
     *
The ID of the DataSource that is used to evaluate the
     * MLModel.

     */
    inline void SetEvaluationDataSourceId(Aws::String&& value) { m_evaluationDataSourceIdHasBeenSet = true; m_evaluationDataSourceId = std::move(value); }

    /**
     *
The ID of the DataSource that is used to evaluate the
     * MLModel.

     */
    inline void SetEvaluationDataSourceId(const char* value) { m_evaluationDataSourceIdHasBeenSet = true; m_evaluationDataSourceId.assign(value); }

    /**
     *
The ID of the DataSource that is used to evaluate the
     * MLModel.

     */
    inline Evaluation& WithEvaluationDataSourceId(const Aws::String& value) { SetEvaluationDataSourceId(value); return *this;}

    /**
     *
The ID of the DataSource that is used to evaluate the
     * MLModel.

     */
    inline Evaluation& WithEvaluationDataSourceId(Aws::String&& value) { SetEvaluationDataSourceId(std::move(value)); return *this;}

    /**
     *
The ID of the DataSource that is used to evaluate the
     * MLModel.

     */
    inline Evaluation& WithEvaluationDataSourceId(const char* value) { SetEvaluationDataSourceId(value); return *this;}

    /**
     *
The location and name of the data in Amazon Simple Storage Server (Amazon S3)
     * that is used in the evaluation.

     */
    inline const Aws::String& GetInputDataLocationS3() const{ return m_inputDataLocationS3; }

    /**
     *
The location and name of the data in Amazon Simple Storage Server (Amazon S3)
     * that is used in the evaluation.

     */
    inline void SetInputDataLocationS3(const Aws::String& value) { m_inputDataLocationS3HasBeenSet = true; m_inputDataLocationS3 = value; }

    /**
     *
The location and name of the data in Amazon Simple Storage Server (Amazon S3)
     * that is used in the evaluation.

     */
    inline void SetInputDataLocationS3(Aws::String&& value) { m_inputDataLocationS3HasBeenSet = true; m_inputDataLocationS3 = std::move(value); }

    /**
     *
The location and name of the data in Amazon Simple Storage Server (Amazon S3)
     * that is used in the evaluation.

     */
    inline void SetInputDataLocationS3(const char* value) { m_inputDataLocationS3HasBeenSet = true; m_inputDataLocationS3.assign(value); }

    /**
     *
The location and name of the data in Amazon Simple Storage Server (Amazon S3)
     * that is used in the evaluation.

     */
    inline Evaluation& WithInputDataLocationS3(const Aws::String& value) { SetInputDataLocationS3(value); return *this;}

    /**
     *
The location and name of the data in Amazon Simple Storage Server (Amazon S3)
     * that is used in the evaluation.

     */
    inline Evaluation& WithInputDataLocationS3(Aws::String&& value) { SetInputDataLocationS3(std::move(value)); return *this;}

    /**
     *
The location and name of the data in Amazon Simple Storage Server (Amazon S3)
     * that is used in the evaluation.

     */
    inline Evaluation& WithInputDataLocationS3(const char* value) { SetInputDataLocationS3(value); return *this;}

    /**
     *
The AWS user account that invoked the evaluation. The account type can be
     * either an AWS root account or an AWS Identity and Access Management (IAM) user
     * account.

     */
    inline const Aws::String& GetCreatedByIamUser() const{ return m_createdByIamUser; }

    /**
     *
The AWS user account that invoked the evaluation. The account type can be
     * either an AWS root account or an AWS Identity and Access Management (IAM) user
     * account.

     */
    inline void SetCreatedByIamUser(const Aws::String& value) { m_createdByIamUserHasBeenSet = true; m_createdByIamUser = value; }

    /**
     *
The AWS user account that invoked the evaluation. The account type can be
     * either an AWS root account or an AWS Identity and Access Management (IAM) user
     * account.

     */
    inline void SetCreatedByIamUser(Aws::String&& value) { m_createdByIamUserHasBeenSet = true; m_createdByIamUser = std::move(value); }

    /**
     *
The AWS user account that invoked the evaluation. The account type can be
     * either an AWS root account or an AWS Identity and Access Management (IAM) user
     * account.

     */
    inline void SetCreatedByIamUser(const char* value) { m_createdByIamUserHasBeenSet = true; m_createdByIamUser.assign(value); }

    /**
     *
The AWS user account that invoked the evaluation. The account type can be
     * either an AWS root account or an AWS Identity and Access Management (IAM) user
     * account.

     */
    inline Evaluation& WithCreatedByIamUser(const Aws::String& value) { SetCreatedByIamUser(value); return *this;}

    /**
     *
The AWS user account that invoked the evaluation. The account type can be
     * either an AWS root account or an AWS Identity and Access Management (IAM) user
     * account.

     */
    inline Evaluation& WithCreatedByIamUser(Aws::String&& value) { SetCreatedByIamUser(std::move(value)); return *this;}

    /**
     *
The AWS user account that invoked the evaluation. The account type can be
     * either an AWS root account or an AWS Identity and Access Management (IAM) user
     * account.

     */
    inline Evaluation& WithCreatedByIamUser(const char* value) { SetCreatedByIamUser(value); return *this;}

    /**
     *
The time that the Evaluation was created. The time is expressed
     * in epoch time.

     */
    inline const Aws::Utils::DateTime& GetCreatedAt() const{ return m_createdAt; }

    /**
     *
The time that the Evaluation was created. The time is expressed
     * in epoch time.

     */
    inline void SetCreatedAt(const Aws::Utils::DateTime& value) { m_createdAtHasBeenSet = true; m_createdAt = value; }

    /**
     *
The time that the Evaluation was created. The time is expressed
     * in epoch time.

     */
    inline void SetCreatedAt(Aws::Utils::DateTime&& value) { m_createdAtHasBeenSet = true; m_createdAt = std::move(value); }

    /**
     *
The time that the Evaluation was created. The time is expressed
     * in epoch time.

     */
    inline Evaluation& WithCreatedAt(const Aws::Utils::DateTime& value) { SetCreatedAt(value); return *this;}

    /**
     *
The time that the Evaluation was created. The time is expressed
     * in epoch time.

     */
    inline Evaluation& WithCreatedAt(Aws::Utils::DateTime&& value) { SetCreatedAt(std::move(value)); return *this;}

    /**
     *
The time of the most recent edit to the Evaluation. The time is
     * expressed in epoch time.

     */
    inline const Aws::Utils::DateTime& GetLastUpdatedAt() const{ return m_lastUpdatedAt; }

    /**
     *
The time of the most recent edit to the Evaluation. The time is
     * expressed in epoch time.

     */
    inline void SetLastUpdatedAt(const Aws::Utils::DateTime& value) { m_lastUpdatedAtHasBeenSet = true; m_lastUpdatedAt = value; }

    /**
     *
The time of the most recent edit to the Evaluation. The time is
     * expressed in epoch time.

     */
    inline void SetLastUpdatedAt(Aws::Utils::DateTime&& value) { m_lastUpdatedAtHasBeenSet = true; m_lastUpdatedAt = std::move(value); }

    /**
     *
The time of the most recent edit to the Evaluation. The time is
     * expressed in epoch time.

     */
    inline Evaluation& WithLastUpdatedAt(const Aws::Utils::DateTime& value) { SetLastUpdatedAt(value); return *this;}

    /**
     *
The time of the most recent edit to the Evaluation. The time is
     * expressed in epoch time.

     */
    inline Evaluation& WithLastUpdatedAt(Aws::Utils::DateTime&& value) { SetLastUpdatedAt(std::move(value)); return *this;}

    /**
     *
A user-supplied name or description of the Evaluation.

     */
    inline const Aws::String& GetName() const{ return m_name; }

    /**
     *
A user-supplied name or description of the Evaluation.

     */
    inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
A user-supplied name or description of the Evaluation.

     */
    inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
A user-supplied name or description of the Evaluation.

     */
    inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }

    /**
     *
A user-supplied name or description of the Evaluation.

     */
    inline Evaluation& WithName(const Aws::String& value) { SetName(value); return *this;}

    /**
     *
A user-supplied name or description of the Evaluation.

     */
    inline Evaluation& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;}

    /**
     *
A user-supplied name or description of the Evaluation.

     */
    inline Evaluation& WithName(const char* value) { SetName(value); return *this;}

    /**
     *
The status of the evaluation. This element can have one of the following
     * values:

 PENDING - Amazon Machine Learning (Amazon ML)
     * submitted a request to evaluate an MLModel.

     * INPROGRESS - The evaluation is underway.

     * FAILED - The request to evaluate an MLModel did not
     * run to completion. It is not usable.

 COMPLETED - The
     * evaluation process completed successfully.

 DELETED - The
     * Evaluation is marked as deleted. It is not usable.

     */
    inline const EntityStatus& GetStatus() const{ return m_status; }

    /**
     *
The status of the evaluation. This element can have one of the following
     * values:

 PENDING - Amazon Machine Learning (Amazon ML)
     * submitted a request to evaluate an MLModel.

     * INPROGRESS - The evaluation is underway.

     * FAILED - The request to evaluate an MLModel did not
     * run to completion. It is not usable.

 COMPLETED - The
     * evaluation process completed successfully.

 DELETED - The
     * Evaluation is marked as deleted. It is not usable.

     */
    inline void SetStatus(const EntityStatus& value) { m_statusHasBeenSet = true; m_status = value; }

    /**
     *
The status of the evaluation. This element can have one of the following
     * values:

 PENDING - Amazon Machine Learning (Amazon ML)
     * submitted a request to evaluate an MLModel.

     * INPROGRESS - The evaluation is underway.

     * FAILED - The request to evaluate an MLModel did not
     * run to completion. It is not usable.

 COMPLETED - The
     * evaluation process completed successfully.

 DELETED - The
     * Evaluation is marked as deleted. It is not usable.

     */
    inline void SetStatus(EntityStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }

    /**
     *
The status of the evaluation. This element can have one of the following
     * values:

 PENDING - Amazon Machine Learning (Amazon ML)
     * submitted a request to evaluate an MLModel.

     * INPROGRESS - The evaluation is underway.

     * FAILED - The request to evaluate an MLModel did not
     * run to completion. It is not usable.

 COMPLETED - The
     * evaluation process completed successfully.

 DELETED - The
     * Evaluation is marked as deleted. It is not usable.

     */
    inline Evaluation& WithStatus(const EntityStatus& value) { SetStatus(value); return *this;}

    /**
     *
The status of the evaluation. This element can have one of the following
     * values:

 PENDING - Amazon Machine Learning (Amazon ML)
     * submitted a request to evaluate an MLModel.

     * INPROGRESS - The evaluation is underway.

     * FAILED - The request to evaluate an MLModel did not
     * run to completion. It is not usable.

 COMPLETED - The
     * evaluation process completed successfully.

 DELETED - The
     * Evaluation is marked as deleted. It is not usable.

     */
    inline Evaluation& WithStatus(EntityStatus&& value) { SetStatus(std::move(value)); return *this;}

    /**
     *
Measurements of how well the MLModel performed, using
     * observations referenced by the DataSource. One of the following
     * metrics is returned, based on the type of the MLModel:

     *

BinaryAUC: A binary MLModel uses the Area Under the Curve
     * (AUC) technique to measure performance.

RegressionRMSE: A
     * regression MLModel uses the Root Mean Square Error (RMSE) technique
     * to measure performance. RMSE measures the difference between predicted and
     * actual values for a single variable.

MulticlassAvgFScore: A
     * multiclass MLModel uses the F1 score technique to measure
     * performance.

 For more information about performance
     * metrics, please see the Amazon Machine
     * Learning Developer Guide.

     */
    inline const PerformanceMetrics& GetPerformanceMetrics() const{ return m_performanceMetrics; }

    /**
     *
Measurements of how well the MLModel performed, using
     * observations referenced by the DataSource. One of the following
     * metrics is returned, based on the type of the MLModel:

     *

BinaryAUC: A binary MLModel uses the Area Under the Curve
     * (AUC) technique to measure performance.

RegressionRMSE: A
     * regression MLModel uses the Root Mean Square Error (RMSE) technique
     * to measure performance. RMSE measures the difference between predicted and
     * actual values for a single variable.

MulticlassAvgFScore: A
     * multiclass MLModel uses the F1 score technique to measure
     * performance.

 For more information about performance
     * metrics, please see the Amazon Machine
     * Learning Developer Guide.

     */
    inline void SetPerformanceMetrics(const PerformanceMetrics& value) { m_performanceMetricsHasBeenSet = true; m_performanceMetrics = value; }

    /**
     *
Measurements of how well the MLModel performed, using
     * observations referenced by the DataSource. One of the following
     * metrics is returned, based on the type of the MLModel:

     *

BinaryAUC: A binary MLModel uses the Area Under the Curve
     * (AUC) technique to measure performance.

RegressionRMSE: A
     * regression MLModel uses the Root Mean Square Error (RMSE) technique
     * to measure performance. RMSE measures the difference between predicted and
     * actual values for a single variable.

MulticlassAvgFScore: A
     * multiclass MLModel uses the F1 score technique to measure
     * performance.

 For more information about performance
     * metrics, please see the Amazon Machine
     * Learning Developer Guide.

     */
    inline void SetPerformanceMetrics(PerformanceMetrics&& value) { m_performanceMetricsHasBeenSet = true; m_performanceMetrics = std::move(value); }

    /**
     *
Measurements of how well the MLModel performed, using
     * observations referenced by the DataSource. One of the following
     * metrics is returned, based on the type of the MLModel:

     *

BinaryAUC: A binary MLModel uses the Area Under the Curve
     * (AUC) technique to measure performance.

RegressionRMSE: A
     * regression MLModel uses the Root Mean Square Error (RMSE) technique
     * to measure performance. RMSE measures the difference between predicted and
     * actual values for a single variable.

MulticlassAvgFScore: A
     * multiclass MLModel uses the F1 score technique to measure
     * performance.

 For more information about performance
     * metrics, please see the Amazon Machine
     * Learning Developer Guide.

     */
    inline Evaluation& WithPerformanceMetrics(const PerformanceMetrics& value) { SetPerformanceMetrics(value); return *this;}

    /**
     *
Measurements of how well the MLModel performed, using
     * observations referenced by the DataSource. One of the following
     * metrics is returned, based on the type of the MLModel:

     *

BinaryAUC: A binary MLModel uses the Area Under the Curve
     * (AUC) technique to measure performance.

RegressionRMSE: A
     * regression MLModel uses the Root Mean Square Error (RMSE) technique
     * to measure performance. RMSE measures the difference between predicted and
     * actual values for a single variable.

MulticlassAvgFScore: A
     * multiclass MLModel uses the F1 score technique to measure
     * performance.

 For more information about performance
     * metrics, please see the Amazon Machine
     * Learning Developer Guide.

     */
    inline Evaluation& WithPerformanceMetrics(PerformanceMetrics&& value) { SetPerformanceMetrics(std::move(value)); return *this;}

    /**
     *
A description of the most recent details about evaluating the
     * MLModel.

     */
    inline const Aws::String& GetMessage() const{ return m_message; }

    /**
     *
A description of the most recent details about evaluating the
     * MLModel.

     */
    inline void SetMessage(const Aws::String& value) { m_messageHasBeenSet = true; m_message = value; }

    /**
     *
A description of the most recent details about evaluating the
     * MLModel.

     */
    inline void SetMessage(Aws::String&& value) { m_messageHasBeenSet = true; m_message = std::move(value); }

    /**
     *
A description of the most recent details about evaluating the
     * MLModel.

     */
    inline void SetMessage(const char* value) { m_messageHasBeenSet = true; m_message.assign(value); }

    /**
     *
A description of the most recent details about evaluating the
     * MLModel.

     */
    inline Evaluation& WithMessage(const Aws::String& value) { SetMessage(value); return *this;}

    /**
     *
A description of the most recent details about evaluating the
     * MLModel.

     */
    inline Evaluation& WithMessage(Aws::String&& value) { SetMessage(std::move(value)); return *this;}

    /**
     *
A description of the most recent details about evaluating the
     * MLModel.

     */
    inline Evaluation& WithMessage(const char* value) { SetMessage(value); return *this;}

    inline long long GetComputeTime() const{ return m_computeTime; }

    inline void SetComputeTime(long long value) { m_computeTimeHasBeenSet = true; m_computeTime = value; }

    inline Evaluation& WithComputeTime(long long value) { SetComputeTime(value); return *this;}

    inline const Aws::Utils::DateTime& GetFinishedAt() const{ return m_finishedAt; }

    inline void SetFinishedAt(const Aws::Utils::DateTime& value) { m_finishedAtHasBeenSet = true; m_finishedAt = value; }

    inline void SetFinishedAt(Aws::Utils::DateTime&& value) { m_finishedAtHasBeenSet = true; m_finishedAt = std::move(value); }

    inline Evaluation& WithFinishedAt(const Aws::Utils::DateTime& value) { SetFinishedAt(value); return *this;}

    inline Evaluation& WithFinishedAt(Aws::Utils::DateTime&& value) { SetFinishedAt(std::move(value)); return *this;}

    inline const Aws::Utils::DateTime& GetStartedAt() const{ return m_startedAt; }

    inline void SetStartedAt(const Aws::Utils::DateTime& value) { m_startedAtHasBeenSet = true; m_startedAt = value; }

    inline void SetStartedAt(Aws::Utils::DateTime&& value) { m_startedAtHasBeenSet = true; m_startedAt = std::move(value); }

    inline Evaluation& WithStartedAt(const Aws::Utils::DateTime& value) { SetStartedAt(value); return *this;}

    inline Evaluation& WithStartedAt(Aws::Utils::DateTime&& value) { SetStartedAt(std::move(value)); return *this;}

  private:
    Aws::String m_evaluationId;
    bool m_evaluationIdHasBeenSet;
    Aws::String m_mLModelId;
    bool m_mLModelIdHasBeenSet;
    Aws::String m_evaluationDataSourceId;
    bool m_evaluationDataSourceIdHasBeenSet;
    Aws::String m_inputDataLocationS3;
    bool m_inputDataLocationS3HasBeenSet;
    Aws::String m_createdByIamUser;
    bool m_createdByIamUserHasBeenSet;
    Aws::Utils::DateTime m_createdAt;
    bool m_createdAtHasBeenSet;
    Aws::Utils::DateTime m_lastUpdatedAt;
    bool m_lastUpdatedAtHasBeenSet;
    Aws::String m_name;
    bool m_nameHasBeenSet;
    EntityStatus m_status;
    bool m_statusHasBeenSet;
    PerformanceMetrics m_performanceMetrics;
    bool m_performanceMetricsHasBeenSet;
    Aws::String m_message;
    bool m_messageHasBeenSet;
    long long m_computeTime;
    bool m_computeTimeHasBeenSet;
    Aws::Utils::DateTime m_finishedAt;
    bool m_finishedAtHasBeenSet;
    Aws::Utils::DateTime m_startedAt;
    bool m_startedAtHasBeenSet;
  };

} // namespace Model
} // namespace MachineLearning
} // namespace Aws


text:
'use strict';

var LoginCtrl = require('../../../../src/js/controller/login/login'),
    Email = require('../../../../src/js/email/email'),
    Account = require('../../../../src/js/email/account'),
    Dialog = require('../../../../src/js/util/dialog'),
    UpdateHandler = require('../../../../src/js/util/update/update-handler'),
    Auth = require('../../../../src/js/service/auth'),
    Keychain = require('../../../../src/js/service/keychain');

describe('Login Controller unit test', function() {
    var scope, location, ctrl,
        emailMock, keychainMock, authMock, accountMock, dialogMock, updateHandlerMock, goToStub,
        emailAddress = 'fred@foo.com';

    beforeEach(function() {
        emailMock = sinon.createStubInstance(Email);
        accountMock = sinon.createStubInstance(Account);
        authMock = sinon.createStubInstance(Auth);
        keychainMock = sinon.createStubInstance(Keychain);
        dialogMock = sinon.createStubInstance(Dialog);
        updateHandlerMock = sinon.createStubInstance(UpdateHandler);

        location = {
            path: function() {}
        };

        authMock.emailAddress = emailAddress;

        angular.module('login-test', ['woServices', 'woEmail', 'woUtil']);
        angular.mock.module('login-test');
        angular.mock.inject(function($rootScope, $controller) {
            scope = $rootScope.$new();
            scope.state = {};
            scope.form = {};

            ctrl = $controller(LoginCtrl, {
                $scope: scope,
                $location: location,
                updateHandler: updateHandlerMock,
                account: accountMock,
                auth: authMock,
                email: emailMock,
                keychain: keychainMock,
                dialog: dialogMock,
                appConfig: {
                    preventAutoStart: true
                }
            });
        });

        scope.goTo = function() {};
        goToStub = sinon.stub(scope, 'goTo');
    });

    afterEach(function() {});

    it('should fail for auth.getEmailAddress', function(done) {
        authMock.init.returns(resolves());
        authMock.getEmailAddress.returns(rejects(new Error()));

        scope.init().then(function() {
            expect(updateHandlerMock.checkForUpdate.calledOnce).to.be.true;
            expect(authMock.init.calledOnce).to.be.true;
            expect(dialogMock.error.calledOnce).to.be.true;
            done();
        });
    });

    it('should fail for auth.init', function(done) {
        authMock.init.returns(rejects(new Error()));
        authMock.getEmailAddress.returns(resolves({
            emailAddress: emailAddress
        }));

        scope.init().then(function() {
            expect(authMock.init.calledOnce).to.be.true;
            expect(accountMock.init.called).to.be.false;
            expect(dialogMock.error.calledOnce).to.be.true;
            done();
        });
    });

    it('should redirect to /add-account', function(done) {
        authMock.init.returns(resolves());
        authMock.getEmailAddress.returns(resolves({}));

        scope.init().then(function() {
            expect(goToStub.withArgs('/add-account').called).to.be.true;
            expect(goToStub.calledOnce).to.be.true;
            done();
        });
    });

    it('should redirect to /login-existing', function(done) {
        authMock.init.returns(resolves());
        authMock.getEmailAddress.returns(resolves({
            emailAddress: emailAddress
        }));
        accountMock.init.returns(resolves({
            publicKey: 'publicKey',
            privateKey: 'privateKey'
        }));
        emailMock.unlock.returns(rejects(new Error()));

        scope.init().then(function() {
            expect(goToStub.withArgs('/login-existing').called).to.be.true;
            expect(goToStub.calledOnce).to.be.true;
            expect(authMock.storeCredentials.called).to.be.false;
            done();
        });
    });

    it('should fail for auth.storeCredentials', function(done) {
        authMock.init.returns(resolves());
        authMock.getEmailAddress.returns(resolves({
            emailAddress: emailAddress
        }));
        accountMock.init.returns(resolves({
            publicKey: 'publicKey',
            privateKey: 'privateKey'
        }));
        emailMock.unlock.returns(resolves());
        authMock.storeCredentials.returns(rejects(new Error()));

        scope.init().then(function() {
            expect(dialogMock.error.calledOnce).to.be.true;
            done();
        });
    });

    it('should redirect to /account', function(done) {
        authMock.init.returns(resolves());
        authMock.getEmailAddress.returns(resolves({
            emailAddress: emailAddress
        }));
        accountMock.init.returns(resolves({
            publicKey: 'publicKey',
            privateKey: 'privateKey'
        }));
        emailMock.unlock.returns(resolves());
        authMock.storeCredentials.returns(resolves());

        scope.init().then(function() {
            expect(goToStub.withArgs('/account').called).to.be.true;
            expect(goToStub.calledOnce).to.be.true;
            done();
        });
    });

    it('should redirect to /login-privatekey-download', function(done) {
        authMock.init.returns(resolves());
        authMock.getEmailAddress.returns(resolves({
            emailAddress: emailAddress
        }));
        accountMock.init.returns(resolves({
            publicKey: 'publicKey'
        }));

        scope.init().then(function() {
            expect(goToStub.withArgs('/login-privatekey-download').called).to.be.true;
            expect(goToStub.calledOnce).to.be.true;
            done();
        });
    });

    it('should redirect to /login-initial', function(done) {
        authMock.init.returns(resolves());
        authMock.getEmailAddress.returns(resolves({
            emailAddress: emailAddress
        }));
        accountMock.init.returns(resolves({}));

        scope.init().then(function() {
            expect(goToStub.withArgs('/login-initial').called).to.be.true;
            expect(goToStub.calledOnce).to.be.true;
            done();
        });
    });

});


text:
module Alf
  module Sql
    class Processor
      class Star < Processor

        def on_select_exp(sexpr)
          if sexpr.from_clause
            sexpr.with_update(:select_list, builder.select_star)
          else
            sexpr
          end
        end

      end # class Star
    end # class Processor
  end # module Sql
end # module Alf


text:
import 'mocha';
import { expect } from 'chai';
import { createPlaidClient } from './clientHelper';
import { PlaidApi, WebhookVerificationKeyGetRequest } from '../dist';
import { TestConstants } from './testConstants';

describe('Webhook Verification', () => {
  let plaidClient: PlaidApi;

  before(async () => {
    plaidClient = createPlaidClient();
  });

  it('get', async () => {
    const request: WebhookVerificationKeyGetRequest = {
      key_id: TestConstants.WEBHOOK_VERIFICATION_KEY_ID,
    };

    const response = await plaidClient.webhookVerificationKeyGet(request);
    expect(response.data).to.be.ok;
    expect(response.data.key).to.be.ok;
    expect(response.data.key.alg).to.be.ok;
    expect(response.data.key.crv).to.be.ok;
    expect(response.data.key.kid).to.be.ok;
    expect(response.data.key.kty).to.be.ok;
    expect(response.data.key.use).to.be.ok;
    expect(response.data.key.x).to.be.ok;
    expect(response.data.key.y).to.be.ok;
  });

  it('get key error', async () => {
    const request: WebhookVerificationKeyGetRequest = {
      key_id: 'invalid key_id',
    };

    try {
      await plaidClient.webhookVerificationKeyGet(request);
    } catch (error) {
      expect(error.response.status).to.equal(400);
      const err = error.response.data;
      expect(err.request_id).to.be.ok;
      expect(err.error_code).to.equal('INVALID_WEBHOOK_VERIFICATION_KEY_ID');
    }
  });
});


text:
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HikingPathFinder.App.UWP")]
[assembly: AssemblyDescription("HikingPathFinder Windows 10 app")]
[assembly: AssemblyConfiguration("")]
[assembly: ComVisible(false)]


text:
var scripts = document.getElementsByTagName("script");
var currentScriptPath = scripts[scripts.length-1].src;
var baseUrl, componentUrl;

for (var i = 0; i < scripts.length; i++) {
	var charIndex = scripts[i].src.indexOf('geogap-pdok-geocoder')
	if (charIndex > 0) {
		baseUrl = currentScriptPath.substring(0, currentScriptPath.lastIndexOf('/') + 1);
		componentUrl = currentScriptPath.substring(0, charIndex);
	}
}

angular.module('geogap.pdokgeocoder', [])

.component('searchbar', {
	bindings: {
		resultLimit: '<',
		crs: '<'
	},
	templateUrl: baseUrl + 'template/searchbar.template.html',
	controller: function ($state, $scope, $element, $sce, GeolocateService) {
		$scope.query = '';

		// ===================== SEARCH FUNCTIONALITY =====================

		this.$onInit = function () {
			if (!this.resultLimit) {
				$scope.resultLimit = 10;
			} else {
				$scope.resultLimit = this.resultLimit;
			}

			if (this.crs ==  'll') {
				$scope.crs = 'll';
			} else if (this.crs == 'rd') {
				$scope.crs = 'rd';
			} else if (!this.crs || (this.crs != 'll' && this.crs != 'rd ')) {
				$scope.crs = 'll';
			}
		};

		$scope.incrementLimit = function() {
			$scope.resultLimit += 5;
		}

		//Autocomplete watch functions
		$scope.$watch('query', function (query){
			if (query.length > 3 && !$scope.selectedLocation) {
				$scope.getResults(query);
			} else {
				$scope.results = [];
				$scope.showSuggestions = false;
				$scope.selectedLocation = false;
			}
		})

		$scope.getResults = function (query) {
			GeolocateService.suggest({
				q: query
			}).then(function(response){
				if (response.response.docs.length > 0) {
					$scope.results = response.response.docs;
					$scope.highlights = response.highlighting;
				} else {
					$scope.showSuggestions = true;
					$scope.suggestions = response.spellcheck.suggestions;
		    }
			});
		};

		$scope.getSuggestion = function(suggestion) {
			$scope.query = suggestion
		};

		$scope.lookupResult = function(data) {
			$scope.query = data.weergavenaam;
			$scope.selectedLocation = true;
			$scope.results = [];

			GeolocateService.lookup({
				id: data.id,
				fl: '*'
			}, $scope.crs).then(function(result) {
				$scope.$emit('newLocation', result, data.type);
			});
		};

		$scope.clearResults = function() {
			$scope.query = '';
			$scope.results = [];
			$scope.$emit('clearResults');
		};

		$scope.getHTML = function(id) {
			return $sce.trustAsHtml($scope.highlights[id].suggest[0]);
		};

		// ========================= TEMPLATE SPECIFIC CSS ==========================

		var searchElement = angular.element(document.getElementById('search-button'));
		searchElement.css('background', 'url(' + baseUrl + 'img/search.png) 0 4px no-repeat #fff');
		searchElement.on('mouseenter',function() {
        searchElement.css('background', 'url(' + baseUrl + 'img/search.png) -24px 4px no-repeat');
    })
    .on('mouseleave',function() {
        searchElement.css('background', 'url(' + baseUrl + 'img/search.png) 0 4px no-repeat #fff');
    });

		var clearElement = angular.element(document.getElementById('clear-button'));
		clearElement.css('background', 'url(' + baseUrl + 'img/clear.png) 0 4px no-repeat #fff');
		clearElement.on('mouseenter',function() {
				clearElement.css('background', 'url(' + baseUrl + 'img/clear.png) -24px 4px no-repeat');
		})
		.on('mouseleave',function() {
				clearElement.css('background', 'url(' + baseUrl + 'img/clear.png) 0 4px no-repeat #fff');
		});

	}
})

.factory('GeolocateService', function($http) {
  var suggestUrl = 'http://geodata.nationaalgeoregister.nl/locatieserver/suggest?'
  var lookupUrl  = 'http://geodata.nationaalgeoregister.nl/locatieserver/lookup?'
  var freeUrl  	 = 'http://geodata.nationaalgeoregister.nl/locatieserver/free?'

  this.suggest = function (params) {
     return $http
    .get(suggestUrl, {params:params})
    .then(function(response) {
      return response.data;
    })
  }

  this.lookup = function (params, crs) {
     return $http
    .get(lookupUrl, {params:params})
    .then(function(result) {
    	var result = result.data.response.docs[0];
    	feature = result
    	feature.type = 'Feature';

			if (crs == 'll') {
				feature.geometry = Terraformer.WKT.parse(result.geometrie_ll);
			}

			if (crs == 'rd') {
				feature.geometry = Terraformer.WKT.parse(result.geometrie_rd);
			}

      return feature;
    })
  }

  this.free = function (params) {
	   return $http
    .get(freeUrl, {params:params})
    .then(function(response) {
      return response.data;
    })
  }

  return this

});


text:
#include "TitleBar.h"
#include "../Core/Theme.h"

Titlebar::Titlebar(QWidget *parent, const int &flag) : MyWidget(parent)
{
    this->parent = parent;

    QWidget *uiWidget;

    if (!(uiWidget = Theme::loadUi("TitleBar.xml", this)))
    {
        throw "Ops! Algo deu errado...\nHouve um erro ao carregar o arquivo \"TitleBar.xml\" do tema atual.";
        return;
    }

    titleIcon = uiWidget->findChild<QLabel *>("windowIcon");
    titleIcon->setPixmap(QPixmap(Global::getQrcPath("icon.png")));

    label = uiWidget->findChild<QLabel *>("windowTitle");
    label->setText(parent->windowTitle());

    buttonMinimize = uiWidget->findChild<QPushButton *>("minimize");
    buttonMinimize->setToolTip("Minimizar");

    buttonMinimizeTray = uiWidget->findChild<QPushButton *>("minimizeTray");
    buttonMinimizeTray->setToolTip("Minimizar para a Bandeja");

    buttonClose = uiWidget->findChild<QPushButton *>("close");
    buttonClose->setToolTip("Fechar");

    if (flag == DIALOG)
    {
        buttonMinimize->hide();
        buttonMinimizeTray->hide();
    }

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(uiWidget);
    layout->setMargin(0);
    layout->setSpacing(0);
    setLayout(layout);

    if (flag == DIALOG)
    {
        connect(buttonClose, SIGNAL(clicked()), parent, SLOT(close()));
    }
    else
    {
        connect(buttonMinimize, SIGNAL(clicked()), parent, SLOT(showMinimized()));
        connect(buttonMinimizeTray, SIGNAL(clicked()), parent, SLOT(hide()));
        connect(buttonClose, SIGNAL(clicked()), this, SLOT(quitApp()));
    }
}

Titlebar::~Titlebar()
{
}

//================================================================================================================
// private
//================================================================================================================

void Titlebar::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
        cursor = mapToParent(event->pos());
}

void Titlebar::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() == Qt::LeftButton)
        parent->move(event->globalPos() - cursor);
}

//================================================================================================================
// private slots
//================================================================================================================

void Titlebar::quitApp()
{
    parent->hide();
    qApp->quit();
}


text:
layout: post
title: "The Week in Robots"
date: 2017-08-19 08:30:00 +0000
tags:
image: https://s3.amazonaws.com/hackedu/2017-08-19-robot.jpg
imagecredits: https://www.flickr.com/photos/krancien/4315987167
---

Racist Robots

AI Programs Are Learning to Exclude Some African-American Voices

Flying Robots

Microsoft Teaches Autonomous Gliders to Make Decisions on the Fly

Microsoft Is Training AI Gliders to Fly Themselves

The Value of Bringing Drones to the Classroom

Robot Parents

Growing Up with Alexa

Robot Doctors

Tiny robots in a mouse’s stomach help heal an ulcer

Robot Artists

How A.I. Is Creating Building Blocks to Reshape Music and Art

Driving Robots

Inside the Self-Driving Bromance of Travis Kalanick and Anthony Levandowski

Judge Says Waymo Can Tell Jurors That Uber Withheld Evidence

Chinese Robots

Seeking Greater Global Power, China Looks to Robots and Microchips

Industrial Robots

This Mobile Robotic Arm Totally Won’t Haunt Your Dreams

Where automation actually occurs

Restaurant Robots

Millennials blamed for death of Chuck E. Cheese’s animatronic band

Robot Cashiers

End of the checkout line: the looming crisis for American cashiers

Robot Maps

An AI Dreamed Up Street Scenes, and They’re Surprisingly Good

Robot Homes

An Amazing Demonstration of the Boston Dynamics SpotMini, A Doglike Robot For Home Use

PR for Robots

AI Is Taking Over the Cloud

Ethics for Robots

Teaching A.I. Systems to Behave Themselves

Robots That Are Coming For Your Job

Falling Robots Are Funny, but That’s How They’ll Learn to Take Your Job

Increasing Minimum Wage Puts More Jobs at Risk of Automation

The robot paradox, continued by Nick Carr

Resisting Robots

Eliminating the Human by David Byrne


text:
'use strict';

class playTime {
	constructor() {
		this.dates;
		this.ranges = {};
	}

	addTime(startDate, endDate) {
		startDate = moment(startDate);
		endDate = moment(endDate);

		var startDateString = startDate.format('YYYY-MM-DD');
		var endDateString = endDate.format('YYYY-MM-DD');

		if (!this.ranges[startDateString]) {
			this.ranges[startDateString] = [];
		}

		if (startDate.isSame(endDate, 'day')) {
			this.ranges[startDateString].push(
				moment.range(startDate, endDate)
			);
		}else{
			this.ranges[startDateString].push(
				moment.range(startDate, startDate.endOf('Day'))
			);

			if (!this.ranges[endDateString]) {
				this.ranges[endDateString] = [];
			}

			this.ranges[endDateString].push(
				moment.range(endDate, endDate.startOf('Day'))
			);
		}

		this.dates = undefined;

	}

	getCompleteTime() {
		var playtimeObject = this.getDates();

		var completeTime = 0;

		Object.keys(playtimeObject).forEach(function (key) {
			if (key !== 'NaN-NaN-NaN') {
				completeTime += playtimeObject[key].time;
			}
		});

		return completeTime;
	}

	getDates() {
		if(this.dates){
			this.dates
		}

		var ranges = this.ranges;
		var dates = {};

		Object.keys(ranges).forEach(function(key){

			var startCurrRange;
			var endCurrRange;

			var newRanges = [];

			var currRanges = ranges[key].sort(function(range, range2){
				return range.toDate()[0] - range2.toDate()[1];
			})

			currRanges.forEach(function(range, index){
				if (!startCurrRange) {
					startCurrRange = range.toDate()[0]
					endCurrRange = range.toDate()[1]
				}else if(endCurrRange >= range.toDate()[0]){
					endCurrRange = (range.toDate()[1] > endCurrRange)?range.toDate()[1]:endCurrRange
				}else{
					newRanges.push([startCurrRange, endCurrRange])
					startCurrRange = range.toDate()[0]
					endCurrRange = range.toDate()[1]
				}

				if(index+1 == currRanges.length){
					newRanges.push([startCurrRange, endCurrRange])
				}
			});

			dates[key] = {};
			dates[key].time = 0;

			newRanges.forEach(function(range, index){
				dates[key].time += moment(range[1]).diff(
					moment(range[0])
				);
			});
		});

		this.dates = dates;

		return dates;
	}
}

playTime.formatTime = function(time){
	if(time == 0){
		return "0 minutes";
	}else if(time <= 1000){
		return time + " milliseconds"
	}else if(time <= 60 * 1000){
		return (time / 1000).toFixed(2) + " seconds"
	}else if(time <= 60*60*1000){
		return (time / (60*1000)).toFixed(2) + " minutes"
	}else if(time <= 24*60*60*1000){
		return (time / (60*60*1000)).toFixed(2) + " hours"
	}else{
		return (time / (24*60*60*1000)).toFixed(2) + " days"
	}
}


text:
package net.tomp2p.examples.ws;

import javax.xml.ws.Endpoint;

import net.tomp2p.examples.ExampleUtils;
import net.tomp2p.p2p.Peer;

public class ExampleWSJSON {
    static Peer master = null;

    public static void main(String[] args) throws Exception {
        try {
            Peer[] peers = ExampleUtils.createAndAttachNodes(100, 4001);
            master = peers[0];
            ExampleUtils.bootstrap(peers);
            exampleJSON(peers);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            master.halt();
        }
    }

    private static void exampleJSON(Peer[] peers) throws InterruptedException {
        Endpoint.publish("http://localhost:1234/tomp2p", new ServiceImpl());
        Thread.sleep(Integer.MAX_VALUE);
    }
}


text:
layout: documentation
---

# StateSeed
`Server` [`Mode Enabled`](/docs/guides/restricted-execution.html) [`Mutates State`](/docs/guides/state.html)

Mutating state directly is not something *ensemblejs* promotes. The `StateSeed` plugin is how you can control the state the start of a game.

Any object you return from this plugin splices into the existing state. We require that you namespace your state. We do this to avoid collisions between framework state, library state and your game state. When creating state the first node is the name of the state. See [this guide](/docs/guides/state.html) for more information.

~~~javascript
module.exports = {
  type: 'StateSeed',
  func: function StateSeed () {
    return {
      theNamespace: {
        object: {
          element: "value1"
        },
        element: "value2"
      }
    };
  }
};
~~~


text:
package org.hippoecm.repository.security.group;

import java.util.HashSet;
import java.util.Set;

import javax.jcr.Node;

import org.hippoecm.repository.api.HippoNodeType;
import org.hippoecm.repository.security.ManagerContext;

/**
 * Dummy group implementation that is used when the provider doesn't support
 * it's own group manager implementation.
 */
public class DummyGroupManager extends AbstractGroupManager {

    public static final String PROVIDER_ID = "<dummyProvider>";

    public DummyGroupManager() {
        providerId = PROVIDER_ID;
    }

    public void initManager(ManagerContext context) {
        initialized = true;
    }

    public Set<String> backendGetMemberships(Node user) {
        return new HashSet<String>(0);
    }

    @Override
    public boolean isExternal() {
        return false;
    }

    public String getNodeType() {
        return HippoNodeType.NT_GROUP;
    }

    public boolean isCaseSensitive() {
        return true;
    }
}


text:
/* global module */
module.exports = function(gulp, $, colortest) {
  return function() {
    'use strict';

    var a11yConfig = require('../../config/a11y/sources');
    var processors = [
      colortest({ method: 'achromatopsia' })
    ];
    var stream = gulp.src(a11yConfig.css.app)
    .pipe($.postcss(processors))
    .pipe($.plumber())
    .pipe(gulp.dest(a11yConfig.css.output + 'achromatopsia'))
    .pipe($.notify({
      onLast: true,
      message: 'Done modifying CSS for achromatopsia -- no color'
    }));

    return stream;
  };
};


text:
package com.lufs.atomikos.repository;

import com.lufs.atomikos.domain.entity.Securities;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * Created by Lucifer.Wu on 2016/8/30.
 */
@Repository
public interface SecuritiesRepository extends JpaRepository<Securities, Long>{
}