text:
/***
* Inferno Engine v4 2015-2017
* Written by Tomasz "Rex Dex" Jonarski
*
* [#filter: tcp #]
***/

#include "build.h"
#include "selector.h"

#include "tcpServer.h"
#include "tcpSocket.h"

#include "base/system/include/thread.h"
#include "base/containers/include/inplaceArray.h"

namespace base
{
    namespace socket
    {
        namespace tcp
        {
            //--

            IServerHandler::~IServerHandler()
            {}

            //--

            void ConnectionStats::print(IFormatStream& f) const
            {
                const auto aliveTime = m_startTime.timeTillNow().toSeconds();

                if (m_totalDataSent)
                    f.appendf("  Data sent: {} ({}/s)\n", MemSize(m_totalDataSent), MemSize((Double)m_totalDataSent / aliveTime));
                if (m_totalDataReceived)
                    f.appendf("  Data recv: {} ({}/s)",  MemSize(m_totalDataReceived), MemSize((Double)m_totalDataReceived / aliveTime));
            }

            //--

            Server::Server(IServerHandler* handler, const ServerConfig& config /*= ServerConfig()*/)
                : m_handler(handler)
                , m_nextConnectionID(1)
                , m_listeningFlag(0)
                , m_initFlag(0)
                , m_config(config)
            {
                m_receciveBuffer.resize(config.m_recvBufferSize);
            }

            Server::~Server()
            {
                close();
            }

            bool Server::init(const Address& listenAddress)
            {
                // lock
                const auto flag = m_initFlag.exchange(1);
                if (flag != 0)
                {
                    TRACE_ERROR("TCP Server: server is already running");
                    return true;
                }

                // open socket
                if (!m_socket.listen(listenAddress, &m_address))
                {
                    TRACE_ERROR("TCP Server: failed to create socket at address '{}'", listenAddress);
                    m_initFlag.exchange(0);
                    return false;
                }

                // inform about assigned port
                if (listenAddress.getPort() == 0)
                {
                    TRACE_INFO("TCP Server: Auto assigned socket '{}'", m_address.getPort());
                }

                // try to set socket in non-blocking mode
                if (!m_socket.setBlocking(false))
                {
                    TRACE_ERROR("TCP Server: failed to set socket into non blocking mode");
                    m_initFlag.exchange(0);
                    m_socket.close();
                    return false;
                }

                // Try to set socket buffer limits
                /*if (!m_socket->setBufferSize(Constants::MAX_DATAGRAM_SIZE, Constants::MAX_DATAGRAM_SIZE))
                {
                    TRACE_ERROR("TCP Server error: failed to check buffer sizes on socket");
                    m_socket->close();
                    m_socket.release();
                    return false;
                }*/

                // set address
                m_listeningFlag.exchange(1);

                // Create thread processing the data
                threads::ThreadSetup setup;
                setup.m_function = [this]() { threadFunc(); };
                setup.m_priority = threads::Priority::AboveNormal;
                setup.m_name = "TCPServerThread";

                // Start selector thread
                m_thread.init(setup);

                // Server is alive
                TRACE_INFO("TCP Server: Started local server on '{}'", m_address);
                return true;
            }

            void Server::close()
            {
                // make sure we close only once
                if (1 == m_initFlag.exchange(0))
                {
                    TRACE_INFO("TCP Server: Closing local server on '{}'", m_address);

                    // close listening socket, this will exit the select() and than the loop
                    m_socket.close();

                    // close socket processing thread, it should be fine now since we closed the master socket
                    m_thread.close();

                    // close all connections
                    m_activeConnections.clearPtr();
                    m_activeConnectionsSocketMap.clear();
                    m_activeConnectionsIDMap.clear();
                }
            }

            Bool Server::send(ConnectionID id, const void* data, const Uint32 dataSize)
            {
                auto lock = CreateLock(m_activeConnectionsLock);

                // don't send shit via dead server
                if (!m_listeningFlag.getValue())
                    return false;

                // get target address for connection
                Connection* connection = nullptr;
                if (!m_activeConnectionsIDMap.find(id, connection))
                    return false;

                // push data and let the system worry
                Uint32 sentLeft = dataSize;
                auto* sentPtr = (const Uint8*)data;
                while (sentLeft > 0)
                {
                    const auto sentSize = connection->m_socket.send(sentPtr, sentLeft);
                    if (sentSize < 0)
                    {
                        TRACE_ERROR("TCP Server: Failed to send {} bytes to {} ({}), closing", dataSize, id, connection->m_address);
                        connection->m_closeRequest.exchange(1);
                        return false;
                    }
                    else if (sentSize != (Int32) dataSize)
                    {
                        TRACE_WARNING("TCP Server: Truncated send ({} -> {}) when sending {} bytes to {} ({})", sentLeft, sentSize, id, connection->m_address);
                        threads::Sleep(10);
                    }

                    sentPtr += sentSize;
                    sentLeft -= sentSize;
                }

                // update stats
                connection->m_stats.m_totalDataSent += dataSize;

                // data sent
                return true;
            }

            Bool Server::disconnect(ConnectionID id)
            {
                // dead server
                if (!m_listeningFlag.getValue())
                    return false;

                auto lock = CreateLock(m_activeConnectionsLock);

                // get target address for connection
                Connection* connection = nullptr;
                if (!m_activeConnectionsIDMap.find(id, connection))
                    return false;

                // close the connection
                TRACE_INFO("TCP Server: Closing connection {} ({})", id, connection->m_address);
                connection->m_closeRequest.exchange(1);
                return true;
            }

            //--

            void Server::serviceListenerSocket(SocketType socket)
            {
                Address remoteAddress;
                RawSocket acceptedSocket;
                if (acceptedSocket.accept(m_socket, &remoteAddress))
                {
                    TRACE_INFO("TCP Server: accepted connection from {}, socket: {}", remoteAddress, acceptedSocket.getSystemSocket());

                    acceptedSocket.setBlocking(false);

                    auto *con = MemNewPool(POOL_NEW, Connection);
                    con->m_id = m_nextConnectionID.increment();
                    con->m_connectedTime.resetToNow();
                    con->m_lastMessageTime.resetToNow();
                    con->m_address = remoteAddress;
                    con->m_socket = std::move(acceptedSocket);
                    con->m_stats.m_startTime.resetToNow();

                    // add to list of active connections, next time we will loop on the receive thread we will start processing the messages
                    {
                        auto lock = CreateLock(m_activeConnectionsLock);
                        m_activeConnections.pushBack(con);
                        m_activeConnectionsIDMap[con->m_id] = con;
                        m_activeConnectionsSocketMap[con->m_socket.getSystemSocket()] = con;
                    }

                    // inform the handler about the new connection
                    m_handler->handleConnectionAccepted(this, remoteAddress, con->m_id);
                }
            }

            void Server::serviceConnectionSocket(SocketType socket, Bool error)
            {
                // find connection for given socket
                Connection *con = nullptr;
                {
                    auto lock = CreateLock(m_activeConnectionsLock);
                    m_activeConnectionsSocketMap.find(socket, con);
                }

                // not found
                if (nullptr == con)
                {
                    TRACE_ERROR("TCP Server: Got data from unrecognized socket");
                    return;
                }

                // close
                if (error)
                {
                    TRACE_ERROR("TCP Server: got error for connection {}", con->m_address);
                    con->m_closeRequest.exchange(1);
                    return;
                }

                // get data
                while (1)
                {
                    const auto dataSize = con->m_socket.receive(m_receciveBuffer.getData(), m_receciveBuffer.getDataSize());
                    if (dataSize < 0)
                    {
                        con->m_closeRequest.exchange(1);
                        break;
                    }
                    else if (dataSize > 0)
                    {
                        // update stats
                        con->m_stats.m_totalDataReceived += dataSize;

                        // pass to handler
                        m_handler->handleConnectionData(this, con->m_address, con->m_id, m_receciveBuffer.getData(), dataSize);
                    }
                    else
                    {
                        // no more data
                        break;
                    }
                }
            }

            void Server::threadFunc()
            {
                Selector selector;

                InplaceArray<SocketType, 64> activeSockets;

                SocketType listenSocket = m_socket.getSystemSocket();

                // loop
                Bool keepRunning = true;
                while (keepRunning)
                {
                    // always put the main socket on the list since we are waiting for the connections
                    activeSockets.reset();
                    activeSockets.pushBack(listenSocket);

                    // process the list of active connections, get list of sockets to look for
                    collectActiveConnections(activeSockets);

                    // wait for something
                    switch (selector.wait(SelectorOp::Read, activeSockets.getTypedData(), activeSockets.size(), 50))
                    {
                        case SelectorEvent::Ready:
                        {
                            // wow, some work
                            for (const auto& result : selector)
                            {
                                if (result.socket == listenSocket)
                                {
                                    if (result.error)
                                    {
                                        TRACE_ERROR("TCP Server: Listener socket closed/lost, existing thread");
                                        serviceListenerClose();
                                        keepRunning = false;
                                    }
                                    else
                                    {
                                        serviceListenerSocket(result.socket);
                                    }
                                }
                                else
                                {
                                    serviceConnectionSocket(result.socket, result.error);
                                }
                            }

                            break;
                        }

                        case SelectorEvent::Busy:
                        {
                            break;
                        }

                        case SelectorEvent::Error:
                        {
                            TRACE_ERROR("TCP Server: Error in poll(), existing server loop");
                            serviceListenerClose();
                            keepRunning = false;
                        }
                    }
                }

                // close all active connections
                if (!m_activeConnections.empty())
                {
                    TRACE_INFO("TCP server: closing remaining {} connections", m_activeConnections.size());
                    m_activeConnections.clearPtr();
                    m_activeConnectionsIDMap.clear();
                    m_activeConnectionsSocketMap.clear();
                }
            }

