text:
using System;
using System.Linq;
using System.Security.Cryptography;

namespace Microsoft.Azure.KeyVault.Cryptography.Algorithms
{
    public class RsaOaep : RsaEncryption
    {
        public const string AlgorithmName = "RSA-OAEP";

        public RsaOaep()
            : base( AlgorithmName )
        {
        }

        public override ICryptoTransform CreateEncryptor( AsymmetricAlgorithm key )
        {
            RSACryptoServiceProvider csp = key as RSACryptoServiceProvider;

            if ( csp == null )
                throw new ArgumentException( "key must be an instance of RSACryptoServiceProvider", "key" );

            return new RsaOaepEncryptor( csp );
        }

        public override ICryptoTransform CreateDecryptor( AsymmetricAlgorithm key )
        {
            RSACryptoServiceProvider csp = key as RSACryptoServiceProvider;

            if ( csp == null )
                throw new ArgumentException( "key must be an instance of RSACryptoServiceProvider", "key" );

            return new RsaOaepDecryptor( csp );
        }

        /// <summary>
        /// RSA 15 Decryptor
        /// </summary>
        /// <remarks>
        /// While this class has a reference to an IDisposable object,
        /// it is not the owner of the object and will not Dispose it.
        /// </remarks>
        class RsaOaepDecryptor : ICryptoTransform
        {
            private readonly RSACryptoServiceProvider _csp;

            internal RsaOaepDecryptor( RSACryptoServiceProvider csp )
            {
                _csp = csp;
            }

            public bool CanReuseTransform
            {
                get { throw new NotImplementedException(); }
            }

            public bool CanTransformMultipleBlocks
            {
                get { throw new NotImplementedException(); }
            }

            public int InputBlockSize
            {
                get { throw new NotImplementedException(); }
            }

            public int OutputBlockSize
            {
                get { throw new NotImplementedException(); }
            }

            public int TransformBlock( byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset )
            {
                throw new NotImplementedException();
            }

            public byte[] TransformFinalBlock( byte[] inputBuffer, int inputOffset, int inputCount )
            {
                byte[] block = inputBuffer.Skip( inputOffset ).Take( inputCount ).ToArray();

                return _csp.Decrypt( block, true );
            }

            public void Dispose()
            {
                // Intentionally empty
            }
        }

        /// <summary>
        /// RSA 15 Encryptor
        /// </summary>
        /// <remarks>
        /// While this class has a reference to an IDisposable object,
        /// it is not the owner of the object and will not Dispose it.
        /// </remarks>
        class RsaOaepEncryptor : ICryptoTransform
        {
            private readonly RSACryptoServiceProvider _csp;

            internal RsaOaepEncryptor( RSACryptoServiceProvider csp )
            {
                _csp = csp;
            }

            public bool CanReuseTransform
            {
                get { throw new NotImplementedException(); }
            }

            public bool CanTransformMultipleBlocks
            {
                get { throw new NotImplementedException(); }
            }

            public int InputBlockSize
            {
                get { throw new NotImplementedException(); }
            }

            public int OutputBlockSize
            {
                get { throw new NotImplementedException(); }
            }

            public int TransformBlock( byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset )
            {
                throw new NotImplementedException();
            }

            public byte[] TransformFinalBlock( byte[] inputBuffer, int inputOffset, int inputCount )
            {
                byte[] block = inputBuffer.Skip( inputOffset ).Take( inputCount ).ToArray();

                return _csp.Encrypt( block , true );
            }