            void Server::collectActiveConnections(Array<SocketType>& outActiveSockets)
            {
                auto lock = CreateLock(m_activeConnectionsLock);

                for (Int32 i=m_activeConnections.lastValidIndex(); i >= 0; --i)
                {
                    auto* con = m_activeConnections[i];
                    FATAL_ASSERT(con->m_socket);

                    if (con->m_closeRequest.getValue())
                    {
                        TRACE_INFO("TCP Server: Got external request to close connection {} ({}), {}", con->m_id, con->m_address, con->m_socket.getSystemSocket());
                        purgeConnection(con);
                    }
                    else
                    {
                        outActiveSockets.pushBack(con->m_socket.getSystemSocket());
                    }
                }
            }

            void Server::serviceListenerClose()
            {
                if (1 == m_listeningFlag.exchange(0))
                    m_handler->handleServerClose(this);
            }

            void Server::purgeConnection(Connection* con)
            {
                // handle notification
                TRACE_INFO("TCP Server: connection '{}' closed\n{}", con->m_address, con->m_stats);
                m_handler->handleConnectionClosed(this, con->m_address, con->m_id);

                // socket is dead, it's now safe place to delete it
                m_activeConnectionsSocketMap.remove(con->m_socket.getSystemSocket());
                m_activeConnectionsIDMap.remove(con->m_id);
                m_activeConnections.remove(con);

                // close handle
                con->m_socket.close();

                // cleanup object
                MemDelete(con);
            }

            //--

        } // tcp
    } // socket
} // base


text:
namespace NDatabase.Client.UnitTests.Data
{
    public enum City
    {
        NewYork,
        London,
        Barcelona,
        Pekin,
        Sydney,
        Cracow
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace qinq\Query {
    use qinq;
    use qtil;

    class Mutable extends qinq\Query {
        /**
         * Query execution
         * source collection will be updated with results
         * @return mixed
         */
        function execute() {
            $links = $this->getLinks();

            $result = null;
            foreach($links as $link) {
                if($link instanceof qinq\Query\Statement) {
                    $result = $this->statement($link);
                }
            }

            if(!is_null($result)) {
                return $result;
            }

            return $this->collection;
        }

        /**
         * Statement execution
         * @param callable $statement
         * @return \qinq\Query\Statement|\qinq\Collection|null
         */
        protected function statement(qinq\Query\Statement $statement) {
            $result = null;

            $l = call_user_func_array($statement,func_get_args());
            if($l instanceof Statement) {
                $result = $l;
            } elseif(qtil\ArrayUtil::isIterable($l)) {
                if($statement->getMutable() === false) {
                    return new qinq\Collection($l);
                } else {
                    $this->collection->from($l);
                }
            } elseif(!is_null($l)) {
                $result = $l;
            }

            return $result;
        }
    }
}


text:
import React, { Component, PropTypes } from 'react';
// import Helmet from 'react-helmet';
// import { connect } from 'react-redux';
// import {Carousel} from 'react-bootstrap';
// import { LinkContainer } from 'react-router-bootstrap';
// import { Link } from 'react-router';
// import { CounterButton } from 'components';
// import * as authActions from 'redux/modules/auth';
// import * as uiinfoActions from 'redux/modules/uiinfo';
// import MobileDetect from 'mobile-detect';
import Events from 'amazeui-react/lib/utils/Events';
import Mobile from './mobile';
import Pc from './pc';

// @connect(
//   state => ({
//     height: state.uiinfo.height
//   }), uiinfoActions)
export default class QQWPA extends Component {
  static propTypes = {
    func: PropTypes.func,
    // number: PropTypes.number.isRequired,
    // string: PropTypes.string.isRequired,
    // object: PropTypes.object,
  };
  // static defaultProps ={
    // a:'a',
    // b:'b',
  // };
  // static contextTypes = {
  //   show: PropTypes.object.isRequired
  // };
  constructor(props) {
    super(props);
    this.state = {
      windowSize: [0, 0]
    };
  }
  // componentWillMount() {
  //   this.updateDimensions();
  // }
  componentDidMount() {
    this.setWindowSize();
    this._windowResize = Events.on(window, 'resize', this.setWindowSize.bind(this));
  }
  componentWillUnmount() {
    this._windowResize.off();
    clearTimeout(this.timeout);
  }
  setWindowSize() {
    clearTimeout(this.timeout);
    this.timeout = setTimeout(()=>{
      this.setState({
        windowSize: [window.innerWidth, window.innerHeight]
      });
      // console.log([window.innerWidth, window.innerHeight]);
    }, 500);
  }
  render() {
    let qq = '';
    // const md = new MobileDetect(navigator.userAgent);
    // console.log(md.phone());
    if (this.state.windowSize[0] && this.state.windowSize[0] <= 850) {
      qq = <Mobile />;
    } else {
      qq = <Pc />;
    }

    // const ss = require('./QQWPA.scss');
    return (
      <div>
        {qq}
      </div>
    );
  }
}


text:
// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.

using System;
using System.Threading;
using System.Threading.Tasks;
using Perspex.Win32.Threading;

namespace Perspex.Threading
{
    /// <summary>
    /// Provides services for managing work items on a thread.
    /// </summary>
    /// <remarks>
    /// In Perspex, there is usually only a single <see cref="Dispatcher"/> in the application -
    /// the one for the UI thread, retrieved via the <see cref="UIThread"/> property.
    /// </remarks>
    public class Dispatcher
    {
        private static readonly Dispatcher s_instance = new Dispatcher();

        private readonly MainLoop _mainLoop = new MainLoop();

        /// <summary>
        /// Initializes a new instance of the <see cref="Dispatcher"/> class.
        /// </summary>
        private Dispatcher()
        {
        }

        /// <summary>
        /// Gets the <see cref="Dispatcher"/> for the UI thread.
        /// </summary>
        public static Dispatcher UIThread => s_instance;

        /// <summary>
        /// Runs the dispatcher's main loop.
        /// </summary>
        /// <param name="cancellationToken">
        /// A cancellation token used to exit the main loop.
        /// </param>
        public void MainLoop(CancellationToken cancellationToken)
        {
            _mainLoop.Run(cancellationToken);
        }

        /// <summary>
        /// Runs continuations pushed on the loop.
        /// </summary>
        public void RunJobs()
        {
            _mainLoop.RunJobs();
        }

        /// <summary>
        /// Invokes a method on the dispatcher thread.
        /// </summary>
        /// <param name="action">The method.</param>
        /// <param name="priority">The priority with which to invoke the method.</param>
        /// <returns>A task that can be used to track the method's execution.</returns>
        public Task InvokeAsync(Action action, DispatcherPriority priority = DispatcherPriority.Normal)
        {
            return _mainLoop.InvokeAsync(action, priority);
        }

        /// <summary>
        /// Post action that will be invoked on main thread
        /// </summary>
        /// <param name="action">The method.</param>
        /// <param name="priority">The priority with which to invoke the method.</param>
        internal void Post(Action action, DispatcherPriority priority = DispatcherPriority.Normal)
        {
            _mainLoop.Post(action, priority);
        }
    }
}


text:
package game.controller.optionState;

import game.controller.AbstractBattleMode;

/**
 * Trainer battle is complete.  There is a won state and lost state that extend this class and determine the appropriate
 * action based on the result of the battle.
 * @author Team Rocket
 *
 */
public abstract class AbstractTrainerBattleComplete extends AbstractBattleCompleteState {

    public AbstractTrainerBattleComplete (AbstractBattleMode mode, String text) {
        super(mode, text);
    }
}


text:
require "minitest/test"
require "growl"

module Minitest

  def self.plugin_growler_options(opts, options)
  end

  def self.plugin_growler_init(options)
    if Growler.growler?
      self.reporter << Growler.new(options)
    end
  end

  class Growler < StatisticsReporter
    VERSION = "1.0.0"

    def self.growler!
      @growler = true
    end

    def self.growler?
      @growler ||= false
    end

    def initialize(options)
      super
    end

    def report
      super

      if failures.to_i > 0 || errors.to_i > 0
        notify("Tests Failed! (#{failures.to_i} failures, #{errors.to_i} errors)", :failure)
      else
        notify("Tests Passed! (#{assertions.to_i} assertions)", :success)
      end
    end

    def notify(message, image_type)
      Growl.notify(message, :image => image_path(image_type))
    end

    def image_path(type)
      File.join(File.expand_path(File.dirname(__FILE__)), 'images', "#{type}.png")
    end
  end
end


text:
ACCEPTED

#### According to
World Register of Marine Species

#### Published in
J. Anat. Physiol. , London, 1, 335.

#### Original name
null

### Remarks
null


text:
package com.qdong.communal.library.module.network;

public class QDongException extends  Exception {

    public QDongException(String detailMessage) {
        super(detailMessage);
    }

}


text:
package athena.api.regression.LinearRegression;

import athena.api.DetectionAlgorithm;
import athena.api.DetectionAlgorithmType;
import athena.api.DetectionStrategy;

import java.io.Serializable;

/**
 * Implementation for K-Means clustering algorithms
 * The options are described below:
 * data - training points stored as RDD[Vector]
 * k - number of clusters
 * maxIterations - max number of iterations
 * runs - number of parallel runs, defaults to 1. The best model is returned.
 * initializationMode - initialization model, either "random" or "k-means||" (default).
 * seed - random seed value for cluster initialization
 * epsion- Set the distance threshold within which we've consider centers to have converged.
 * Created by seunghyeon on 4/7/16.
 */
public class LinearRegressionDetectionAlgorithm implements DetectionAlgorithm, Serializable {
    int numClasses = 2;
    int numIterations = 100;
    double stepSize = 0.00000001;
    double miniBatchFraction = -1;

    public int getNumIterations() {
        return numIterations;
    }

    public void setNumIterations(int numIterations) {
        this.numIterations = numIterations;
    }

    public double getStepSize() {
        return stepSize;
    }

    public void setStepSize(double stepSize) {
        this.stepSize = stepSize;
    }

    public double getMiniBatchFraction() {
        return miniBatchFraction;
    }

    public void setMiniBatchFraction(double miniBatchFraction) {
        this.miniBatchFraction = miniBatchFraction;
    }

    public int getNumClasses() {
        return numClasses;
    }

    public void setNumClasses(int numClasses) {
        this.numClasses = numClasses;
    }

    @Override
    public DetectionAlgorithmType getDetectionAlgorithmType() {
        return DetectionAlgorithmType.CLASSIFICATION;
    }