            public void Dispose()
            {
                // Intentionally empty
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.xlcloud.service.manager;

import java.util.List;

import org.xlcloud.service.AccessToken;
import org.xlcloud.service.AccessTokens;
import org.xlcloud.service.ScopeType;

/**
 * Interface for {@link AccessToken} related actions logic.
 *
 * @author Jakub Wachowski, AMG.net
 */
public interface TokensManager {

    /**
     * Returns all tokens of the user that have one of scopes listed in given list.
     * @param userId id of the user
     * @param scopes list of scopes
     * @return
     */
    AccessTokens getAccessTokensForUser(Long userId, List<ScopeType> scopes);

    /**
     * Returns details of the token.
     * @return
     */
    AccessToken getAccessToken(String tokenId);

    /**
     * Revokes the access token with all belonging entitlements (policies).
     * @param tokenId
     */
    void revokeAccessToken(String tokenId);

    /**
     * Revokes all access tokens for specified user (along with entitlements).
     *
     * @param userId
     *            id of the user
     */
    void revokeUserAccessTokens(Long userId);

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Odontotrema subintegrum var. macrosporum Vain.

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<alpha android:duration="@android:integer/config_shortAnimTime" android:fromAlpha="1.0" android:toAlpha="0.0"
  xmlns:android="http://schemas.android.com/apk/res/android" />


text:
package com.google.refine.importing;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;

import com.google.refine.Jsonizable;
import com.google.refine.ProjectManager;
import com.google.refine.ProjectMetadata;
import com.google.refine.model.Project;
import com.google.refine.util.JSONUtilities;

public class ImportingJob implements Jsonizable {
    final public long id;
    final public File dir; // Temporary directory where the data about this job is stored

    private JSONObject config;

    public Project project;
    public ProjectMetadata metadata;

    public long lastTouched;
    public boolean updating;
    public boolean canceled;

    final private Object lock = new Object();

    public ImportingJob(long id, File dir) {
        this.id = id;
        this.dir = dir;

        JSONObject cfg = new JSONObject();
        JSONUtilities.safePut(cfg, "state", "new");
        JSONUtilities.safePut(cfg, "hasData", false);
        this.config = cfg;

        lastTouched = System.currentTimeMillis();

        dir.mkdirs();
    }

    public JSONObject getOrCreateDefaultConfig() {
        return config;
    }

    public void setState(String state) {
        synchronized(config) {
            JSONUtilities.safePut(config, "state", state);
        }
    }

    public void setError(List<Exception> exceptions) {
        synchronized(config) {
            JSONUtilities.safePut(config, "errors",
                    DefaultImportingController.convertErrorsToJsonArray(exceptions));
            setState("error");
        }
    }

    public void setProjectID(long projectID) {
        synchronized (config) {
            JSONUtilities.safePut(config, "projectID", projectID);
        }
    }

    public void setProgress(int percent, String message) {
        synchronized (config) {
            JSONObject progress = JSONUtilities.getObject(config, "progress");
            if (progress == null) {
                progress = new JSONObject();
                JSONUtilities.safePut(config, "progress", progress);
            }
            JSONUtilities.safePut(progress, "message", message);
            JSONUtilities.safePut(progress, "percent", percent);
            JSONUtilities.safePut(progress, "memory", Runtime.getRuntime().totalMemory() / 1000000);
            JSONUtilities.safePut(progress, "maxmemory", Runtime.getRuntime().maxMemory() / 1000000);
        }
    }

    public void setFileSelection(JSONArray fileSelectionArray) {
        synchronized (config) {
            JSONUtilities.safePut(config, "fileSelection", fileSelectionArray);
        }
    }

    public void setRankedFormats(JSONArray rankedFormats) {
        synchronized (config) {
            JSONUtilities.safePut(config, "rankedFormats", rankedFormats);
        }
    }

    public JSONObject getRetrievalRecord() {
        synchronized(config) {
            return JSONUtilities.getObject(config,"retrievalRecord");
        }
    }

    public List<JSONObject> getSelectedFileRecords() {
        List<JSONObject> results = new ArrayList<JSONObject>();

        JSONObject retrievalRecord = JSONUtilities.getObject(config,"retrievalRecord");
        if (retrievalRecord != null) {
            JSONArray fileRecordArray = JSONUtilities.getArray(retrievalRecord, "files");
            if (fileRecordArray != null) {
                JSONArray fileSelectionArray = JSONUtilities.getArray(config,"fileSelection");
                if (fileSelectionArray != null) {
                    for (int i = 0; i < fileSelectionArray.length(); i++) {
                        int index = JSONUtilities.getIntElement(fileSelectionArray, i, -1);
                        if (index >= 0 && index < fileRecordArray.length()) {
                            results.add(JSONUtilities.getObjectElement(fileRecordArray, index));
                        }
                    }
                }
            }
        }
        return results;
    }

    public void touch() {
        lastTouched = System.currentTimeMillis();
    }

    public void prepareNewProject() {
        if (project != null) {
            project.dispose();
        }

        // Make sure all projects have been saved in case we run out of memory
        // or have some other catastrophe on import
        ProjectManager.singleton.save(true);

        project = new Project();
        metadata = new ProjectMetadata();
    }

    public void dispose() {
        if (project != null) {
            project.dispose();
            project = null;
        }
        metadata = null;

        try {
            FileUtils.deleteDirectory(dir);
        } catch (IOException e) {
        }
    }

    public File getRawDataDir() {
        File dir2 = new File(dir, "raw-data");
        dir2.mkdirs();
        return dir2;
    }

    @Override
    public void write(JSONWriter writer, Properties options)
            throws JSONException {

        synchronized(lock) {
            writer.object();
            writer.key("config"); writer.value(config);
            writer.endObject();
        }
    }

}


text:
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="css/bootstrap.min.css" rel="stylesheet">

Popover Example

  Toggle popover
   <button type="button" class="btn btn-default">Back</button>


text:
package sync2

import (
	"sync"
	"sync/atomic"
	"time"
)

type AtomicInt32 int32

func (i *AtomicInt32) Add(n int32) int32 {
	return atomic.AddInt32((*int32)(i), n)
}

func (i *AtomicInt32) Set(n int32) {
	atomic.StoreInt32((*int32)(i), n)
}

func (i *AtomicInt32) Get() int32 {
	return atomic.LoadInt32((*int32)(i))
}

func (i *AtomicInt32) CompareAndSwap(oldval, newval int32) (swapped bool) {
	return atomic.CompareAndSwapInt32((*int32)(i), oldval, newval)
}

type AtomicUint32 uint32

func (i *AtomicUint32) Add(n uint32) uint32 {
	return atomic.AddUint32((*uint32)(i), n)
}

func (i *AtomicUint32) Set(n uint32) {
	atomic.StoreUint32((*uint32)(i), n)
}

func (i *AtomicUint32) Get() uint32 {
	return atomic.LoadUint32((*uint32)(i))
}

func (i *AtomicUint32) CompareAndSwap(oldval, newval uint32) (swapped bool) {
	return atomic.CompareAndSwapUint32((*uint32)(i), oldval, newval)
}

type AtomicInt64 int64

func (i *AtomicInt64) Add(n int64) int64 {
	return atomic.AddInt64((*int64)(i), n)
}

func (i *AtomicInt64) Set(n int64) {
	atomic.StoreInt64((*int64)(i), n)
}

func (i *AtomicInt64) Get() int64 {
	return atomic.LoadInt64((*int64)(i))
}

func (i *AtomicInt64) CompareAndSwap(oldval, newval int64) (swapped bool) {
	return atomic.CompareAndSwapInt64((*int64)(i), oldval, newval)
}

type AtomicUint64 uint64

func (i *AtomicUint64) Add(n uint64) uint64 {
	return atomic.AddUint64((*uint64)(i), n)
}

func (i *AtomicUint64) Set(n uint64) {
	atomic.StoreUint64((*uint64)(i), n)
}

func (i *AtomicUint64) Get() uint64 {
	return atomic.LoadUint64((*uint64)(i))
}

func (i *AtomicUint64) CompareAndSwap(oldval, newval uint64) (swapped bool) {
	return atomic.CompareAndSwapUint64((*uint64)(i), oldval, newval)
}

type AtomicDuration int64

func (d *AtomicDuration) Add(duration time.Duration) time.Duration {
	return time.Duration(atomic.AddInt64((*int64)(d), int64(duration)))
}

func (d *AtomicDuration) Set(duration time.Duration) {
	atomic.StoreInt64((*int64)(d), int64(duration))
}

func (d *AtomicDuration) Get() time.Duration {
	return time.Duration(atomic.LoadInt64((*int64)(d)))
}

func (d *AtomicDuration) CompareAndSwap(oldval, newval time.Duration) (swapped bool) {
	return atomic.CompareAndSwapInt64((*int64)(d), int64(oldval), int64(newval))
}

// AtomicString gives you atomic-style APIs for string, but
// it's only a convenience wrapper that uses a mutex. So, it's
// not as efficient as the rest of the atomic types.
type AtomicString struct {
	mu  sync.Mutex
	str string
}

func (s *AtomicString) Set(str string) {
	s.mu.Lock()
	s.str = str
	s.mu.Unlock()
}

func (s *AtomicString) Get() string {
	s.mu.Lock()
	str := s.str
	s.mu.Unlock()
	return str
}

func (s *AtomicString) CompareAndSwap(oldval, newval string) (swapped bool) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.str == oldval {
		s.str = newval
		return true
	}
	return false
}

type AtomicBool int32

func (b *AtomicBool) Set(v bool) {
	if v {
		atomic.StoreInt32((*int32)(b), 1)
	} else {
		atomic.StoreInt32((*int32)(b), 0)
	}
}

func (b *AtomicBool) Get() bool {
	return atomic.LoadInt32((*int32)(b)) == 1
}


text:
/*
 * JSR 354 JavaFX Binding Example
 */
package net.java.javamoney.javafx.binding;

import net.java.javamoney.javafx.value.ObservableMonetaryValue;

/**
 *
 * @author Werner Keil
 */
public interface MonetaryExpression extends ObservableMonetaryValue {

}


text:
const int InductionVariable::ChangeMagnitudeLimitForLoopCountBasedHoisting = 64 << 10;

InductionVariable::InductionVariable()
#if DBG
    : sym(nullptr)
#endif
{
    Assert(!IsValid());
}

InductionVariable::InductionVariable(StackSym *const sym, const ValueNumber symValueNumber, const int change)
    : sym(sym), symValueNumber(symValueNumber), changeBounds(change, change), isChangeDeterminate(true)
{
    Assert(sym);
    Assert(!sym->IsTypeSpec());
    Assert(IsValid());
}

#if DBG

bool InductionVariable::IsValid() const
{
    return !!sym;
}

#endif

StackSym *InductionVariable::Sym() const
{
    Assert(IsValid());
    return sym;
}

ValueNumber InductionVariable::SymValueNumber() const
{
    Assert(IsChangeDeterminate());
    return symValueNumber;
}

void InductionVariable::SetSymValueNumber(const ValueNumber symValueNumber)
{
    Assert(IsChangeDeterminate());
    this->symValueNumber = symValueNumber;
}

bool InductionVariable::IsChangeDeterminate() const
{
    Assert(IsValid());
    return isChangeDeterminate;
}

void InductionVariable::SetChangeIsIndeterminate()
{
    Assert(IsValid());
    isChangeDeterminate = false;
}

const IntConstantBounds &InductionVariable::ChangeBounds() const
{
    Assert(IsChangeDeterminate());
    return changeBounds;
}

bool InductionVariable::IsChangeUnidirectional() const
{
    return
        ChangeBounds().LowerBound() >= 0 && ChangeBounds().UpperBound() != 0 ||
        ChangeBounds().UpperBound() <= 0 && ChangeBounds().LowerBound() != 0;
}

bool InductionVariable::Add(const int n)
{
    Assert(IsChangeDeterminate());

    if(n == 0)
        return true;

    int newLowerBound;
    if(changeBounds.LowerBound() == IntConstMin)
    {
        if(n >= 0)
        {
            isChangeDeterminate = false;
            return false;
        }
        newLowerBound = IntConstMin;
    }
    else if(changeBounds.LowerBound() == IntConstMax)
    {
        if(n < 0)
        {
            isChangeDeterminate = false;
            return false;
        }
        newLowerBound = IntConstMax;
    }
    else if(Int32Math::Add(changeBounds.LowerBound(), n, &newLowerBound))
        newLowerBound = n < 0 ? IntConstMin : IntConstMax;

    int newUpperBound;
    if(changeBounds.UpperBound() == IntConstMin)
    {
        if(n >= 0)
        {
            isChangeDeterminate = false;
            return false;
        }
        newUpperBound = IntConstMin;
    }
    else if(changeBounds.UpperBound() == IntConstMax)
    {
        if(n < 0)
        {
            isChangeDeterminate = false;
            return false;
        }
        newUpperBound = IntConstMax;
    }
    else if(Int32Math::Add(changeBounds.UpperBound(), n, &newUpperBound))
        newUpperBound = n < 0 ? IntConstMin : IntConstMax;

    changeBounds = IntConstantBounds(newLowerBound, newUpperBound);
    return true;
}

void InductionVariable::ExpandInnerLoopChange()
{
    Assert(IsValid());

    if(!isChangeDeterminate)
        return;

    changeBounds =
        IntConstantBounds(
            changeBounds.LowerBound() < 0 ? IntConstMin : changeBounds.LowerBound(),
            changeBounds.UpperBound() > 0 ? IntConstMax : changeBounds.UpperBound());
}

void InductionVariable::Merge(const InductionVariable &other)
{
    Assert(Sym() == other.Sym());
    // The value number may be different, the caller will give the merged info the appropriate value number

    isChangeDeterminate &= other.isChangeDeterminate;
    if(!isChangeDeterminate)
        return;

    changeBounds =
        IntConstantBounds(
            min(changeBounds.LowerBound(), other.changeBounds.LowerBound()),
            max(changeBounds.UpperBound(), other.changeBounds.UpperBound()));
}


text:
define([
    'collection/contentPages'
], function (ContentPages) {
    'use strict';

    var GenericContentView = Backbone.View.extend({

        lazyImages: [],

        initialize: function () {

            ContentPages.add(this.model);

            this.lazyImages = this.$el.find('img[data-src]');

            if (this.lazyImages.length > 0) {
                this.lazyImages.unveil(200);
            }

            this.listenTo(this.model, 'change:hidden', function (model, hidden) {

                if (hidden) {
                    this.hide();
                } else {
                    this.show();
                }

            });

        },

        show: function () {

            this.$el.show();

            if (this.lazyImages.length > 0) {
                this.lazyImages.trigger('unveil');
            }

        },

        hide: function() {
            this.$el.hide();
        }

    });

    return GenericContentView;
});


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Lime.Protocol.Network;
using Lime.Protocol.Util;

namespace Lime.Protocol.Listeners
{
    public class BufferedChannelListener : IChannelListener, IDisposable
    {
        private readonly Func<Message, CancellationToken, Task<bool>> _messageConsumer;
        private readonly Func<Notification, CancellationToken, Task<bool>> _notificationConsumer;
        private readonly Func<Command, CancellationToken, Task<bool>> _commandConsumer;
        private readonly object _syncRoot;
        private CancellationTokenSource _cts;
        public BufferedChannelListener(
            Func<Message, CancellationToken, Task<bool>> messageConsumer,
            Func<Notification, CancellationToken, Task<bool>> notificationConsumer,
            Func<Command, CancellationToken, Task<bool>> commandConsumer,
            int capacity = 1)
        {
            _messageConsumer = messageConsumer ?? throw new ArgumentNullException(nameof(messageConsumer));
            _notificationConsumer = notificationConsumer ?? throw new ArgumentNullException(nameof(notificationConsumer));
            _commandConsumer = commandConsumer ?? throw new ArgumentNullException(nameof(commandConsumer));
            MessageBuffer = ChannelUtil.CreateForCapacity<Message>(capacity, singleWriter: true, singleReader: true);
            NotificationBuffer = ChannelUtil.CreateForCapacity<Notification>(capacity, singleWriter: true, singleReader: true);
            CommandBuffer = ChannelUtil.CreateForCapacity<Command>(capacity, singleWriter: true, singleReader: true);
            _syncRoot = new object();
        }

        public Channel<Message> MessageBuffer { get; }

        public Channel<Notification> NotificationBuffer { get; }

        public Channel<Command> CommandBuffer { get; }

        public Task<Message> MessageListenerTask { get; private set; }

        public Task<Notification> NotificationListenerTask { get; private set; }

        public Task<Command> CommandListenerTask { get; private set; }

        public void Start(IEstablishedReceiverChannel channel)
        {
            lock (_syncRoot)
            {
                if (_cts != null && !_cts.IsCancellationRequested)
                {
                    throw new InvalidOperationException("The listener is already active");
                }
                _cts = new CancellationTokenSource();

                MessageListenerTask = CreateListenerTask(
                    channel.ReceiveMessageAsync,
                    MessageBuffer,
                    _messageConsumer,
                    _cts.Token);

                NotificationListenerTask = CreateListenerTask(
                    channel.ReceiveNotificationAsync,
                    NotificationBuffer,
                    _notificationConsumer,
                    _cts.Token);

                CommandListenerTask = CreateListenerTask(
                    channel.ReceiveCommandAsync,
                    CommandBuffer,
                    _commandConsumer,
                    _cts.Token);
            }
        }

        public void Stop()
        {
            lock (_syncRoot)
            {
                if (_cts == null || _cts.IsCancellationRequested)
                {
                    throw new InvalidOperationException("The listener is not active");
                }

                _cts.Cancel();
                MessageBuffer.Writer.TryComplete();
                NotificationBuffer.Writer.TryComplete();
                CommandBuffer.Writer.TryComplete();
            }
        }

        private async Task<T> CreateListenerTask<T>(
            Func<CancellationToken, Task<T>> producer,
            Channel<T> channel,
            Func<T, CancellationToken, Task<bool>> consumer,
            CancellationToken cancellationToken)
        {
            using var cts = new CancellationTokenSource();
            using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken);

            var producerToChannelTask = ProducerConsumer.CreateAsync(
                producer,
                async (i, c) =>
                {
                    await channel.Writer.WriteAsync(i, c);
                    return true;
                },
                linkedCts.Token,
                true);
            var channelToConsumerTask = ProducerConsumer.CreateAsync(
                (c) => channel.Reader.ReadAsync(c).AsTask(),
                consumer,
                linkedCts.Token,
                true);

            await Task.WhenAny(producerToChannelTask, channelToConsumerTask);

            // Cancel and awaits the both tasks again
            cts.Cancel();

            var items = await Task.WhenAll(producerToChannelTask, channelToConsumerTask);

            return items.FirstOrDefault(i => i != null);
        }

        /// <summary>
        /// Stops the listener tasks and releases any related resource.
        /// </summary>
        public void Dispose()
        {
            _cts?.CancelAndDispose();
        }
    }
}


text:
package com.koch.ambeth.merge.event;

public interface IEntityMetaDataEvent {
	Class<?>[] getEntityTypes();
}


text: #include "../factored/Selector.h"


text:
[Readme available here](https://github.com/pingyhq/pingy-cli/blob/master/README.md)
====


text:
package water;

import water.api.*;
import static water.util.JCodeGen.toStaticVar;
import static water.util.Utils.contains;
import hex.ConfusionMatrix;
import hex.VarImp;
import javassist.*;
import water.api.Request.API;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.TransfVec;
import water.fvec.Vec;
import water.serial.AutoBufferSerializer;
import water.util.*;
import water.util.Log.Tag.Sys;

import java.util.*;

import org.apache.commons.math3.random.CorrelatedRandomVectorGenerator;

/**
 * A Model models reality (hopefully).
 * A model can be used to 'score' a row, or a collection of rows on any
 * compatible dataset - meaning the row has all the columns with the same names
 * as used to build the mode.
 */
public abstract class Model extends Lockable<Model> {
  static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
  static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.

  /** Dataset key used to *build* the model, for models for which this makes
   *  sense, or null otherwise.  Not all models are built from a dataset (eg
   *  artificial models), or are built from a single dataset (various ensemble
   *  models), so this key has no *mathematical* significance in the model but
   *  is handy during common model-building and for the historical record.  */
  @API(help="Datakey used to *build* the model")
  public final Key _dataKey;

  /** Columns used in the model and are used to match up with scoring data
   *  columns.  The last name is the response column name. */
  @API(help="Column names used to build the model")
  public final String _names[];

  /** Categorical/factor/enum mappings, per column.  Null for non-enum cols.
   *  The last column holds the response col enums.  */
  @API(help="Column names used to build the model")
  public final String _domains[][];

  @API(help = "Relative class distribution factors in original data")
  public final float[] _priorClassDist;

  @API(help = "Relative class distribution factors used for model building")
  protected float[] _modelClassDist;
  // WARNING: be really careful to modify this POJO because
  // modification does not involve update in DKV
  public void setModelClassDistribution(float[] classdist) {
    _modelClassDist = classdist.clone();
  }

  private final UniqueId uniqueId;

  /** The start time in mS since the epoch for model training. */
  public long training_start_time = 0L;

  /** The duration in mS for model training. */
  public long training_duration_in_ms = 0L;

  /** Any warnings thrown during model building. */
  @API(help="warnings")
  public String[]  warnings = new String[0];

  /** Whether or not this model has cross-validated results stored. */
  protected boolean _have_cv_results;

  /** Full constructor from frame: Strips out the Vecs to just the names needed
   *  to match columns later for future datasets.
   */
  public Model( Key selfKey, Key dataKey, Frame fr, float[] priorClassDist ) {
    this(selfKey,dataKey,fr.names(),fr.domains(), priorClassDist, null);
  }

  /** Full constructor */
  public Model( Key selfKey, Key dataKey, String names[], String domains[][], float[] priorClassDist, float[] modelClassDist ) {
    super(selfKey);
    this.uniqueId = new UniqueId(_key);
    if( domains == null ) domains=new String[names.length+1][];
    assert domains.length==names.length;
    assert names.length > 1;
    assert names[names.length-1] != null; // Have a valid response-column name?
    _dataKey = dataKey;
    _names   = names;
    _domains = domains;
    _priorClassDist = priorClassDist;
    _modelClassDist = modelClassDist;
  }

  // Currently only implemented by GLM2, DeepLearning, GBM and DRF:
  public Request2 get_params() { throw new UnsupportedOperationException("get_params() has not yet been implemented in class: " + this.getClass()); }

  // NOTE: this is a local copy of the Job; to get the real state you need to get it from the DKV.
  // Currently only implemented by GLM2, DeepLearning, GBM and DRF:
  public Request2 job() { throw new UnsupportedOperationException("job() has not yet been implemented in class: " + this.getClass()); }

  /** Simple shallow copy constructor to a new Key */
  public Model( Key selfKey, Model m ) { this(selfKey,m._dataKey,m._names,m._domains, m._priorClassDist, m._modelClassDist); }

  public enum ModelCategory {
    Unknown,
    Binomial,
    Multinomial,
    Regression,
    Clustering;
  }

  // TODO: override in KMeansModel once that's rewritten on water.Model
  public ModelCategory getModelCategory() {
    return (isClassifier() ?
            (nclasses() > 2 ? ModelCategory.Multinomial : ModelCategory.Binomial) :
            ModelCategory.Regression);
  }

  /** Remove any Model internal Keys */
  @Override public Futures delete_impl(Futures fs) { return fs; /* None in the default Model */ }
  @Override public String errStr() { return "Model"; }
  public void addWarning(String warning) {
    if(this.warnings == null || this.warnings.length == 0)
      this.warnings = new String[]{warning};
    else {
      this.warnings = Arrays.copyOf(this.warnings,this.warnings.length+1);
      this.warnings[this.warnings.length-1] = warning;
    }
  }

  public UniqueId getUniqueId() {
    return this.uniqueId;
  }

  public void start_training(long training_start_time) {
    Log.info("setting training_start_time to: " + training_start_time + " for Model: " + this._key.toString() + " (" + this.getClass().getSimpleName() + "@" + System.identityHashCode(this) + ")");

    final long t = training_start_time;
    new TAtomic<Model>() {
      @Override public Model atomic(Model m) {
          if (m != null) {
            m.training_start_time = t;
          } return m;
      }
    }.invoke(_key);
    this.training_start_time = training_start_time;
  }
  public void start_training(Model previous) {
    training_start_time = System.currentTimeMillis();
    Log.info("setting training_start_time to: " + training_start_time + " for Model: " + this._key.toString() + " (" + this.getClass().getSimpleName() + "@" + System.identityHashCode(this) + ") [checkpoint case]");
    if (null != previous)
      training_duration_in_ms += previous.training_duration_in_ms;

    final long t = training_start_time;
    final long d = training_duration_in_ms;
    new TAtomic<Model>() {
      @Override public Model atomic(Model m) {
          if (m != null) {
            m.training_start_time = t;
            m.training_duration_in_ms = d;
          } return m;
      }
    }.invoke(_key);
  }
  public void stop_training() {
    training_duration_in_ms += (System.currentTimeMillis() - training_start_time);
    Log.info("setting training_duration_in_ms to: " + training_duration_in_ms + " for Model: " + this._key.toString() + " (" + this.getClass().getSimpleName() + "@" + System.identityHashCode(this) + ")");

    final long d = training_duration_in_ms;
    new TAtomic<Model>() {
      @Override public Model atomic(Model m) {
          if (m != null) {
            m.training_duration_in_ms = d;
          } return m;
      }
    }.invoke(_key);
  }

  public String responseName() { return   _names[  _names.length-1]; }
  public String[] classNames() { return _domains[_domains.length-1]; }
  public boolean isClassifier() { return classNames() != null ; }
  public int nclasses() {
    String cns[] = classNames();
    return cns==null ? 1 : cns.length;
  }
  /** Returns number of input features */
  public int nfeatures() { return _names.length - 1; }

  /** For classifiers, confusion matrix on validation set. */
  public ConfusionMatrix cm() { return null; }
  /** Returns mse for validation set. */
  public double mse() { return Double.NaN; }
  /** Variable importance of individual input features measured by this model. */
  public VarImp varimp() { return null; }

  /** Bulk score for given fr frame.
   * The frame is always adapted to this model.
   *
   * @param fr frame to be scored
   * @return frame holding predicted values
   *
   * @see #score(Frame, boolean)
   */
  public Frame score(Frame fr) {
    return score(fr, true);
  }
  /** Bulk score the frame fr, producing a Frame result; the 1st Vec is the
   *  predicted class, the remaining Vecs are the probability distributions.
   *  For Regression (single-class) models, the 1st and only Vec is the
   *  prediction value.
   *
   *  The flat adapt
   * @param fr frame which should be scored
   * @param adapt a flag enforcing an adaptation of fr to this model. If flag
   *        is false scoring code expect that fr is already adapted.
   * @return a new frame containing a predicted values. For classification it contains a column with
   *         prediction and distribution for all response classes. For regression it contains only
   *         one column with predicted values.
   */
  public final Frame score(Frame fr, boolean adapt) {
    int ridx = fr.find(responseName());
    if (ridx != -1) { // drop the response for scoring!
      fr = new Frame(fr);
      fr.remove(ridx);
    }
    // Adapt the Frame layout - returns adapted frame and frame containing only
    // newly created vectors
    Frame[] adaptFrms = adapt ? adapt(fr,false) : null;
    // Adapted frame containing all columns - mix of original vectors from fr
    // and newly created vectors serving as adaptors
    Frame adaptFrm = adapt ? adaptFrms[0] : fr;
    // Contains only newly created vectors. The frame eases deletion of these vectors.
    Frame onlyAdaptFrm = adapt ? adaptFrms[1] : null;
    // Invoke scoring
    Frame output = scoreImpl(adaptFrm);
    // Be nice to DKV and delete vectors which i created :-)
    if (adapt) onlyAdaptFrm.delete();
    return output;
  }

  /** Score already adapted frame.
   *
   * @param adaptFrm
   * @return
   */
  protected Frame scoreImpl(Frame adaptFrm) {
    int ridx = adaptFrm.find(responseName());
    assert ridx == -1 : "Adapted frame should not contain response in scoring method!";
    assert nfeatures() == adaptFrm.numCols() : "Number of model features " + nfeatures() + " != number of test set columns: " + adaptFrm.numCols();
    assert adaptFrm.vecs().length == _names.length-1 : "Scoring data set contains wrong number of columns: " + adaptFrm.vecs().length  + " instead of " + (_names.length-1);

    // Create a new vector for response
    // If the model produces a classification/enum, copy the domain into the
    // result vector.
    Vec v = adaptFrm.anyVec().makeZero(classNames());
    adaptFrm.add("predict",v);
    if( nclasses() > 1 ) {
      String prefix = "";
      for( int c=0; c<nclasses(); c++ ) // if any class is the same as column name in frame, then prefix all classnames
        if (contains(adaptFrm._names, classNames()[c])) { prefix = "class_"; break; }
      for( int c=0; c<nclasses(); c++ )
        adaptFrm.add(prefix+classNames()[c],adaptFrm.anyVec().makeZero());
    }
    new MRTask2() {
      @Override public void map( Chunk chks[] ) {
        double tmp [] = new double[_names.length-1]; // We do not need the last field representing response
        float preds[] = new float [nclasses()==1?1:nclasses()+1];
        int len = chks[0]._len;
        for( int row=0; row<len; row++ ) {
          float p[] = score0(chks,row,tmp,preds);
          for( int c=0; c<preds.length; c++ )
            chks[_names.length-1+c].set0(row,p[c]);
        }
      }
    }.doAll(adaptFrm);
    // Return just the output columns
    int x=_names.length-1, y=adaptFrm.numCols();
    return adaptFrm.extractFrame(x, y);
  }

  /** Single row scoring, on a compatible Frame.  */
  public final float[] score( Frame fr, boolean exact, int row ) {
    double tmp[] = new double[fr.numCols()];
    for( int i=0; i<tmp.length; i++ )
      tmp[i] = fr.vecs()[i].at(row);
    return score(fr.names(),fr.domains(),exact,tmp);
  }

  /** Single row scoring, on a compatible set of data.  Fairly expensive to adapt. */
  public final float[] score( String names[], String domains[][], boolean exact, double row[] ) {
    return score(adapt(names,domains,exact),row,new float[nclasses()]);
  }

  /** Single row scoring, on a compatible set of data, given an adaption vector */
  public final float[] score( int map[][][], double row[], float[] preds ) {
    /*FIXME final int[][] colMap = map[map.length-1]; // Response column mapping is the last array
    assert colMap.length == _names.length-1 : " "+Arrays.toString(colMap)+" "+Arrays.toString(_names);
    double tmp[] = new double[colMap.length]; // The adapted data
    for( int i=0; i<colMap.length; i++ ) {
      // Column mapping, or NaN for missing columns
      double d = colMap[i]==-1 ? Double.NaN : row[colMap[i]];
      if( map[i] != null ) {    // Enum mapping
        int e = (int)d;
        if( e < 0 || e >= map[i].length ) d = Double.NaN; // User data is out of adapt range
        else {
          e = map[i][e];
          d = e==-1 ? Double.NaN : (double)e;
        }
      }
      tmp[i] = d;
    }
    return score0(tmp,preds);   // The results. */
    return null;
  }

  /** Build an adaption array.  The length is equal to the Model's vector length.
   *  Each inner 2D-array is a
   *  compressed domain map from data domains to model domains - or null for non-enum
   *  columns, or null for identity mappings.  The extra final int[] is the
   *  column mapping itself, mapping from model columns to data columns. or -1
   *  if missing.
   *  If 'exact' is true, will throw if there are:
   *    any columns in the model but not in the input set;
   *    any enums in the data that the model does not understand
   *    any enums returned by the model that the data does not have a mapping for.
   *  If 'exact' is false, these situations will use or return NA's instead.
   */
  private int[][][] adapt( String names[], String domains[][], boolean exact) {
    int maplen = names.length;
    int map[][][] = new int[maplen][][];
    // Make sure all are compatible
    for( int c=0; c<names.length;++c) {
            // Now do domain mapping
      String ms[] = _domains[c];  // Model enum
      String ds[] =  domains[c];  // Data  enum
      if( ms == ds ) { // Domains trivially equal?
      } else if( ms == null ) {
        throw new IllegalArgumentException("Incompatible column: '" + _names[c] + "', expected (trained on) numeric, was passed a categorical");
      } else if( ds == null ) {
        if( exact )
          throw new IllegalArgumentException("Incompatible column: '" + _names[c] + "', expected (trained on) categorical, was passed a numeric");
        throw H2O.unimpl();     // Attempt an asEnum?
      } else if( !Arrays.deepEquals(ms, ds) ) {
        map[c] = getDomainMapping(_names[c], ms, ds, exact);
      } // null mapping is equal to identity mapping
    }
    return map;
  }

  /**
   * Type of missing columns during adaptation between train/test datasets
   * Overload this method for models that have sparse data handling.
   * Otherwise, NaN is used.
   * @return real-valued number (can be NaN)
   */
  protected double missingColumnsType() { return Double.NaN; }

  /** Build an adapted Frame from the given Frame. Useful for efficient bulk
   *  scoring of a new dataset to an existing model.  Same adaption as above,
   *  but expressed as a Frame instead of as an int[][]. The returned Frame
   *  does not have a response column.
   *  It returns a two element array containing an adapted frame and a
   *  frame which contains only vectors which where adapted (the purpose of the
   *  second frame is to delete all adapted vectors with deletion of the
   *  frame). */
  public Frame[] adapt( final Frame fr, boolean exact) {
    return adapt(fr, exact, true);
  }

  public Frame[] adapt( final Frame fr, boolean exact, boolean haveResponse) {
    Frame vfr = new Frame(fr); // To avoid modification of original frame fr
    int n = _names.length;
    if (haveResponse) {
      int ridx = vfr.find(_names[_names.length - 1]);
      if (ridx != -1 && ridx != vfr._names.length - 1) { // Unify frame - put response to the end
        String name = vfr._names[ridx];
        vfr.add(name, vfr.remove(ridx));
      }
      n = ridx == -1 ? _names.length - 1 : _names.length;
    }
    String [] names = Arrays.copyOf(_names, n);
    Frame  [] subVfr;
    // replace missing columns with NaNs (or 0s for DeepLearning with sparse data)
    subVfr = vfr.subframe(names, missingColumnsType());
    vfr = subVfr[0]; // extract only subframe but keep the rest for delete later
    Vec[] frvecs = vfr.vecs();
    boolean[] toEnum = new boolean[frvecs.length];
    if(!exact) for(int i = 0; i < n;++i)
      if(_domains[i] != null && !frvecs[i].isEnum()) {// if model expects domain but input frame does not have domain => switch vector to enum
        frvecs[i] = frvecs[i].toEnum();
        toEnum[i] = true;
      }
    int[][][] map = adapt(names,vfr.domains(),exact);
    assert map.length == names.length; // Be sure that adapt call above do not skip any column
    ArrayList<Vec> avecs = new ArrayList<Vec>(); // adapted vectors
    ArrayList<String> anames = new ArrayList<String>(); // names for adapted vector

    for( int c=0; c<map.length; c++ ) // Iterate over columns
      if(map[c] != null) { // Column needs adaptation
        Vec adaptedVec;
        if (toEnum[c]) { // Vector was flipped to column already, compose transformation
          adaptedVec = TransfVec.compose( (TransfVec) frvecs[c], map[c], vfr.domains()[c], false);
        } else adaptedVec = frvecs[c].makeTransf(map[c], vfr.domains()[c]);
        avecs.add(frvecs[c] = adaptedVec);
        anames.add(names[c]); // Collect right names
      } else if (toEnum[c]) { // Vector was transformed to enum domain, but does not need adaptation we need to record it
        avecs.add(frvecs[c]);
        anames.add(names[c]);
      }
    // Fill trash bin by vectors which need to be deleted later by the caller.
    Frame vecTrash = new Frame(anames.toArray(new String[anames.size()]), avecs.toArray(new Vec[avecs.size()]));
    if (subVfr[1]!=null) vecTrash.add(subVfr[1], true);
    return new Frame[] { new Frame(names,frvecs), vecTrash };
  }

  /** Returns a mapping between values of model domains (modelDom) and given column domain.
   * @see #getDomainMapping(String, String[], String[], boolean) */
  public static int[][] getDomainMapping(String[] modelDom, String[] colDom, boolean exact) {
    return getDomainMapping(null, modelDom, colDom, exact);
  }
  /**
   * Returns a mapping for given column according to given modelDom.
   * In this case, modelDom is
   *
   * @param colName name of column which is mapped, can be null.
   * @param modelDom
   * @param logNonExactMapping
   * @return
   */
  public static int[][] getDomainMapping(String colName, String[] modelDom, String[] colDom, boolean logNonExactMapping) {
    int emap[] = new int[modelDom.length];
    boolean bmap[] = new boolean[modelDom.length];
    HashMap<String,Integer> md = new HashMap<String, Integer>((int) ((colDom.length/0.75f)+1));
    for( int i = 0; i < colDom.length; i++) md.put(colDom[i], i);
    for( int i = 0; i < modelDom.length; i++) {
      Integer I = md.get(modelDom[i]);
      if (I == null && logNonExactMapping)
        Log.warn(Sys.SCORM, "Domain mapping: target domain contains the factor '"+modelDom[i]+"' which DOES NOT appear in input domain " + (colName!=null?"(column: " + colName+")":""));
      if (I!=null) {
        emap[i] = I;
        bmap[i] = true;
      }
    }
    if (logNonExactMapping) { // Inform about additional values in column domain which do not appear in model domain
      for (int i=0; i<colDom.length; i++) {
        boolean found = false;
        for (int j=0; j<emap.length; j++)
          if (emap[j]==i) { found=true; break; }
        if (!found)
          Log.warn(Sys.SCORM, "Domain mapping: target domain DOES NOT contain the factor '"+colDom[i]+"' which appears in input domain "+ (colName!=null?"(column: " + colName+")":""));
      }
    }

    // produce packed values
    int[][] res = Utils.pack(emap, bmap);
    // Sort values in numeric order to support binary search in TransfVec
    Utils.sortWith(res[0], res[1]);
    return res;
  }

  /** Bulk scoring API for one row.  Chunks are all compatible with the model,
   *  and expect the last Chunks are for the final distribution and prediction.
   *  Default method is to just load the data into the tmp array, then call
   *  subclass scoring logic. */
  protected float[] score0( Chunk chks[], int row_in_chunk, double[] tmp, float[] preds ) {
    assert chks.length>=_names.length; // Last chunk is for the response
    for( int i=0; i<_names.length-1; i++ ) // Do not include last value since it can contains a response
      tmp[i] = chks[i].at0(row_in_chunk);
    float[] scored = score0(tmp,preds);
    // Correct probabilities obtained from training on oversampled data back to original distribution
    // C.f. http://gking.harvard.edu/files/0s.pdf Eq.(27)
    if (isClassifier() && _priorClassDist != null && _modelClassDist != null) {
      assert(scored.length == nclasses()+1); //1 label + nclasses probs
      ModelUtils.correctProbabilities(scored, _priorClassDist, _modelClassDist);
      //set label based on corrected probabilities (max value wins, with deterministic tie-breaking)
      scored[0] = ModelUtils.getPrediction(scored, tmp);
    }
    return scored;
  }

  /**
   * Compute the model error for a given test data set
   * For multi-class classification, this is the classification error based on assigning labels for the highest predicted per-class probability.
   * For binary classification, this is the classification error based on assigning labels using the optimal threshold for maximizing the F1 score.
   * For regression, this is the mean squared error (MSE).
   * @param ftest Frame containing test data
   * @param vactual The response column Vec
   * @param fpreds Frame containing ADAPTED (domain labels from train+test data) predicted data (classification: label + per-class probabilities, regression: target)
   * @param hitratio_fpreds Frame containing predicted data (domain labels from test data) (classification: label + per-class probabilities, regression: target)
   * @param label Name for the scored data set to be printed
   * @param printMe Whether to print the scoring results to Log.info
   * @param max_conf_mat_size Largest size of Confusion Matrix (#classes) for it to be printed to Log.info
   * @param cm Confusion Matrix object to populate for multi-class classification (also used for regression)
   * @param auc AUC object to populate for binary classification
   * @param hr HitRatio object to populate for classification
   * @return model error, see description above
   */
  public double calcError(final Frame ftest, final Vec vactual,
                          final Frame fpreds, final Frame hitratio_fpreds,
                          final String label, final boolean printMe,
                          final int max_conf_mat_size, final water.api.ConfusionMatrix cm,
                          final AUC auc,
                          final HitRatio hr)
  {
    StringBuilder sb = new StringBuilder();
    double error = Double.POSITIVE_INFINITY;
    // populate AUC
    if (auc != null) {
      assert(isClassifier());
      assert(nclasses() == 2);
      auc.actual = ftest;
      auc.vactual = vactual;
      auc.predict = fpreds;
      auc.vpredict = fpreds.vecs()[2]; //binary classifier (label, prob0, prob1 (THIS ONE), adaptedlabel)
      auc.invoke();
      auc.toASCII(sb);
      error = auc.data().err(); //using optimal threshold for F1
    }
    // populate CM
    if (cm != null) {
      cm.actual = ftest;
      cm.vactual = vactual;
      cm.predict = fpreds;
      cm.vpredict = fpreds.vecs()[0]; // prediction (either label or regression target)
      cm.invoke();
      if (isClassifier()) {
        if (auc != null) {
          AUCData aucd = auc.data();
          //override the CM with the one computed by AUC (using optimal threshold)
          //Note: must still call invoke above to set the domains etc.
          cm.cm = new long[3][3]; // 1 extra layer for NaNs (not populated here, since AUC skips them)
          cm.cm[0][0] = aucd.cm()[0][0];
          cm.cm[1][0] = aucd.cm()[1][0];
          cm.cm[0][1] = aucd.cm()[0][1];
          cm.cm[1][1] = aucd.cm()[1][1];
          assert(new hex.ConfusionMatrix(cm.cm).err() == aucd.err()); //check consistency with AUC-computed error
        } else {
          error = new hex.ConfusionMatrix(cm.cm).err(); //only set error if AUC didn't already set the error
        }
        if (cm.cm.length <= max_conf_mat_size+1) cm.toASCII(sb);
      } else {
        assert(auc == null);
        error = cm.mse;
        cm.toASCII(sb);
      }
    }
    // populate HitRatio
    if (hr != null) {
      assert(isClassifier());
      hr.actual = ftest;
      hr.vactual = vactual;
      hr.predict = hitratio_fpreds;
      hr.invoke();
      hr.toASCII(sb);
    }
    if (printMe && sb.length() > 0) {
      Log.info("Scoring on " + label + " data:");
      for (String s : sb.toString().split("\n")) Log.info(s);
    }
    return error;
  }

  /** Subclasses implement the scoring logic.  The data is pre-loaded into a
   *  re-used temp array, in the order the model expects.  The predictions are
   *  loaded into the re-used temp array, which is also returned.  */
  protected abstract float[] score0(double data[/*ncols*/], float preds[/*nclasses+1*/]);
  // Version where the user has just ponied-up an array of data to be scored.
  // Data must be in proper order.  Handy for JUnit tests.
  public double score(double [] data){ return Utils.maxIndex(score0(data,new float[nclasses()]));  }

  /** Debug flag to generate benchmar code */
  protected static final boolean GEN_BENCHMARK_CODE = false;

  /** Return a String which is a valid Java program representing a class that
   *  implements the Model.  The Java is of the form:
   *

   *    class UUIDxxxxModel {
   *      public static final String NAMES[] = { ....column names... }
   *      public static final String DOMAINS[][] = { ....domain names... }
   *      // Pass in data in a double[], pre-aligned to the Model's requirements.
   *      // Jam predictions into the preds[] array; preds[0] is reserved for the
   *      // main prediction (class for classifiers or value for regression),
   *      // and remaining columns hold a probability distribution for classifiers.
   *      float[] predict( double data[], float preds[] );
   *      double[] map( HashMap < String,Double > row, double data[] );
   *      // Does the mapping lookup for every row, no allocation
   *      float[] predict( HashMap < String,Double > row, double data[], float preds[] );
   *      // Allocates a double[] for every row
   *      float[] predict( HashMap < String,Double > row, float preds[] );
   *      // Allocates a double[] and a float[] for every row
   *      float[] predict( HashMap < String,Double > row );
   *    }
   *

   */
  public String toJava() { return toJava(new SB()).toString(); }
  public SB toJava( SB sb ) {
    SB fileContextSB = new SB(); // preserve file context
    String modelName = JCodeGen.toJavaId(_key.toString());
    // HEADER
    sb.p("import java.util.Map;").nl();
    sb.p("import water.genmodel.GenUtils.*;").nl().nl();
    sb.p("// AUTOGENERATED BY H2O at ").p(new Date().toString()).nl();
    sb.p("// ").p(H2O.getBuildVersion().toString()).nl();
    sb.p("//").nl();
    sb.p("// Standalone prediction code with sample test data for ").p(this.getClass().getSimpleName()).p(" named ").p(modelName).nl();
    sb.p("//").nl();
    sb.p("// How to download, compile and execute:").nl();
    sb.p("//     mkdir tmpdir").nl();
    sb.p("//     cd tmpdir").nl();
    sb.p("//     curl http:/").p(H2O.SELF.toString()).p("/h2o-model.jar > h2o-model.jar").nl();
    sb.p("//     curl http:/").p(H2O.SELF.toString()).p("/2/").p(this.getClass().getSimpleName()).p("View.java?_modelKey=").pobj(_key).p(" > ").p(modelName).p(".java").nl();
    sb.p("//     javac -cp h2o-model.jar -J-Xmx2g -J-XX:MaxPermSize=128m ").p(modelName).p(".java").nl();
    if (GEN_BENCHMARK_CODE)
    sb.p("//     java -cp h2o-model.jar:. -Xmx2g -XX:MaxPermSize=256m -XX:ReservedCodeCacheSize=256m ").p(modelName).nl();
    sb.p("//").nl();
    sb.p("//     (Note:  Try java argument -XX:+PrintCompilation to show runtime JIT compiler behavior.)").nl();
    sb.nl();
    sb.p("public class ").p(modelName).p(" extends water.genmodel.GeneratedModel {").nl(); // or extends GenerateModel
    toJavaInit(sb, fileContextSB).nl();
    toJavaNAMES(sb);
    toJavaNCLASSES(sb);
    toJavaDOMAINS(sb, fileContextSB);
    toJavaPROB(sb);
    toJavaSuper(sb); //
    toJavaPredict(sb, fileContextSB);
    sb.p("}").nl();
    sb.p(fileContextSB).nl(); // Append file
    return sb;
  }
  // Same thing as toJava, but as a Javassist CtClass
  private CtClass makeCtClass() throws CannotCompileException {
    CtClass clz = ClassPool.getDefault().makeClass(JCodeGen.toJavaId(_key.toString()));
    clz.addField(CtField.make(toJavaNAMES   (new SB()).toString(),clz));
    clz.addField(CtField.make(toJavaNCLASSES(new SB()).toString(),clz));
    toJavaInit(clz);            // Model-specific top-level goodness
    clz.addMethod(CtMethod.make(toJavaPredict(new SB(), new SB()).toString(),clz)); // FIX ME
    return clz;
  }
  /** Generate implementation for super class. */
  protected SB toJavaSuper( SB sb ) {
    sb.nl();
    sb.ii(1);
    sb.i().p("public String[]   getNames() { return NAMES; } ").nl();
    sb.i().p("public String[][] getDomainValues() { return DOMAINS; }").nl();
    return sb;
  }
  private SB toJavaNAMES( SB sb ) { return JCodeGen.toStaticVar(sb, "NAMES", _names, "Names of columns used by model."); }
  private SB toJavaNCLASSES( SB sb ) { return isClassifier() ? JCodeGen.toStaticVar(sb, "NCLASSES", nclasses(), "Number of output classes included in training data response column.") : sb; }
  private SB toJavaDOMAINS( SB sb, SB fileContextSB ) {
    sb.nl();
    sb.ii(1);
    sb.i().p("// Column domains. The last array contains domain of response column.").nl();
    sb.i().p("public static final String[][] DOMAINS = new String[][] {").nl();
    for (int i=0; i<_domains.length; i++) {
      String[] dom = _domains[i];
      String colInfoClazz = "ColInfo_"+i;
      sb.i(1).p("/* ").p(_names[i]).p(" */ ");
      sb.p(colInfoClazz).p(".VALUES");
      if (i!=_domains.length-1) sb.p(',');
      sb.nl();
      fileContextSB.i().p("// The class representing column ").p(_names[i]).nl();
      JCodeGen.toClassWithArray(fileContextSB, null, colInfoClazz, dom);
    }
    return sb.i().p("};").nl();
  }
  private SB toJavaPROB( SB sb) {
    sb.di(1);
    toStaticVar(sb, "PRIOR_CLASS_DISTRIB", _priorClassDist, "Prior class distribution");
    toStaticVar(sb, "MODEL_CLASS_DISTRIB", _modelClassDist, "Class distribution used for model building");
    return sb;
  }
  // Override in subclasses to provide some top-level model-specific goodness
  protected SB toJavaInit(SB sb, SB fileContextSB) { return sb; }
  protected void toJavaInit(CtClass ct) { }
  // Override in subclasses to provide some inside 'predict' call goodness
  // Method returns code which should be appended into generated top level class after
  // predict method.
  protected void toJavaPredictBody(SB bodySb, SB classCtxSb, SB fileCtxSb) {
    throw new IllegalArgumentException("This model type does not support conversion to Java");
  }
  // Wrapper around the main predict call, including the signature and return value
  private SB toJavaPredict(SB ccsb, SB fileCtxSb) { // ccsb = classContext
    ccsb.nl();
    ccsb.p("  // Pass in data in a double[], pre-aligned to the Model's requirements.").nl();
    ccsb.p("  // Jam predictions into the preds[] array; preds[0] is reserved for the").nl();
    ccsb.p("  // main prediction (class for classifiers or value for regression),").nl();
    ccsb.p("  // and remaining columns hold a probability distribution for classifiers.").nl();
    ccsb.p("  public final float[] predict( double[] data, float[] preds) { return predict( data, preds, "+toJavaDefaultMaxIters()+"); }").nl();
    ccsb.p("  public final float[] predict( double[] data, float[] preds, int maxIters ) {").nl();
    SB classCtxSb = new SB();
    toJavaPredictBody(ccsb.ii(1), classCtxSb, fileCtxSb); ccsb.di(1);
    ccsb.p("    return preds;").nl();
    ccsb.p("  }").nl();
    ccsb.p(classCtxSb);
    return ccsb;
  }

  protected String toJavaDefaultMaxIters() { return "-1"; }

  // Convenience method for testing: build Java, convert it to a class &
  // execute it: compare the results of the new class's (JIT'd) scoring with
  // the built-in (interpreted) scoring on this dataset.  Throws if there
  // is any error (typically an AssertionError).
  public void testJavaScoring( Frame fr ) {
    try {
      //System.out.println(toJava());
      Class clz = ClassPool.getDefault().toClass(makeCtClass());
      Object modelo = clz.newInstance();
    }
    catch( CannotCompileException cce ) { throw new Error(cce); }
    catch( InstantiationException cce ) { throw new Error(cce); }
    catch( IllegalAccessException cce ) { throw new Error(cce); }
  }

  /** Generates code which unify preds[1,...NCLASSES] */
  protected void toJavaUnifyPreds(SB bodySb) {
  }
  /** Fill preds[0] based on already filled and unified preds[1,..NCLASSES]. */
  protected void toJavaFillPreds0(SB bodySb) {
    // Pick max index as a prediction
    if (isClassifier()) {
      if (_priorClassDist!=null && _modelClassDist!=null) {
        bodySb.i().p("water.util.ModelUtils.correctProbabilities(preds, PRIOR_CLASS_DISTRIB, MODEL_CLASS_DISTRIB);").nl();
      }
      bodySb.i().p("preds[0] = water.util.ModelUtils.getPrediction(preds,data);").nl();
    } else {
      bodySb.i().p("preds[0] = preds[1];").nl();
    }
  }

  /**
   * Compute the cross validation error from an array of predictions for N folds.
   * Also stores the results in the model for display/query.
   * @param source Full training data
   * @param response Full response
   * @param cv_preds N Frames containing predictions made by N-fold CV runs on disjoint contiguous holdout pieces of the training data
   * @param offsets Starting row numbers for the N CV pieces (length = N+1, first element: 0, last element: #rows)
   */
  public final void scoreCrossValidation(Job.ValidatedJob job, Frame source, Vec response, Frame[] cv_preds, long[] offsets) {
    assert(offsets[0] == 0);
    assert(offsets[offsets.length-1] == source.numRows());

    //Hack to make a frame with the correct dimensions and vector group
    Frame cv_pred = score(source);

    // Stitch together the content of cv_pred from cv_preds
    for (int i=0; i<cv_preds.length; ++i) {
      // stitch probabilities (or regression values)
      for (int c=(isClassifier() ? 1 : 0); c<cv_preds[i].numCols(); ++c) {
        Vec.Writer vw = cv_pred.vec(c).open();
        try {
          for (long r=0; r < cv_preds[i].numRows(); ++r) {
            vw.set(offsets[i] + r, cv_preds[i].vec(c).at(r));
          }
        } finally {
          vw.close();
        }
      }
      if (isClassifier()) {
        // make labels
        float[] probs = new float[cv_preds[i].numCols()];
        Vec.Writer vw = cv_pred.vec(0).open();
        try {
          for (long r = 0; r < cv_preds[i].numRows(); ++r) {
            //probs[0] stays 0, is not used in getPrediction
            for (int c = 1; c < cv_preds[i].numCols(); ++c) {
              probs[c] = (float) cv_preds[i].vec(c).at(r);
            }
            final int label = ModelUtils.getPrediction(probs, (int)r);
            vw.set(offsets[i] + r, label);
          }
        } finally {
          vw.close();
        }
      }
    }

    // Now score the model on the
    try {
      AUC auc = nclasses() == 2 ? new AUC() : null;
      water.api.ConfusionMatrix cm = new water.api.ConfusionMatrix();
      HitRatio hr = isClassifier() ? new HitRatio() : null;
      double cv_error = calcError(source, response, cv_pred, cv_pred, "cross-validated", true, 10, cm, auc, hr);
      setCrossValidationError(job, cv_error, cm, auc == null ? null : auc.data(), hr);
    } finally {
      // cleanup temporary frame wit predictions
      cv_pred.delete();
    }
  }

  protected void setCrossValidationError(Job.ValidatedJob job, double cv_error, water.api.ConfusionMatrix cm, AUCData auc, HitRatio hr) { throw H2O.unimpl(); }

  protected void printCrossValidationModelsHTML(StringBuilder sb) {
    if (job() == null) return;
    Job.ValidatedJob job = (Job.ValidatedJob)job();
    if (job.xval_models != null && job.xval_models.length > 0) {
      sb.append("
Cross Validation Models
");
      sb.append("
");
      sb.append("
Model
");
      for (Key k : job.xval_models) {
        sb.append("
");
        sb.append("" + (UKV.get(k) != null ? Inspector.link(k.toString(), k.toString()) : "Pending") + "	");
        sb.append("
");
      }
      sb.append("
");
    }
  }

  /** Helper type for serialization */
  protected static class ModelAutobufferSerializer extends AutoBufferSerializer<Model> { }

  /** Returns a model serializer into AutoBuffer. */
  public AutoBufferSerializer<Model> getModelSerializer() {
    return new ModelAutobufferSerializer();
  }
}


text:
<link rel="import" href="../../bower_components/google-map/google-map.html">
<link rel="import" href="../../bower_components/paper-material/paper-material.html">

<dom-module id="page-home">

  <template>
    <paper-material elevation="1">

LibertyJS

        Your friendly Philly JavaScript conference.

        Come to LibertyJS for a full day of workshops, talks, and lots of
        JavaScript fun!

        Saturday, June 20th, 2015 at

          Impact Hub Philadelphia

          Follow @liberty_js

    </paper-material>
    <paper-material>
      <google-map fit-to-markers zoom="15">
        <google-map-marker latitude="39.970827" longitude="-75.142762"></google-map-marker>
      </google-map>

    </paper-material>
    <paper-material>

Sponsors

Gold

Silver

Bronze

    </paper-material>
  </template>
</dom-module>


text:
lychee.define('lychee.net.Remote').tags({
	platform: 'nodejs'
}).requires([
	'lychee.data.BitON',
	'lychee.data.JSON',
	'lychee.net.Protocol'
]).includes([
	'lychee.net.Tunnel'
]).supports(function(lychee, global) {

	if (typeof process !== 'undefined') {
		return true;
	}

	return false;

}).exports(function(lychee, global, attachments) {

	var _BitON = lychee.data.BitON;
	var _JSON  = lychee.data.JSON;

	/*
	 * IMPLEMENTATION
	 */

	var Class = function(data) {

		var settings = lychee.extend({}, data);

		this.__socket      = null;
		this.__isConnected = false;

		lychee.net.Tunnel.call(this, settings);

		settings = null;

		/*
		 * INITIALIZATION
		 */

		this.bind('connect', function() {
			this.__isConnected = true;
		}, this);

		this.bind('disconnect', function() {
			this.__isConnected = false;
		}, this);

		this.bind('send', function(blob) {

			if (this.__socket !== null) {
				this.__socket.send(blob);
			}

		}, this);

	};

	Class.prototype = {

		/*
		 * ENTITY API
		 */

		// deserialize: function(blob) {},

		serialize: function() {

			var data = lychee.net.Tunnel.prototype.serialize.call(this);
			data['constructor'] = 'lychee.net.Remote';

			return data;

		},

		/*
		 * CUSTOM API
		 */

		connect: function(socket) {

			if (this.__isConnected === false) {

				var that = this;

				this.__socket = new lychee.net.Protocol(socket, lychee.net.Protocol.TYPE.remote);

				this.__socket.ondata = function(blob) {
					that.receive(blob);
				};

				this.__socket.onclose = function(code) {
					that.__socket = null;
					that.trigger('disconnect', [ code ]);
				};

				if (lychee.debug === true) {
					console.log('lychee.net.Remote: Connected to ' + this.host + ':' + this.port);
				}

				return true;

			}

			return false;

		},

		disconnect: function() {

			if (this.__isConnected === true) {

				if (this.__socket !== null) {
					this.__socket.close();
				}

				return true;

			}

			return false;

		}

	};

	return Class;

});


text:
<?php
	require_once "Mail.php";
	require_once "Mail/mime.php";
	//$from = "John Bragato <john.bragato@gmail.com>";
	//$to = "jbragato <jbragato@yahoo.com>";

	if (isset($_POST['from'])) $from = $_POST['from'];
		else	$from = "john.bragato@gmail.com";

	if (isset($_POST['recipient'])) $recipient = $_POST['recipient'];
		else    $recipient = "(Not entered)";

	if (isset($_POST['subject'])) $subject = $_POST['subject'];
		else    $subject = "(Not entered)";

	if (isset($_POST['body'])) $body = $_POST['body'];
		else	$body = "(Not entered)";

	if (isset($_POST['replyto'])) $replyto = $_POST['replyto'];
		else	$replyto = "john.bragato@gmail.com";

	if (isset($_POST['filehtml'])) $filehtml = $_POST['filehtml'];
		else	$filehtml = "/mnt/Post_Ready/zProd_Server/imageServer7/mail/outbox/compiledPhotoReport.html";

	//$DAYRtmp = "date " . "+%Y-%m-%d-RetouchToDo";
	//$DAYRdo = shell_exec("$DAYRtmp");
	//$DAYR   =   "/mnt/Post_Ready/Daily/" . "$DAYRdo";
	//$filehtmlcount = shell_exec("`find /mnt/Post_Ready/Daily/$DAYR -type f | awk -F'/' '{ print $NF }' | sort | wc -l`");
	//$filehtmlcounttmp = "find " . "$DAYR";
	//$endoffilehtmlcounttmp = "-type " . "f " . "| " . "awk " . "-F'/' " . "'{ " .  "print " . "\$NF " . "}' " . "| " . "sort " . "| " . "wc " . "-l";
	//$filehtmlcount  =   "$filehtmlcounttmp" . "filehtmlcounttmp2";
	//$htmlsubject	=	shell_exec("$filehtmlcount");

	$from = "john.bragato@gmail.com";
	$recipient = "john.bragato@bluefly.com";
	$subject = "Hi!";
	$body = "Ciao,\n\tHow are you?";
	$replyto = "john.bragato@gmail.com";

	// Set up the headers that will be included in the email.
	$headers = array(
	  'To'            => $recipient,
	  'From'          => $from,
	  'Return-Path'   => $from,
	  'Reply-To'      => $replyto,
	  'Subject'       => $subject,
	  'Errors-To'     => '<jbragato@yahoo.com>',
	  'MIME-Version'  => '1.0',
	);

	// Set up parameters for both the HTML and plain text mime parts.
	$textparams = array(
	  'charset'       => 'utf-8',
	  'content_type'  => 'text/plain',
	  'encoding'      => 'quoted/printable',
	);
	$htmlparams = array(
	  'charset'       => 'utf-8',
	  'content_type'  => 'text/html',
	  'encoding'      => 'quoted/printable',
	);

	// Create the email itself. The content is blank for now.
	$email = new Mail_mimePart('', array('content_type' => 'multipart/alternative'));

	// Read in the Html Email File
	$htmlbody	=	shell_exec("cat " . "$filehtml");
	$textbody	=	shell_exec("cat " . "$filehtml");

	// Add the text and HTML versions as parts within the main email.
	$textmime = $email->addSubPart($textbody, $textparams);
	$htmlmime = $email->addSubPart($htmlbody, $htmlparams);

	// Get back the body and headers from the MIME object. Merge the headers with
	// the ones we defined earlier.
	$final = $email->encode();
	$final['headers'] = array_merge($final['headers'], $headers);

	// Perform the actual send.
	$smtp_params = array();
	$smtp_params['host'] = 'ssl://smtp.gmail.com';
	$smtp_params['port'] = '465';
	$smtp_params['auth'] = true;
	$smtp_params['username'] = 'john.bragato';
	$smtp_params['password'] = 'yankee17';
	$smtp_params['persist'] = true;

	$mail =& Mail::factory('smtp', $smtp_params);
	$status = $mail->send($recipient, $final['headers'], $final['body']);
	echo $status;
?>


text:
define(
   ({
    _widgetLabel: "Attribuuttabel",
    ok: "OK",
    cancel: "Annuleren",
    unsupportQueryWarning: "De laag moet querybewerking ondersteunen voor weergave in de widget Attribuuttabel. Zorg ervoor dat de querybewerking in de service aan is.",
    exportMessage: "Gegevens exporteren naar CSV-bestand?",
    exportFiles: "Exporteren naar CSV",
    exportSelected: "Selectie naar CSV exporteren",
    exportAll: "Alles naar CSV exporteren",
    options: "Opties",
    zoomto: "Zoomen naar",
    highlight: "Grafische elementen markeren",
    selectAll: "Gegevens op alle pagina´s selecteren",
    selectPage: "Gegevens op huidige pagina selecteren",
    clearSelection: "Selectie wissen",
    filter: "Filter",
    setFilterTip: "Stel het filter correct in.",
    noFilterTip: "Zonder filterexpressie zal deze querytaak alle functies in de opgegeven gegevensbron weergeven.",
    filterByExtent: "Filteren op kaartextent",
    showSelectedRecords: "Geselecteerde records weergeven",
    showAllRecords: "Alle records weergeven",
    showRelatedRecords: "Gerelateerde records weergeven",
    noRelatedRecords: "Geen verwante records gevonden",
    refresh: "Vernieuwen",
    features: "objecten",
    selected: "geselecteerd",
    transparent: "Transparante modus",
    indicate: "Selectie zoeken",
    columns: "Kolommen weergeven/verbergen",
    selectionSymbol: "Selectiesymbool",
    closeMessage: "Tabel verbergen (opnieuw uitvouwen vanaf de onderkant)",
    dataNotAvailable: "Gegevens niet beschikbaar!<br>Klik op de knop [Vernieuwen] om het nog eens te proberen.",
    openTableTip: "Attributentabel openen",
    closeTableTip: "Attributentabel verbergen"
  })
);


text:
package com.heliosapm.streams.metrics.processors.impl;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.kafka.streams.processor.ProcessorContext;
import org.cliffc.high_scale_lib.NonBlockingHashMap;
import org.springframework.jmx.export.annotation.ManagedAttribute;

import com.heliosapm.streams.metrics.StreamedMetric;
import com.heliosapm.streams.metrics.ValueType;
import com.heliosapm.streams.metrics.processors.AbstractStreamedMetricProcessor;
import com.heliosapm.streams.metrics.processors.TimestampedMetricKey;
import com.heliosapm.utils.tuples.NVP;

/**
	 *
Title: StreamedMetricMeter

	 *
Description: A metered aggregator counting instances of metrics submitted through here with the specified aggregation window

	 * @author Whitehead (nwhitehead AT heliosdev DOT org)
	 *
com.heliosapm.streams.metrics.processors.impl.StreamedMetricMeter

	 */
//	@ManagedResource
//	@Configurable
	public class StreamedMetricMeter extends AbstractStreamedMetricProcessor<String, StreamedMetric> {
		/** The aggregation period of this meter in seconds */
		protected final int aggregationPeriod;
		/** The timeout period in seconds after which an idle TimestampedMetricKey will be removed from the store */
		protected final int idleTimeout;
		/** Period accumulator, replaces metricTimestampStore */
		protected final NonBlockingHashMap<String, TimestampedMetricKey> periodAccumulator = new NonBlockingHashMap<String, TimestampedMetricKey>(1024);

		/**
		 * Creates a new StreamedMetricMeter
		 * @param aggregationPeriod The aggregation period of this meter in seconds.
		 * @param period The punctuation period in ms.
		 * @param maxForwards The maximum number of uncommited forwards
		 * @param topicSink The topic sink for this processor
		 * @param sources The topic sources for this processor
		 * @param idleTimeout the idle timeout period in secs.
		 */
		protected StreamedMetricMeter(final int aggregationPeriod, final long period, final int maxForwards, final String topicSink, final String[] sources, final int idleTimeout) {
			super(ValueType.METER, period, maxForwards, topicSink, sources);
			this.aggregationPeriod = aggregationPeriod;
			this.idleTimeout = idleTimeout;
			log.info("Created Instance [" + System.identityHashCode(this) + "]");
		}

		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.streams.metrics.processors.AbstractStreamedMetricProcessor#init(org.apache.kafka.streams.processor.ProcessorContext)
		 */
		@Override
		public void init(final ProcessorContext context) {
			super.init(context);
			log.info("Set context on Instance [" + System.identityHashCode(this) + "]: {}", context);

		}

		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.streams.metrics.processors.AbstractStreamedMetricProcessor#doProcess(java.lang.Object, java.lang.Object)
		 */
		@Override
		protected boolean doProcess(final String key, final StreamedMetric sm) {
			final String mkey = sm.metricKey();
			TimestampedMetricKey tmk = periodAccumulator.putIfAbsent(mkey, TimestampedMetricKey.PLACEHOLDER);
			if(tmk==null || tmk==TimestampedMetricKey.PLACEHOLDER) {
				tmk = new TimestampedMetricKey(TimeUnit.MILLISECONDS.toSeconds(sm.getTimestamp()), sm.forValue(1L).getValueAsLong(), sm.metricKey(), aggregationPeriod);
				periodAccumulator.replace(mkey, tmk);
				log.debug("New MTS: [{}]", tmk);
			} else {
				tmk.increment(sm.forValue(1L).getValueAsLong());
				// if is same period, we just add the count (done internally)
				// otherwise we forward the count for the prior window and start a new one
//				if(!tmk.isSameAggPeriodAs(sm.getTimestamp(), sm.forValue(1L).getValueAsLong())) {
//					final long total = tmk.getCount();
//					final NVP<Long, Double> timeRate = tmk.reset(sm.getTimestamp(), sm.forValue(1L).getValueAsLong());
//					final StreamedMetric f = StreamedMetric.fromKey(TimeUnit.SECONDS.toMillis(timeRate.getKey()), tmk.getMetricKey(), timeRate.getValue());
//					log.info("Forwarding Batch: ts:[{}], key:[{}], total:[{}], tps:[{}]", new Date(f.getTimestamp()), tmk.getMetricKey(), total, timeRate.getValue());
//					forward(f.metricKey(), f);
//				}
			}
//			commit();
			return true;
		}

		/**
		 * {@inheritDoc}
		 * @see com.heliosapm.streams.metrics.processors.AbstractStreamedMetricProcessor#punctuate(long)
		 */
		@Override
		public void punctuate(final long timestamp) {
			log.info("-----------Punctuate");
			for(Map.Entry<String, TimestampedMetricKey> entry: periodAccumulator.entrySet()) {
				final String metricKey = entry.getKey();
				final TimestampedMetricKey tmk = entry.getValue();
				final NVP<Long, Double> nvp = tmk.punctuate(timestamp);
				final StreamedMetric f;
				if(nvp!=null) {
					f = StreamedMetric.fromKey(TimeUnit.SECONDS.toMillis(nvp.getKey()), tmk.getMetricKey(), nvp.getValue());
					log.info("Forwarding Current Batch: key:[{}], tps:[{}]", tmk.getMetricKey(), nvp.getValue());
				} else {
					if(tmk.isExpired(timestamp, idleTimeout)) {
						f = StreamedMetric.fromKey(timestamp, tmk.getMetricKey(), 0D);
						log.info("Forwarding Stale Batch: key:[{}], tps:[0.0]", tmk.getMetricKey());
					} else {
						if(tmk.isIdle(timestamp, idleTimeout)) {
							log.info("Purging Idle Batch: [{}]", metricKey);
							periodAccumulator.remove(metricKey);
						}
						f = null;
					}
				}
				if(f!=null) forward(f.getMetricName(), f);
			}
			commit();
		}

		/**
		 * Returns the number of metrics in the period accumulator
		 * @return the number of metrics in the period accumulator
		 */
		@ManagedAttribute(description="The number of metrics in the period accumulator")
		public int getAccumulatorSize() {
			return periodAccumulator.size();
		}

		/**
		 * Returns the length of the time in seconds window within which incoming metrics will be aggregated and forwarded
		 * @return the length of the time in seconds window within which incoming metrics will be aggregated and forwarded
		 */
		@ManagedAttribute(description="The length of the time in seconds window within which incoming metrics will be aggregated and forwarded")
		public int getAggregationPeriod() {
			return aggregationPeriod;
		}

		/**
		 * Returns the timeout period in seconds after which an idle TimestampedMetricKey will be removed from the store
		 * @return the timeout period in seconds after which an idle TimestampedMetricKey will be removed from the store
		 */
		@ManagedAttribute(description="The timeout period in seconds after which an idle TimestampedMetricKey will be removed from the store")
		public int getIdleTimeout() {
			return idleTimeout;
		}
	}


text:
Introduction
============

UpCloo framework is based on ZF2 components and in particular:

 * TreeRouteStack (Router)
 * EventManager
 * ServiceManager

Renderers
---------

You have to define "renderers" (who render your data). The framework
provides two default renderers that are:

 * UpCloo\\Renderer\\Json
 * UpCloo\\Renderer\\Jsonp

Events
------

The framework flow is event driven and the execution depends in
your actions. In a valid request you reach this events list

 * begin
 * route
 * pre.fetch
 * execute
 * renderer
 * finish

The default flow can change on errors, redirections and exceptions,
for example if a route is missing the "404" event is thrown and the
flow is like this:

 * begin
 * route
 * 404
 * finish

You have to attach a listener on the "404" event in order to handle this error
situation.

Services
--------

The `ServiceManager` is responsible to provide objects to your application and
is widly used into the App framework in order to select the right controller
and renderer.

Configuration
-------------

The framework uses your configuration in order to bootstrap and run.


text:
from google.appengine.datastore import datastore_query
from google.appengine.ext import ndb

def fetch_page(query, batch_size, cursor_str, **kwargs):
  """Fetches a page from a query.

  Arguments:
    query: ndb.Query.
    batch_size: Maximum number of items to return.
    cursor_str: query-dependent string encoded cursor to continue a previous
        search.

  Returns:
  - items
  - str encoded cursor if relevant or None.
  """
  assert isinstance(query, ndb.Query), query
  if not 0 < batch_size <= 1000 or not isinstance(batch_size, int):
    raise ValueError('batch_size must be between 1 and 1000, got %r' %
                     batch_size)
  if cursor_str:
    if not isinstance(cursor_str, basestring):
      raise ValueError('cursor must be between valid string, got %r' %
                       cursor_str)
    cursor = datastore_query.Cursor(urlsafe=cursor_str)
  else:
    cursor = None
  items, cursor, more = query.fetch_page(
      batch_size, start_cursor=cursor, **kwargs)
  if not more:
    return items, None
  return items, cursor.urlsafe()


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Substrate.Entities
{
    using Substrate.Nbt;

    public class EntitySquid : EntityMob
    {
        public static readonly SchemaNodeCompound SquidSchema = MobSchema.MergeInto(new SchemaNodeCompound("")
        {
            new SchemaNodeString("id", TypeId),
        });

        public static new string TypeId
        {
            get { return "Squid"; }
        }

        protected EntitySquid (string id)
            : base(id)
        {
        }

        public EntitySquid ()
            : this(TypeId)
        {
        }

        public EntitySquid (TypedEntity e)
            : base(e)
        {
        }

        #region INBTObject<Entity> Members

        public override bool ValidateTree (TagNode tree)
        {
            return new NbtVerifier(tree, SquidSchema).Verify();
        }

        #endregion

        #region ICopyable<Entity> Members

        public override TypedEntity Copy ()
        {
            return new EntitySquid(this);
        }

        #endregion
    }
}


text:
import Renderer from "./Renderer";
import Editor from "./Editor";
export interface SankeyDataType {
  columns: {
    name: string;
    friendly_name: string;
    type: "integer";
  }[];

  rows: {
    value: number;
    [name: string]: number | string | null;
  }[];
}

export default {
  type: "SANKEY",
  name: "Sankey",
  getOptions: (options: {}) => ({
    ...options,
  }),
  Renderer,
  Editor,

  defaultRows: 7,
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
    <type>org.netbeans.modules.web.project</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/web-project/3">
            <name>AUTTC_Website</name>
            <minimum-ant-version>1.6.5</minimum-ant-version>
            <web-module-libraries>
                <library dirs="200">
                    <file>${file.reference.tomcat-dbcp.jar}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${file.reference.commons-fileupload-1.3.2.jar}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${file.reference.commons-io-2.5.jar}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${libs.MySQLDriver.classpath}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
                <library dirs="200">
                    <file>${libs.jstl.classpath}</file>
                    <path-in-war>WEB-INF/lib</path-in-war>
                </library>
            </web-module-libraries>
            <web-module-additional-libraries/>
            <source-roots>
                <root id="src.dir"/>
            </source-roots>
            <test-roots>
                <root id="test.src.dir"/>
            </test-roots>
        </data>
    </configuration>
</project>


text:
layout:     post
title:      Гугл Мап Апи
date:       2015-10-19
summary: 	Для проекта понадобилось отображать пользовательские маршруты на карте
categories: google-map
---

Для проекта понадобилось отображать пользовательские маршруты на карте. То есть пользователь должен уметь:

- Ввести название города, населенного пункта или какого-то географического объекта
- Должны найтись координаты этого объекта
- Возможность строить маршрут на карте
- Расставлять фотографии на карте по встроенным координатам

Координаты из фотографии

https://blueimp.github.io/JavaScript-Load-Image/

Пример
![](/content/images/2015/10/75c2290a5e5820e07867fcc3bab544a2.png)

Вон сами координаты: GPSLatitude, GPSLongtitude

Поиск координат по названиям географических объектов:

Можно поиграться с веб-сервисом с помощью параметров ссылки

[GoogleMap](http://maps.google.com/maps/api/geocode/json?address=%D0%92%D0%BE%D1%80%D0%BE%D0%BD%D0%B5%D0%B6+%D0%9B%D1%8E%D0%B7%D1%8E%D0%BA%D0%BE%D0%B2%D0%B0+63)

Расставлять на карте точки с "кастомным маркером" и соединить их маршрутом:

Примерное решение описал, для себя, поэтому оно просто 100% должно быть не оптимальным и можно сделать лучше.


text:
package com.aspose.barcode.cloud.client.examples.managingRecognition.cloudStorage;

import java.nio.file.Path;

import com.aspose.barcode.api.BarcodeApi;
import com.aspose.barcode.cloud.client.examples.Configuration;
import com.aspose.barcode.cloud.client.examples.Utils;
import com.aspose.barcode.model.Barcode;
import com.aspose.barcode.model.BarcodeResponseList;
import com.aspose.storage.api.StorageApi;

/**
 * This sample code allows you to read barcode from specific region of image on
 * the Aspose Cloud Storage using Aspose BarCode Cloud API.
 *
 */
public class ReadBarcodeFromSpecificRegionOfImage {

	public static void main(String[] args) {
		//ExStart: ReadBarcodeFromSpecificRegionOfImage

		// ExStart:1

		try {

			// Instantiate Aspose.Storage Cloud API SDK
			StorageApi storageApi = new StorageApi(Configuration.apiKey, Configuration.appSID, true);

			// Instantiate Aspose.BarCode Cloud API SDK
			BarcodeApi barcodeApi = new BarcodeApi(Configuration.apiKey, Configuration.appSID, true);

			// set input file name
			String name = "sample-barcode.jpeg";

			//The barcode type.
			//If this parameter is empty, autodetection of all supported types is used
			String type = "";

			//Sets mode for checksum validation during recognition
			String checksumValidation = "On";

			//Sets if FNC symbol stripping should be performed.
			Boolean stripFnc = Boolean.TRUE;

			//Sets recognition of rotated barcode
			Integer rotationAngle = 0;

			//Sets exact number of barcodes to recognize
			Integer barcodesCount = 0;

			//Set recognition of barcode inside specified Rectangle region
			Integer rectX = 10;
			Integer rectY = 10;
			Integer rectWidth = 200;
			Integer rectHeight = 200;

			//Set 3rd party cloud storage server (if any)
			String storage = "";

			// Set folder location at cloud storage
			String folder = "";

			 Path inputFile = Utils.getPath(ReadBarcodeFromSpecificRegionOfImage.class, name);

			// upload files to aspose cloud storage
			storageApi.PutCreate(name, "", "",inputFile.toFile());

			// invoke Aspose.BarCode Cloud SDK API to read barcode with specific
			// region of image
			BarcodeResponseList apiResponse = barcodeApi.GetBarcodeRecognize(
					name, type, checksumValidation, stripFnc, rotationAngle,
					barcodesCount, rectX, rectY, rectWidth, rectHeight,
					storage, folder);

			if (apiResponse != null && apiResponse.getStatus().equals("OK")) {

				for (Barcode barcode : apiResponse.getBarcodes()) {
					System.out.println("Codetext: " + barcode.getBarcodeValue()
							+ "\nType: " + barcode.getBarcodeType());
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		//ExEnd: ReadBarcodeFromSpecificRegionOfImage
	}

}


text:
namespace bgslibrary
{
  namespace algorithms
  {
    namespace lb
    {
      class BGModel
      {
      public:

        BGModel(int width, int height);
        virtual ~BGModel();

        void InitModel(IplImage* image);
        void UpdateModel(IplImage* image);

        virtual void setBGModelParameter(int id, int value) {};

        virtual IplImage* GetSrc();
        virtual IplImage* GetFG();
        virtual IplImage* GetBG();

      protected:

        IplImage* m_SrcImage;
        IplImage* m_BGImage;
        IplImage* m_FGImage;

        const unsigned int m_width;
        const unsigned int m_height;

        virtual void Init() = 0;
        virtual void Update() = 0;
      };
    }
  }
}


text:
#ifndef __IOPINCTRL_H__
#define __IOPINCTRL_H__

#include <stdint.h>
#include "LPC11Uxx.h"

/**
 * @brief	Set gpio pin direction
 *
 * 	change pin direction only without changing any other settings
 * 	for fast switching between In & Out
 *
 * @Param 	PortNo	: Port number
 * 			PinNo  	: Pin number
 * 			Dir     : I/O direction
 */

static inline __attribute__((always_inline)) void IOPinSetDir(int PortNo, int PinNo, IOPINDIR Dir) {
	if (Dir == IOPINDIR_OUTPUT)
		LPC_GPIO->DIR[PortNo] |= 1 << PinNo;
	else if (Dir == IOPINDIR_INPUT)
		LPC_GPIO->DIR[PortNo] &= ~(1 << PinNo);
}

/**
 * @brief	Read pin state
 *
 * @Param 	PortNo	: Port number
 * 			PinNo  	: Pin number
 *
 * @return	Pin state 1 or 0
 */
static inline __attribute__((always_inline)) int IOPinRead(int PortNo, int PinNo) {
	return ((LPC_GPIO->PIN[PortNo] >> PinNo ) & 1);
}

/**
 * @brief	Set pin to high (1 logic)
 *
 * @Param 	PortNo	: Port number
 * 			PinNo  	: Pin number
 */
static inline __attribute__((always_inline)) void IOPinSet(int PortNo, int PinNo) {
	LPC_GPIO->SET[PortNo] = (1 << PinNo);
}

/**
 * @brief	Set pin to low (0 logic)
 *
 * @Param 	PortNo	: Port number
 * 			PinNo  	: Pin number
 */
static inline __attribute__((always_inline)) void IOPinClear(int PortNo, int PinNo) {
	LPC_GPIO->CLR[PortNo] = (1 << PinNo);
}

/**
 * @brief	Toggle pin state (invert pin state)
 *
 * @Param 	PortNo	: Port number
 * 			PinNo  	: Pin number
 */
static inline __attribute__((always_inline)) void IOPinToggle(int PortNo, int PinNo) {
	LPC_GPIO->NOT[PortNo] = (1 << PinNo);
}

/**
 * @brief	Read all pins on port
 *
 * @Param 	PortNo	: Port number
 *
 * @return	Bit field pin states
 */
static inline __attribute__((always_inline)) uint32_t IOPinReadPort(int PortNo) {
	return LPC_GPIO->PIN[PortNo];
}

/**
 * @brief	Write state to all pin on port
 *
 * @Param 	PortNo	: Port number
 * 			Data	: Bit field state of all pins on port
 */
static inline __attribute__((always_inline)) void IOPinWritePort(int PortNo, uint32_t Data) {
	LPC_GPIO->W[PortNo] = Data;
}

static inline __attribute__((always_inline)) void IOPinWrite8Port(int PortNo, uint8_t Data) {
	LPC_GPIO->B[PortNo] = Data;
}

static inline __attribute__((always_inline)) void IOPinWrite16Port(int PortNo, uint16_t Data)
{
	LPC_GPIO->B[PortNo] = Data & 0xFF;
	LPC_GPIO->B[PortNo + 1] = (Data >> 8) & 0xFF;
}

static inline __attribute__((always_inline)) void IOPinWrite32Port(int PortNo, uint32_t Data)
{
	LPC_GPIO->W[PortNo] = Data;
}

#endif	// __IOPINCTRL_H__