    @Override
    public DetectionStrategy getDetectionStrategy() {
        return DetectionStrategy.Linear;
    }
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\FixturesBundle\Listener;

use Symfony\Component\Config\Definition\ConfigurationInterface;

interface ListenerInterface extends ConfigurationInterface
{
    public function getName(): string;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="../resources/text-based-repaint.js"></script>
</head>
<body onload="runRepaintAndPixelTest()">
<svg style="position: absolute; top: 0; left: 0; width: 100%; height: 100%">
    <title>You should see the word PASS two times</title>
    <text id="text" transform="translate(10, 50) scale(10 10)" font-size="12">
        <tspan x="0" y="12">PASS</tspan>
        <tspan x="0" y="12" id="remove">FAIL</tspan>
        <tspan x="0" y="24">PASS</tspan>
    </text>
</svg>
</body>
<script>
function repaintTest() {
    document.getElementById("text").removeChild(document.getElementById("remove"));
}
</script>
</html>


text:
function [] = testRunModel()
%% function [] = testRunModel()
%
% Calls different tests for runModel_Themi.m.
%

[bol,message] = testReadingSubAndForecastDataAndWritingDB();
if bol ~= 1
  fprintf('ERROR in testReadingSubAndForecastDataAndWritingDB().\n');
  fprintf('Message: %s\n',message);
end;

[bol, message] = testAssimilation();
if bol ~= 1
  fprintf('ERROR in testAssimilation().\n');
  fprintf('Message: %s.\n',message);
end

end


text:
create table if not exists gameTime (
    id                bigint auto_increment,
    gameDateId        bigint not NULL,
    fieldId           bigint not NULL,
    startTime         time not NULL,
    actualStartTime   time default NULL,
    genderPreference  varchar(10) not NULL,
    gameId            bigint default NULL,
    locked            tinyint not NULL default 0,

    PRIMARY KEY (id),
    unique key ux_gameOneGame(gameDateId, fieldId, startTime),
    unique key ux_gameId(gameId),
    key ix_fieldIdStartTime(fieldId, startTime),
    key ix_fieldIdGender(fieldId, genderPreference)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


text:
<?php

namespace ShangCube\Sphere\Utility;

use ShangCube\Sphere\Core\Configuration;
use ShangCube\Sphere\Core\ConfigurationInterface;
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\Mapping\UnderscoreNamingStrategy;

class GeneralUtility
{
    /**
     * @var ConfigurationInterface
     */
    protected static $configuration;

    /**
     * @return ConfigurationInterface
     */
    public static function getConfiguration()
    {
        if (!isset(self::$configuration)) {
            self::$configuration = new class extends Configuration
            {
                protected function initialize()
                {
                    $databaseParameter = [];

                    // @todo Database configuration should be got from database driver utility with different support
                    if ($url = getenv('DATABASE_URL')) {
                        $databaseParameter['url'] = $url;
                    }
                    $this->databaseParameter = $databaseParameter;

                    $metadataType = getenv('METADATA_TYPE');
                    $metadataPath = getenv('METADATA_PATH');
                    $this->metadataConfig = Setup::createYAMLMetadataConfiguration(array($metadataPath), true);
                    $this->metadataConfig->setNamingStrategy(new UnderscoreNamingStrategy(CASE_LOWER));
                }
            };
        }

        return self::$configuration;
    }

    public static function makeObjectInstance($className)
    {

    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Maughania rollae K.V.Billore & K.Hemadri

### Remarks
null


text:
import './integration_server_status_map.html';
import './integration_server_status_map.css';
import { Template }               from 'meteor/templating';
import SimpleSchema               from 'simpl-schema';
import { RobaDialog }             from 'meteor/austinsand:roba-dialog';
import { IntegrationServers }     from '../../../../../imports/api/integrations/integration_servers';
import { ImportedItemWorkStates } from '../../../../../imports/api/imported_items/imported_item_work_states';
import { ImportedItemWorkPhases } from '../../../../../imports/api/imported_items/imported_item_work_phases';
import { Util }                   from '../../../../../imports/api/util';
import './integration_server_status_reference';

/**
 * Template Helpers
 */
Template.IntegrationServerStatusMap.helpers({
  statusMap () {
    let server = this;

    return server && server.statusMap || {}
  },
  workStates () {
    return _.keys(ImportedItemWorkStates).map((workState) => {
      return { key: workState, title: Util.camelToTitle(workState) }
    })
  },
  workPhases () {
    return _.keys(ImportedItemWorkPhases).map((workPhase) => {
      return { key: workPhase, title: Util.camelToTitle(workPhase) }
    })
  },
  unmappedStatuses () {
    let statusMap        = this,
        statusList       = Template.instance().statusList.get() || [],
        mappedStatuses   = _.keys(statusMap),
        unmappedStatuses = [];

    statusList.forEach((status) => {
      if (!_.contains(mappedStatuses, status.id)) {
        unmappedStatuses.push(status);
      }
    });

    return _.sortBy(unmappedStatuses, 'title')
  }
});

/**
 * Template Event Handlers
 */
Template.IntegrationServerStatusMap.events({
  'drop .status-drop-box' (e, instance, ui) {
    let dropBox       = $(e.target),
        statusElement = ui.helper,
        statusList    = instance.statusList.get() || [],
        phaseKey      = dropBox.attr('data-phase-key'),
        stateKey      = dropBox.attr('data-state-key'),
        statusId      = statusElement.attr('data-id'),
        rawStatus     = _.findWhere(statusList, { id: statusId }),
        serverId      = FlowRouter.getParam('serverId'),
        server        = IntegrationServers.findOne(serverId),
        statusMap     = server.statusMap || {};

    console.log('Drop:', rawStatus, phaseKey, stateKey, statusId);

    if (rawStatus !== undefined && phaseKey !== undefined && stateKey !== undefined && statusId !== undefined) {
      statusMap[ statusId ] = {
        workPhase: phaseKey,
        workState: stateKey,
        status   : rawStatus
      };
      Meteor.call('editIntegrationServer', serverId, 'statusMap', statusMap, (error, response) => {
        if (error) {
          console.error('editIntegrationServer failed:', error);
        } else {
          console.log('editIntegrationServer returned:', response);
          instance.$('.status-card').height('auto');
        }
      });
    } else {
      console.error('Something was null on the drop:', rawStatus, phaseKey, stateKey, statusId, statusMap);
    }
  },
  'click .btn-remove-status-mapping' (e, instance) {
    let statusElement = $(e.target).closest('.status-card'),
        statusId      = statusElement.attr('data-id'),
        serverId      = FlowRouter.getParam('serverId'),
        server        = IntegrationServers.findOne(serverId),
        statusMap     = server.statusMap || {};

    console.log('Remove Status Mapping:', statusId, statusMap);

    if (statusId && statusMap) {
      delete statusMap[ statusId ];
      Meteor.call('editIntegrationServer', serverId, 'statusMap', statusMap, (error, response) => {
        if (error) {
          console.error('editIntegrationServer failed:', error);
        } else {
          console.log('editIntegrationServer returned:', response);
        }
      });
    }
  },
  'click .btn-add-status' (e, instance) {
    let workPhase = this,
        serverId  = FlowRouter.getParam('serverId'),
        server    = IntegrationServers.findOne(serverId),
        statusMap = server.statusMap || {};
    console.log('Add status to work phase:', workPhase);

    RobaDialog.show({
      contentTemplate: 'AddRecordForm',
      contentData    : {
        schema: new SimpleSchema({
          id          : {
            type : String,
            label: 'ID'
          },
          title       : {
            type : String,
            label: 'Title'
          },
          workStateKey: {
            type    : String,
            label   : 'Work State',
            autoform: {
              options: _.keys(ImportedItemWorkStates).map((key) => {
                return {
                  label: Util.camelToTitle(key),
                  value: key
                }
              })
            }
          }
        })
      },
      title          : 'Add Status',
      width          : 500,
      buttons        : [
        { text: 'Cancel' },
        { text: 'Add' }
      ],
      callback       : function (btn) {
        if (btn.match(/add/i)) {
          let formId = $('.roba-dialog form').attr('id');
          if (AutoForm.validateForm(formId)) {
            let formData = AutoForm.getFormValues(formId).insertDoc;

            // Add a status to the status map
            RobaDialog.hide();
            if (statusMap[ formData.id ]) {
              RobaDialog.error('Duplicate status id')
            } else {
              statusMap[ formData.id ] = {
                workPhase: workPhase.key,
                workState: formData.workStateKey,
                status   : {
                  id   : formData.id,
                  title: formData.title
                }
              };
              console.log('Manually adjusting statusMap:', formData, statusMap);
              Meteor.call('editIntegrationServer', serverId, 'statusMap', statusMap, (error, response) => {
                if (error) {
                  console.error('editIntegrationServer failed:', error);
                } else {
                  console.log('editIntegrationServer returned:', response);
                }
              });
            }

            AutoForm.resetForm(formId)
          }
          return;
        }
        RobaDialog.hide();
      }.bind(this)
    });
  }
});

/**
 * Template Created
 */
Template.IntegrationServerStatusMap.onCreated(() => {
  let instance = Template.instance();

  instance.statusList = new ReactiveVar();

  instance.autorun(() => {
    let server = Template.currentData();

    if (server && server._id && server.isAuthenticated) {
      Meteor.call('getIntegrationServerStatusList', server._id, (error, response) => {
        if (error) {
          console.error('getIntegrationServerStatusList failed:', error);
        } else {
          instance.statusList.set(response);
        }
      });
    }
  })
});

/**
 * Template Rendered
 */
Template.IntegrationServerStatusMap.onRendered(() => {
  let instance = Template.instance();

  instance.autorun(() => {
    let statusList = instance.statusList.get();

    if (statusList) {
      setTimeout(() => {
        instance.$('.status-card').draggable({
          revert        : true,
          revertDuration: 0
        });

        instance.$('.status-drop-box').droppable({
          hoverClass : 'status-drop-box-hover',
          activeClass: 'status-drop-box-active',
          tolerance  : 'pointer'
        });
      }, 1000);
    }
  })
});

/**
 * Template Destroyed
 */
Template.IntegrationServerStatusMap.onDestroyed(() => {

});


text:
(function(){
Template.__checkName("post_submit");
Template["post_submit"] = new Template("Template.post_submit", (function() {
  var view = this;
  return HTML.DIV({
    "class": "grid grid-module"
  }, "\n    ", Blaze._TemplateWith(function() {
    return {
      collection: Spacebars.call("Posts"),
      id: Spacebars.call("submitPostForm"),
      template: Spacebars.call("telescope"),
      "label-class": Spacebars.call("control-label"),
      "input-col-class": Spacebars.call("controls"),
      type: Spacebars.call("method"),
      meteormethod: Spacebars.call("submitPost")
    };
  }, function() {
    return Spacebars.include(view.lookupTemplate("quickForm"));
  }), "\n  ");
}));

})();


text:
// hardcodet.net NotifyIcon for WPF
// Copyright (c) 2009 - 2013 Philipp Sumi
// Contact and Information: http://www.hardcodet.net
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Code Project Open License (CPOL);
// either version 1.0 of the License, or (at your option) any later
// version.
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
// THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE

using System;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Interop;
using System.Windows.Threading;
using SimulaDesign.ClientTray.Interop;
using Point = SimulaDesign.ClientTray.Interop.Point;

namespace SimulaDesign.ClientTray
{
    /// <summary>
    /// A WPF proxy to for a taskbar icon (NotifyIcon) that sits in the system's
    /// taskbar notification area ("system tray").
    /// </summary>
    public partial class TaskbarIcon : FrameworkElement, IDisposable
    {
        #region Members

        /// <summary>
        /// Represents the current icon data.
        /// </summary>
        private NotifyIconData iconData;

        /// <summary>
        /// Receives messages from the taskbar icon.
        /// </summary>
        private readonly WindowMessageSink messageSink;

        /// <summary>
        /// An action that is being invoked if the
        /// <see cref="singleClickTimer"/> fires.
        /// </summary>
        private Action singleClickTimerAction;

        /// <summary>
        /// A timer that is used to differentiate between single
        /// and double clicks.
        /// </summary>
        private readonly Timer singleClickTimer;

        /// <summary>
        /// A timer that is used to close open balloon tooltips.
        /// </summary>
        private readonly Timer balloonCloseTimer;

        /// <summary>
        /// Indicates whether the taskbar icon has been created or not.
        /// </summary>
        public bool IsTaskbarIconCreated { get; private set; }

        /// <summary>
        /// Indicates whether custom tooltips are supported, which depends
        /// on the OS. Windows Vista or higher is required in order to
        /// support this feature.
        /// </summary>
        public bool SupportsCustomToolTips
        {
            get { return messageSink.Version == NotifyIconVersion.Vista; }
        }

        /// <summary>
        /// Checks whether a non-tooltip popup is currently opened.
        /// </summary>
        private bool IsPopupOpen
        {
            get
            {
                var popup = TrayPopupResolved;
                var menu = ContextMenu;
                var balloon = CustomBalloon;

                return popup != null && popup.IsOpen ||
                       menu != null && menu.IsOpen ||
                       balloon != null && balloon.IsOpen;
            }
        }

        private double scalingFactor = double.NaN;

        #endregion

        #region Construction

        /// <summary>
        /// Inits the taskbar icon and registers a message listener
        /// in order to receive events from the taskbar area.
        /// </summary>
        public TaskbarIcon()
        {
            //using dummy sink in design mode
            messageSink = Util.IsDesignMode
                ? WindowMessageSink.CreateEmpty()
                : new WindowMessageSink(NotifyIconVersion.Win95);

            //init icon data structure
            iconData = NotifyIconData.CreateDefault(messageSink.MessageWindowHandle);

            //create the taskbar icon
            CreateTaskbarIcon();

            //register event listeners
            messageSink.MouseEventReceived += OnMouseEvent;
            messageSink.TaskbarCreated += OnTaskbarCreated;
            messageSink.ChangeToolTipStateRequest += OnToolTipChange;
            messageSink.BalloonToolTipChanged += OnBalloonToolTipChanged;

            //init single click / balloon timers
            singleClickTimer = new Timer(DoSingleClickAction);
            balloonCloseTimer = new Timer(CloseBalloonCallback);

            //register listener in order to get notified when the application closes
            if (Application.Current != null) Application.Current.Exit += OnExit;
        }

        #endregion

        #region Custom Balloons

        /// <summary>
        /// Shows a custom control as a tooltip in the tray location.
        /// </summary>
        /// <param name="balloon"></param>
        /// <param name="animation">An optional animation for the popup.</param>
        /// <param name="timeout">The time after which the popup is being closed.
        /// Submit null in order to keep the balloon open inde
        /// </param>
        /// <exception cref="ArgumentNullException">If <paramref name="balloon"/>
        /// is a null reference.</exception>
        public void ShowCustomBalloon(UIElement balloon, PopupAnimation animation, int? timeout)
        {
            Dispatcher dispatcher = this.GetDispatcher();
            if (!dispatcher.CheckAccess())
            {
                var action = new Action(() => ShowCustomBalloon(balloon, animation, timeout));
                dispatcher.Invoke(DispatcherPriority.Normal, action);
                return;
            }

            if (balloon == null) throw new ArgumentNullException("balloon");
            if (timeout.HasValue && timeout < 500)
            {
                string msg = "Invalid timeout of {0} milliseconds. Timeout must be at least 500 ms";
                msg = String.Format(msg, timeout);
                throw new ArgumentOutOfRangeException("timeout", msg);
            }

            EnsureNotDisposed();

            //make sure we don't have an open balloon
            lock (this)
            {
                CloseBalloon();
            }

            //create an invisible popup that hosts the UIElement
            Popup popup = new Popup();
            popup.AllowsTransparency = true;

            //provide the popup with the taskbar icon's data context
            UpdateDataContext(popup, null, DataContext);

            //don't animate by default - devs can use attached
            //events or override
            popup.PopupAnimation = animation;

            //in case the balloon is cleaned up through routed events, the
            //control didn't remove the balloon from its parent popup when
            //if was closed the last time - just make sure it doesn't have
            //a parent that is a popup
            var parent = LogicalTreeHelper.GetParent(balloon) as Popup;
            if (parent != null) parent.Child = null;

            if (parent != null)
            {
                string msg =
                    "Cannot display control [{0}] in a new balloon popup - that control already has a parent. You may consider creating new balloons every time you want to show one.";
                msg = String.Format(msg, balloon);
                throw new InvalidOperationException(msg);
            }

            popup.Child = balloon;

            //don't set the PlacementTarget as it causes the popup to become hidden if the
            //TaskbarIcon's parent is hidden, too...
            //popup.PlacementTarget = this;

            popup.Placement = PlacementMode.AbsolutePoint;
            popup.StaysOpen = true;

            Point position = TrayInfo.GetTrayLocation();
            position = GetDeviceCoordinates(position);
            popup.HorizontalOffset = position.X - 1;
            popup.VerticalOffset = position.Y - 1;

            //store reference
            lock (this)
            {
                SetCustomBalloon(popup);
            }

            //assign this instance as an attached property
            SetParentTaskbarIcon(balloon, this);

            //fire attached event
            RaiseBalloonShowingEvent(balloon, this);

            //display item
            popup.IsOpen = true;

            if (timeout.HasValue)
            {
                //register timer to close the popup
                balloonCloseTimer.Change(timeout.Value, Timeout.Infinite);
            }
        }

        /// <summary>
        /// Resets the closing timeout, which effectively
        /// keeps a displayed balloon message open until
        /// it is either closed programmatically through
        /// <see cref="CloseBalloon"/> or due to a new
        /// message being displayed.
        /// </summary>
        public void ResetBalloonCloseTimer()
        {
            if (IsDisposed) return;

            lock (this)
            {
                //reset timer in any case
                balloonCloseTimer.Change(Timeout.Infinite, Timeout.Infinite);
            }
        }

        /// <summary>
        /// Closes the current <see cref="CustomBalloon"/>, if the
        /// property is set.
        /// </summary>
        public void CloseBalloon()
        {
            if (IsDisposed) return;

            Dispatcher dispatcher = this.GetDispatcher();
            if (!dispatcher.CheckAccess())
            {
                Action action = CloseBalloon;
                dispatcher.Invoke(DispatcherPriority.Normal, action);
                return;
            }

            lock (this)
            {
                //reset timer in any case
                balloonCloseTimer.Change(Timeout.Infinite, Timeout.Infinite);

                //reset old popup, if we still have one
                Popup popup = CustomBalloon;
                if (popup != null)
                {
                    UIElement element = popup.Child;

                    //announce closing
                    RoutedEventArgs eventArgs = RaiseBalloonClosingEvent(element, this);
                    if (!eventArgs.Handled)
                    {
                        //if the event was handled, clear the reference to the popup,
                        //but don't close it - the handling code has to manage this stuff now

                        //close the popup
                        popup.IsOpen = false;

                        //remove the reference of the popup to the balloon in case we want to reuse
                        //the balloon (then added to a new popup)
                        popup.Child = null;

                        //reset attached property
                        if (element != null) SetParentTaskbarIcon(element, null);
                    }

                    //remove custom balloon anyway
                    SetCustomBalloon(null);
                }
            }
        }

        /// <summary>
        /// Timer-invoke event which closes the currently open balloon and
        /// resets the <see cref="CustomBalloon"/> dependency property.
        /// </summary>
        private void CloseBalloonCallback(object state)
        {
            if (IsDisposed) return;

            //switch to UI thread
            Action action = CloseBalloon;
            this.GetDispatcher().Invoke(action);
        }

        #endregion

        #region Process Incoming Mouse Events

        /// <summary>
        /// Processes mouse events, which are bubbled
        /// through the class' routed events, trigger
        /// certain actions (e.g. show a popup), or
        /// both.
        /// </summary>
        /// <param name="me">Event flag.</param>
        private void OnMouseEvent(MouseEvent me)
        {
            if (IsDisposed) return;

            switch (me)
            {
                case MouseEvent.MouseMove:
                    RaiseTrayMouseMoveEvent();
                    //immediately return - there's nothing left to evaluate
                    return;
                case MouseEvent.IconRightMouseDown:
                    RaiseTrayRightMouseDownEvent();
                    break;
                case MouseEvent.IconLeftMouseDown:
                    RaiseTrayLeftMouseDownEvent();
                    break;
                case MouseEvent.IconRightMouseUp:
                    RaiseTrayRightMouseUpEvent();
                    break;
                case MouseEvent.IconLeftMouseUp:
                    RaiseTrayLeftMouseUpEvent();
                    break;
                case MouseEvent.IconMiddleMouseDown:
                    RaiseTrayMiddleMouseDownEvent();
                    break;
                case MouseEvent.IconMiddleMouseUp:
                    RaiseTrayMiddleMouseUpEvent();
                    break;
                case MouseEvent.IconDoubleClick:
                    //cancel single click timer
                    singleClickTimer.Change(Timeout.Infinite, Timeout.Infinite);
                    //bubble event
                    RaiseTrayMouseDoubleClickEvent();
                    break;
                case MouseEvent.BalloonToolTipClicked:
                    RaiseTrayBalloonTipClickedEvent();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("me", "Missing handler for mouse event flag: " + me);
            }

            //get mouse coordinates
            Point cursorPosition = new Point();
            if (messageSink.Version == NotifyIconVersion.Vista)
            {
                //physical cursor position is supported for Vista and above
                WinApi.GetPhysicalCursorPos(ref cursorPosition);
            }
            else
            {
                WinApi.GetCursorPos(ref cursorPosition);
            }

            cursorPosition = GetDeviceCoordinates(cursorPosition);

            bool isLeftClickCommandInvoked = false;

            //show popup, if requested
            if (me.IsMatch(PopupActivation))
            {
                if (me == MouseEvent.IconLeftMouseUp)
                {
                    //show popup once we are sure it's not a double click
                    singleClickTimerAction = () =>
                    {
                        LeftClickCommand.ExecuteIfEnabled(LeftClickCommandParameter, LeftClickCommandTarget ?? this);
                        ShowTrayPopup(cursorPosition);
                    };
                    singleClickTimer.Change(WinApi.GetDoubleClickTime(), Timeout.Infinite);
                    isLeftClickCommandInvoked = true;
                }
                else
                {
                    //show popup immediately
                    ShowTrayPopup(cursorPosition);
                }
            }

            //show context menu, if requested
            if (me.IsMatch(MenuActivation))
            {
                if (me == MouseEvent.IconLeftMouseUp)
                {
                    //show context menu once we are sure it's not a double click
                    singleClickTimerAction = () =>
                    {
                        LeftClickCommand.ExecuteIfEnabled(LeftClickCommandParameter, LeftClickCommandTarget ?? this);
                        ShowContextMenu(cursorPosition);
                    };
                    singleClickTimer.Change(WinApi.GetDoubleClickTime(), Timeout.Infinite);
                    isLeftClickCommandInvoked = true;
                }
                else
                {
                    //show context menu immediately
                    ShowContextMenu(cursorPosition);
                }
            }

            //make sure the left click command is invoked on mouse clicks
            if (me == MouseEvent.IconLeftMouseUp && !isLeftClickCommandInvoked)
            {
                //show context menu once we are sure it's not a double click
                singleClickTimerAction =
                    () =>
                    {
                        LeftClickCommand.ExecuteIfEnabled(LeftClickCommandParameter, LeftClickCommandTarget ?? this);
                    };
                singleClickTimer.Change(WinApi.GetDoubleClickTime(), Timeout.Infinite);
            }
        }

        #endregion

        #region ToolTips

        /// <summary>
        /// Displays a custom tooltip, if available. This method is only
        /// invoked for Windows Vista and above.
        /// </summary>
        /// <param name="visible">Whether to show or hide the tooltip.</param>
        private void OnToolTipChange(bool visible)
        {
            //if we don't have a tooltip, there's nothing to do here...
            if (TrayToolTipResolved == null) return;

            if (visible)
            {
                if (IsPopupOpen)
                {
                    //ignore if we are already displaying something down there
                    return;
                }

                var args = RaisePreviewTrayToolTipOpenEvent();
                if (args.Handled) return;

                TrayToolTipResolved.IsOpen = true;

                //raise attached event first
                if (TrayToolTip != null) RaiseToolTipOpenedEvent(TrayToolTip);

                //bubble routed event
                RaiseTrayToolTipOpenEvent();
            }
            else
            {
                var args = RaisePreviewTrayToolTipCloseEvent();
                if (args.Handled) return;

                //raise attached event first
                if (TrayToolTip != null) RaiseToolTipCloseEvent(TrayToolTip);

                TrayToolTipResolved.IsOpen = false;

                //bubble event
                RaiseTrayToolTipCloseEvent();
            }
        }

        /// <summary>
        /// Creates a <see cref="ToolTip"/> control that either
        /// wraps the currently set <see cref="TrayToolTip"/>
        /// control or the <see cref="ToolTipText"/> string.<br/>
        /// If <see cref="TrayToolTip"/> itself is already
        /// a <see cref="ToolTip"/> instance, it will be used directly.
        /// </summary>
        /// <remarks>We use a <see cref="ToolTip"/> rather than
        /// <see cref="Popup"/> because there was no way to prevent a
        /// popup from causing cyclic open/close commands if it was
        /// placed under the mouse. ToolTip internally uses a Popup of
        /// its own, but takes advance of Popup's internal <see cref="UIElement.IsHitTestVisible"/>
        /// property which prevents this issue.</remarks>
        private void CreateCustomToolTip()
        {
            //check if the item itself is a tooltip
            ToolTip tt = TrayToolTip as ToolTip;

            if (tt == null && TrayToolTip != null)
            {
                //create an invisible wrapper tooltip that hosts the UIElement
                tt = new ToolTip();
                tt.Placement = PlacementMode.Mouse;

                //do *not* set the placement target, as it causes the popup to become hidden if the
                //TaskbarIcon's parent is hidden, too. At runtime, the parent can be resolved through
                //the ParentTaskbarIcon attached dependency property:
                //tt.PlacementTarget = this;

                //make sure the tooltip is invisible
                tt.HasDropShadow = false;
                tt.BorderThickness = new Thickness(0);
                tt.Background = System.Windows.Media.Brushes.Transparent;

                //setting the
                tt.StaysOpen = true;
                tt.Content = TrayToolTip;
            }
            else if (tt == null && !String.IsNullOrEmpty(ToolTipText))
            {
                //create a simple tooltip for the ToolTipText string
                tt = new ToolTip();
                tt.Content = ToolTipText;
            }

            //the tooltip explicitly gets the DataContext of this instance.
            //If there is no DataContext, the TaskbarIcon assigns itself
            if (tt != null)
            {
                UpdateDataContext(tt, null, DataContext);
            }

            //store a reference to the used tooltip
            SetTrayToolTipResolved(tt);
        }

        /// <summary>
        /// Sets tooltip settings for the class depending on defined
        /// dependency properties and OS support.
        /// </summary>
        private void WriteToolTipSettings()
        {
            const IconDataMembers flags = IconDataMembers.Tip;
            iconData.ToolTipText = ToolTipText;

            if (messageSink.Version == NotifyIconVersion.Vista)
            {
                //we need to set a tooltip text to get tooltip events from the
                //taskbar icon
                if (String.IsNullOrEmpty(iconData.ToolTipText) && TrayToolTipResolved != null)
                {
                    //if we have not tooltip text but a custom tooltip, we
                    //need to set a dummy value (we're displaying the ToolTip control, not the string)
                    iconData.ToolTipText = "ToolTip";
                }
            }

            //update the tooltip text
            Util.WriteIconData(ref iconData, NotifyCommand.Modify, flags);
        }

        #endregion

        #region Custom Popup

        /// <summary>
        /// Creates a <see cref="ToolTip"/> control that either
        /// wraps the currently set <see cref="TrayToolTip"/>
        /// control or the <see cref="ToolTipText"/> string.<br/>
        /// If <see cref="TrayToolTip"/> itself is already
        /// a <see cref="ToolTip"/> instance, it will be used directly.
        /// </summary>
        /// <remarks>We use a <see cref="ToolTip"/> rather than
        /// <see cref="Popup"/> because there was no way to prevent a
        /// popup from causing cyclic open/close commands if it was
        /// placed under the mouse. ToolTip internally uses a Popup of
        /// its own, but takes advance of Popup's internal <see cref="UIElement.IsHitTestVisible"/>
        /// property which prevents this issue.</remarks>
        private void CreatePopup()
        {
            //check if the item itself is a popup
            Popup popup = TrayPopup as Popup;

            if (popup == null && TrayPopup != null)
            {
                //create an invisible popup that hosts the UIElement
                popup = new Popup();
                popup.AllowsTransparency = true;

                //don't animate by default - devs can use attached
                //events or override
                popup.PopupAnimation = PopupAnimation.None;

                //the CreateRootPopup method outputs binding errors in the debug window because
                //it tries to bind to "Popup-specific" properties in case they are provided by the child.
                //We don't need that so just assign the control as the child.
                popup.Child = TrayPopup;

                //do *not* set the placement target, as it causes the popup to become hidden if the
                //TaskbarIcon's parent is hidden, too. At runtime, the parent can be resolved through
                //the ParentTaskbarIcon attached dependency property:
                //popup.PlacementTarget = this;

                popup.Placement = PlacementMode.AbsolutePoint;
                popup.StaysOpen = false;
            }

            //the popup explicitly gets the DataContext of this instance.
            //If there is no DataContext, the TaskbarIcon assigns itself
            if (popup != null)
            {
                UpdateDataContext(popup, null, DataContext);
            }

            //store a reference to the used tooltip
            SetTrayPopupResolved(popup);
        }

        /// <summary>
        /// Displays the <see cref="TrayPopup"/> control if
        /// it was set.
        /// </summary>
        private void ShowTrayPopup(Point cursorPosition)
        {
            if (IsDisposed) return;

            //raise preview event no matter whether popup is currently set
            //or not (enables client to set it on demand)
            var args = RaisePreviewTrayPopupOpenEvent();
            if (args.Handled) return;

            if (TrayPopup != null)
            {
                //use absolute position, but place the popup centered above the icon
                TrayPopupResolved.Placement = PlacementMode.AbsolutePoint;
                TrayPopupResolved.HorizontalOffset = cursorPosition.X;
                TrayPopupResolved.VerticalOffset = cursorPosition.Y;

                //open popup
                TrayPopupResolved.IsOpen = true;

                IntPtr handle = IntPtr.Zero;
                if (TrayPopupResolved.Child != null)
                {
                    //try to get a handle on the popup itself (via its child)
                    HwndSource source = (HwndSource) PresentationSource.FromVisual(TrayPopupResolved.Child);
                    if (source != null) handle = source.Handle;
                }

                //if we don't have a handle for the popup, fall back to the message sink
                if (handle == IntPtr.Zero) handle = messageSink.MessageWindowHandle;

                //activate either popup or message sink to track deactivation.
                //otherwise, the popup does not close if the user clicks somewhere else
                WinApi.SetForegroundWindow(handle);

                //raise attached event - item should never be null unless developers
                //changed the CustomPopup directly...
                if (TrayPopup != null) RaisePopupOpenedEvent(TrayPopup);

                //bubble routed event
                RaiseTrayPopupOpenEvent();
            }
        }

        #endregion

        #region Context Menu

        /// <summary>
        /// Displays the <see cref="ContextMenu"/> if
        /// it was set.
        /// </summary>
        private void ShowContextMenu(Point cursorPosition)
        {
            if (IsDisposed) return;

            //raise preview event no matter whether context menu is currently set
            //or not (enables client to set it on demand)
            var args = RaisePreviewTrayContextMenuOpenEvent();
            if (args.Handled) return;

            if (ContextMenu != null)
            {
                //use absolute positioning. We need to set the coordinates, or a delayed opening
                //(e.g. when left-clicked) opens the context menu at the wrong place if the mouse
                //is moved!
                ContextMenu.Placement = PlacementMode.AbsolutePoint;
                ContextMenu.HorizontalOffset = cursorPosition.X;
                ContextMenu.VerticalOffset = cursorPosition.Y;
                ContextMenu.IsOpen = true;

                IntPtr handle = IntPtr.Zero;

                //try to get a handle on the context itself
                HwndSource source = (HwndSource) PresentationSource.FromVisual(ContextMenu);
                if (source != null)
                {
                    handle = source.Handle;
                }

                //if we don't have a handle for the popup, fall back to the message sink
                if (handle == IntPtr.Zero) handle = messageSink.MessageWindowHandle;

                //activate the context menu or the message window to track deactivation - otherwise, the context menu
                //does not close if the user clicks somewhere else. With the message window
                //fallback, the context menu can't receive keyboard events - should not happen though
                WinApi.SetForegroundWindow(handle);

                //bubble event
                RaiseTrayContextMenuOpenEvent();
            }
        }

        #endregion

        #region Balloon Tips

        /// <summary>
        /// Bubbles events if a balloon ToolTip was displayed
        /// or removed.
        /// </summary>
        /// <param name="visible">Whether the ToolTip was just displayed
        /// or removed.</param>
        private void OnBalloonToolTipChanged(bool visible)
        {
            if (visible)
            {
                RaiseTrayBalloonTipShownEvent();
            }
            else
            {
                RaiseTrayBalloonTipClosedEvent();
            }
        }

        /// <summary>
        /// Displays a balloon tip with the specified title,
        /// text, and icon in the taskbar for the specified time period.
        /// </summary>
        /// <param name="title">The title to display on the balloon tip.</param>
        /// <param name="message">The text to display on the balloon tip.</param>
        /// <param name="symbol">A symbol that indicates the severity.</param>
        public void ShowBalloonTip(string title, string message, BalloonIcon symbol)
        {
            lock (this)
            {
                ShowBalloonTip(title, message, symbol.GetBalloonFlag(), IntPtr.Zero);
            }
        }

        /// <summary>
        /// Displays a balloon tip with the specified title,
        /// text, and a custom icon in the taskbar for the specified time period.
        /// </summary>
        /// <param name="title">The title to display on the balloon tip.</param>
        /// <param name="message">The text to display on the balloon tip.</param>
        /// <param name="customIcon">A custom icon.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="customIcon"/>
        /// is a null reference.</exception>
        public void ShowBalloonTip(string title, string message, Icon customIcon)
        {
            if (customIcon == null) throw new ArgumentNullException("customIcon");

            lock (this)
            {
                ShowBalloonTip(title, message, BalloonFlags.User, customIcon.Handle);
            }
        }

        /// <summary>
        /// Invokes <see cref="WinApi.Shell_NotifyIcon"/> in order to display
        /// a given balloon ToolTip.
        /// </summary>
        /// <param name="title">The title to display on the balloon tip.</param>
        /// <param name="message">The text to display on the balloon tip.</param>
        /// <param name="flags">Indicates what icon to use.</param>
        /// <param name="balloonIconHandle">A handle to a custom icon, if any, or
        /// <see cref="IntPtr.Zero"/>.</param>
        private void ShowBalloonTip(string title, string message, BalloonFlags flags, IntPtr balloonIconHandle)
        {
            EnsureNotDisposed();

            iconData.BalloonText = message ?? String.Empty;
            iconData.BalloonTitle = title ?? String.Empty;

            iconData.BalloonFlags = flags;
            iconData.CustomBalloonIconHandle = balloonIconHandle;
            Util.WriteIconData(ref iconData, NotifyCommand.Modify, IconDataMembers.Info | IconDataMembers.Icon);
        }

        /// <summary>
        /// Hides a balloon ToolTip, if any is displayed.
        /// </summary>
        public void HideBalloonTip()
        {
            EnsureNotDisposed();

            //reset balloon by just setting the info to an empty string
            iconData.BalloonText = iconData.BalloonTitle = String.Empty;
            Util.WriteIconData(ref iconData, NotifyCommand.Modify, IconDataMembers.Info);
        }

        #endregion

        #region Single Click Timer event

        /// <summary>
        /// Performs a delayed action if the user requested an action
        /// based on a single click of the left mouse.<br/>
        /// This method is invoked by the <see cref="singleClickTimer"/>.
        /// </summary>
        private void DoSingleClickAction(object state)
        {
            if (IsDisposed) return;

            //run action
            Action action = singleClickTimerAction;
            if (action != null)
            {
                //cleanup action
                singleClickTimerAction = null;

                //switch to UI thread
                this.GetDispatcher().Invoke(action);
            }
        }

        #endregion

        #region Set Version (API)

        /// <summary>
        /// Sets the version flag for the <see cref="iconData"/>.
        /// </summary>
        private void SetVersion()
        {
            iconData.VersionOrTimeout = (uint) NotifyIconVersion.Vista;
            bool status = WinApi.Shell_NotifyIcon(NotifyCommand.SetVersion, ref iconData);

            if (!status)
            {
                iconData.VersionOrTimeout = (uint) NotifyIconVersion.Win2000;
                status = Util.WriteIconData(ref iconData, NotifyCommand.SetVersion);
            }

            if (!status)
            {
                iconData.VersionOrTimeout = (uint) NotifyIconVersion.Win95;
                status = Util.WriteIconData(ref iconData, NotifyCommand.SetVersion);
            }

            if (!status)
            {
                Debug.Fail("Could not set version");
            }
        }

        #endregion

        #region Create / Remove Taskbar Icon

        /// <summary>
        /// Recreates the taskbar icon if the whole taskbar was
        /// recreated (e.g. because Explorer was shut down).
        /// </summary>
        private void OnTaskbarCreated()
        {
            IsTaskbarIconCreated = false;
            CreateTaskbarIcon();
        }

        /// <summary>
        /// Creates the taskbar icon. This message is invoked during initialization,
        /// if the taskbar is restarted, and whenever the icon is displayed.
        /// </summary>
        private void CreateTaskbarIcon()
        {
            lock (this)
            {
                if (!IsTaskbarIconCreated)
                {
                    const IconDataMembers members = IconDataMembers.Message
                                                    | IconDataMembers.Icon
                                                    | IconDataMembers.Tip;

                    //write initial configuration
                    var status = Util.WriteIconData(ref iconData, NotifyCommand.Add, members);
                    if (!status)
                    {
                        //couldn't create the icon - we can assume this is because explorer is not running (yet!)
                        //-> try a bit later again rather than throwing an exception. Typically, if the windows
                        // shell is being loaded later, this method is being reinvoked from OnTaskbarCreated
                        // (we could also retry after a delay, but that's currently YAGNI)
                        return;
                    }

                    //set to most recent version
                    SetVersion();
                    messageSink.Version = (NotifyIconVersion) iconData.VersionOrTimeout;

                    IsTaskbarIconCreated = true;
                }
            }
        }

        /// <summary>
        /// Closes the taskbar icon if required.
        /// </summary>
        private void RemoveTaskbarIcon()
        {
            lock (this)
            {
                //make sure we didn't schedule a creation

                if (IsTaskbarIconCreated)
                {
                    Util.WriteIconData(ref iconData, NotifyCommand.Delete, IconDataMembers.Message);
                    IsTaskbarIconCreated = false;
                }
            }
        }

        #endregion

        /// <summary>
        /// Recalculates OS coordinates in order to support WPFs coordinate
        /// system if OS scaling (DPIs) is not 100%.
        /// </summary>
        /// <param name="point"></param>
        /// <returns></returns>
        private Point GetDeviceCoordinates(Point point)
        {
            if (double.IsNaN(scalingFactor))
            {
                //calculate scaling factor in order to support non-standard DPIs
                var presentationSource = PresentationSource.FromVisual(this);
                if (presentationSource == null)
                {
                    scalingFactor = 1;
                }
                else
                {
                    var transform = presentationSource.CompositionTarget.TransformToDevice;
                    scalingFactor = 1/transform.M11;
                }
            }

            //on standard DPI settings, just return the point
            if (scalingFactor == 1.0) return point;

            return new Point() {X = (int) (point.X*scalingFactor), Y = (int) (point.Y*scalingFactor)};
        }

        #region Dispose / Exit

        /// <summary>
        /// Set to true as soon as <c>Dispose</c> has been invoked.
        /// </summary>
        public bool IsDisposed { get; private set; }

        /// <summary>
        /// Checks if the object has been disposed and
        /// raises a <see cref="ObjectDisposedException"/> in case
        /// the <see cref="IsDisposed"/> flag is true.
        /// </summary>
        private void EnsureNotDisposed()
        {
            if (IsDisposed) throw new ObjectDisposedException(Name ?? GetType().FullName);
        }

        /// <summary>
        /// Disposes the class if the application exits.
        /// </summary>
        private void OnExit(object sender, EventArgs e)
        {
            Dispose();
        }

        /// <summary>
        /// This destructor will run only if the <see cref="Dispose()"/>
        /// method does not get called. This gives this base class the
        /// opportunity to finalize.
        /// <para>
        /// Important: Do not provide destructors in types derived from
        /// this class.
        /// </para>
        /// </summary>
        ~TaskbarIcon()
        {
            Dispose(false);
        }

        /// <summary>
        /// Disposes the object.
        /// </summary>
        /// <remarks>This method is not virtual by design. Derived classes
        /// should override <see cref="Dispose(bool)"/>.
        /// </remarks>
        public void Dispose()
        {
            Dispose(true);

            // This object will be cleaned up by the Dispose method.
            // Therefore, you should call GC.SupressFinalize to
            // take this object off the finalization queue
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Closes the tray and releases all resources.
        /// </summary>
        /// <summary>
        /// <c>Dispose(bool disposing)</c> executes in two distinct scenarios.
        /// If disposing equals <c>true</c>, the method has been called directly
        /// or indirectly by a user's code. Managed and unmanaged resources
        /// can be disposed.
        /// </summary>
        /// <param name="disposing">If disposing equals <c>false</c>, the method
        /// has been called by the runtime from inside the finalizer and you
        /// should not reference other objects. Only unmanaged resources can
        /// be disposed.</param>
        /// <remarks>Check the <see cref="IsDisposed"/> property to determine whether
        /// the method has already been called.</remarks>
        private void Dispose(bool disposing)
        {
            //don't do anything if the component is already disposed
            if (IsDisposed || !disposing) return;

            lock (this)
            {
                IsDisposed = true;

                //deregister application event listener
                if (Application.Current != null)
                {
                    Application.Current.Exit -= OnExit;
                }

                //stop timers
                singleClickTimer.Dispose();
                balloonCloseTimer.Dispose();

                //dispose message sink
                messageSink.Dispose();

                //remove icon
                RemoveTaskbarIcon();
            }
        }

        #endregion
    }
}


text:
namespace device {

// static
absl::optional<AuthenticatorMakeCredentialResponse>
AuthenticatorMakeCredentialResponse::CreateFromU2fRegisterResponse(
    absl::optional<FidoTransportProtocol> transport_used,
    base::span<const uint8_t, kRpIdHashLength> relying_party_id_hash,
    base::span<const uint8_t> u2f_data) {
  auto public_key = P256PublicKey::ExtractFromU2fRegistrationResponse(
      static_cast<int32_t>(CoseAlgorithmIdentifier::kEs256), u2f_data);
  if (!public_key)
    return absl::nullopt;

  auto attested_credential_data =
      AttestedCredentialData::CreateFromU2fRegisterResponse(
          u2f_data, std::move(public_key));

  if (!attested_credential_data)
    return absl::nullopt;

  // Extract the credential_id for packing into the response data.
  std::vector<uint8_t> credential_id =
      attested_credential_data->credential_id();

  // The counter is zeroed out for Register requests.
  std::array<uint8_t, 4> counter = {};
  constexpr uint8_t flags =
      static_cast<uint8_t>(AuthenticatorData::Flag::kTestOfUserPresence) |
      static_cast<uint8_t>(AuthenticatorData::Flag::kAttestation);

  AuthenticatorData authenticator_data(relying_party_id_hash, flags, counter,
                                       std::move(attested_credential_data));

  auto fido_attestation_statement =
      FidoAttestationStatement::CreateFromU2fRegisterResponse(u2f_data);

  if (!fido_attestation_statement)
    return absl::nullopt;

  AuthenticatorMakeCredentialResponse response(
      transport_used, AttestationObject(std::move(authenticator_data),
                                        std::move(fido_attestation_statement)));
  response.is_resident_key = false;
  return response;
}

AuthenticatorMakeCredentialResponse::AuthenticatorMakeCredentialResponse(
    absl::optional<FidoTransportProtocol> in_transport_used,
    AttestationObject in_attestation_object)
    : attestation_object(std::move(in_attestation_object)),
      transport_used(in_transport_used) {}

AuthenticatorMakeCredentialResponse::AuthenticatorMakeCredentialResponse(
    AuthenticatorMakeCredentialResponse&& that) = default;

AuthenticatorMakeCredentialResponse&
AuthenticatorMakeCredentialResponse::operator=(
    AuthenticatorMakeCredentialResponse&& other) = default;

AuthenticatorMakeCredentialResponse::~AuthenticatorMakeCredentialResponse() =
    default;

std::vector<uint8_t>
AuthenticatorMakeCredentialResponse::GetCBOREncodedAttestationObject() const {
  return cbor::Writer::Write(AsCBOR(attestation_object))
      .value_or(std::vector<uint8_t>());
}

absl::optional<device::DevicePublicKeyOutput>
AuthenticatorMakeCredentialResponse::GetDevicePublicKeyResponse() const {
  const absl::optional<cbor::Value>& maybe_extensions =
      attestation_object.authenticator_data().extensions();
  if (!maybe_extensions) {
    return absl::nullopt;
  }

  DCHECK(maybe_extensions->is_map());
  const cbor::Value::MapValue& extensions = maybe_extensions->GetMap();
  const auto device_public_key_it =
      extensions.find(cbor::Value(device::kExtensionDevicePublicKey));
  if (device_public_key_it == extensions.end()) {
    return absl::nullopt;
  }

  return device::DevicePublicKeyOutput::FromExtension(
      device_public_key_it->second);
}

const std::array<uint8_t, kRpIdHashLength>&
AuthenticatorMakeCredentialResponse::GetRpIdHash() const {
  return attestation_object.rp_id_hash();
}

std::vector<uint8_t> AsCTAPStyleCBORBytes(
    const AuthenticatorMakeCredentialResponse& response) {
  const AttestationObject& object = response.attestation_object;
  cbor::Value::MapValue map;
  map.emplace(1, object.attestation_statement().format_name());
  map.emplace(2, object.authenticator_data().SerializeToByteArray());
  map.emplace(3, AsCBOR(object.attestation_statement()));
  if (response.enterprise_attestation_returned) {
    map.emplace(4, true);
  }
  if (response.large_blob_key) {
    map.emplace(5, cbor::Value(*response.large_blob_key));
  }
  if (response.device_public_key_signature.has_value()) {
    cbor::Value::MapValue unsigned_extension_outputs;
    unsigned_extension_outputs.emplace(kExtensionDevicePublicKey,
                                       *response.device_public_key_signature);
    map.emplace(6, std::move(unsigned_extension_outputs));
  }
  auto encoded_bytes = cbor::Writer::Write(cbor::Value(std::move(map)));
  DCHECK(encoded_bytes);
  return std::move(*encoded_bytes);
}

}  // namespace device


text:
function varargout = minDistancePoints(p1, varargin)
%MINDISTANCEPOINTS Minimal distance between several points
%
%   DIST = minDistancePoints(PTS)
%   Returns the minimum distance between all couple of points in PTS. PTS
%   is a N-by-D array of values, N being the number of points and D the
%   dimension of the points.
%
%   DIST = minDistancePoints(PTS1, PTS2)
%   Computes for each point in PTS1 the minimal distance to every point of
%   PTS2. PTS1 and PTS2 are N-by-D arrays, where N is the number of points,
%   and D is the dimension. Dimension must be the same for both arrays, but
%   number of points can be different.
%   The result is an array the same length as PTS1.
%
%
%   DIST = minDistancePoints(..., NORM)
%   Uses a user-specified norm. NORM=2 means euclidean norm (the default),
%   NORM=1 is the Manhattan (or "taxi-driver") distance.
%   Increasing NORM growing up reduces the minimal distance, with a limit
%   to the biggest coordinate difference among dimensions.
%
%
%   [DIST I J] = minDistancePoints(PTS)
%   Returns indices I and J of the 2 points which are the closest. DIST
%   verifies relation:
%   DIST = distancePoints(PTS(I,:), PTS(J,:));
%
%   [DIST J] = minDistancePoints(PTS1, PTS2, ...)
%   Also returns the indices of points which are the closest. J has the
%   same size as DIST. It verifies relation:
%   DIST(I) = distancePoints(PTS1(I,:), PTS2(J,:));
%   for I comprised between 1 and the number of rows in PTS1.
%
%
%   Examples:
%   % minimal distance between random planar points
%       points = rand(20,2)*100;
%       minDist = minDistancePoints(points);
%
%   % minimal distance between random space points
%       points = rand(30,3)*100;
%       [minDist ind1 ind2] = minDistancePoints(points);
%       minDist
%       distancePoints(points(ind1, :), points(ind2, :))
%   % results should be the same
%
%   % minimal distance between 2 sets of points
%       points1 = rand(30,2)*100;
%       points2 = rand(30,2)*100;
%       [minDists inds] = minDistancePoints(points1, points2);
%       minDists(10)
%       distancePoints(points1(10, :), points2(inds(10), :))
%   % results should be the same
%
%   See Also
%   points2d, distancePoints, nndist, hausdorffDistance
%
%   ---------
%   author: David Legland
%   INRA - TPV URPOI - BIA IMASTE
%   created the 15/06/2004.
%

% HISTORY:
% 22/06/2005 compute sqrt only at the end (faster), and change behaviour
%   for 2 inputs: compute min distance for each point in PTS1.
%   Also add support for different norms.
% 15/08/2005 make difference when 1 array or 2 arrays of points
% 25/10/2006 also returns indices of closest points
% 30/10/2006 generalize to points of any dimension
% 28/08/2007 code cleanup, add comments and help

%% Initialisations

% default norm (euclidean)
n = 2;

% flag for processing of all points
allPoints = false;

% process input variables
if isempty(varargin)
    % specify only one array of points, not the norm
    p2 = p1;

elseif length(varargin) == 1
    var = varargin{1};
    if length(var) > 1
        % specify two arrays of points
        p2  = var;
        allPoints = true;
    else
        % specify array of points and the norm
        n   = var;
        p2  = p1;
    end

else
    % specify two array of points and the norm
    p2  = varargin{1};
    n   = varargin{2};
    allPoints = true;
end

% number of points in each array
n1  = size(p1, 1);
n2  = size(p2, 1);

% dimension of points
d   = size(p1, 2);

%% Computation of distances

% allocate memory
dist = zeros(n1, n2);

% different behaviour depending on the norm used
if n == 2
    % Compute euclidian distance (default case).
    % Compute difference of coordinate for each pair of point and for each
    % dimension. Result "dist" is a n1-by-n2 array.
    % in 2D: dist = dx.*dx + dy.*dy;
    for i = 1:d
        dist = dist + (repmat(p1(:,i), [1 n2])-repmat(p2(:,i)', [n1 1])).^2;
    end

    % compute minimal distance:
    if ~allPoints
        % either on all couple of points
        mat = repmat((1:n1)', [1 n1]);
        ind = mat < mat';
        [minSqDist, ind] = min(dist(ind));
    else
        % or for each point of P1
        [minSqDist, ind] = min(dist, [], 2);
    end

    % convert squared distance to distance
    minDist = sqrt(minSqDist);

elseif n == inf
    % infinite norm corresponds to maximum absolute value of differences
    % in 2D: dist = max(abs(dx) + max(abs(dy));
    for i = 1:d
        dist = max(dist, abs(p1(:,i)-p2(:,i)));
    end

else
    % compute distance using the specified norm.
    % in 2D: dist = power(abs(dx), n) + power(abs(dy), n);
    for i = 1:d
        dist = dist + power((abs(repmat(p1(:,i), [1 n2])-repmat(p2(:,i)', [n1 1]))), n);
    end

    % compute minimal distance
    if ~allPoints
        % either on all couple of points
        mat = repmat((1:n1)', [1 n1]);
        ind = mat < mat';
        [minSqDist, ind] = min(dist(ind));
    else
        % or for each point of P1
        [minSqDist, ind] = min(dist, [], 2);
    end

    % convert squared distance to distance
    minDist = power(minSqDist, 1/n);

end

if ~allPoints
    % convert index in array to row and column subindices.
    % This uses the fact that index are sorted in a triangular matrix,
    % with the last index of each column being a so-called triangular
    % number
    ind2 = ceil((-1+sqrt(8*ind+1))/2);
    ind1 = ind - ind2*(ind2-1)/2;
    ind2 = ind2 + 1;
end

%% format output parameters

% format output depending on number of asked parameters
if nargout <= 1
    varargout{1} = minDist;

elseif nargout == 2
    % If two arrays are asked, 'ind' is an array of indices, one for each
    % point in PTS1, corresponding to the result in minDist
    varargout{1} = minDist;
    varargout{2} = ind;

elseif nargout == 3
    % If only one array is asked, minDist is a scalar, ind1 and ind2 are 2
    % indices corresponding to the closest points.
    varargout{1} = minDist;
    varargout{2} = ind1;
    varargout{3} = ind2;
end