<commit_before>/*************************************************************************
 *
 *  $RCSfile: parser.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:12:10 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _PARSER_HXX
#define _PARSER_HXX

#ifndef _EXPR_HXX
#include "expr.hxx"
#endif
#ifndef _CODEGEN_HXX
#include "codegen.hxx"
#endif
#ifndef _SYMTBL_HXX
#include "symtbl.hxx"
#endif

struct SbiParseStack;

class SbiParser : public SbiTokenizer
{
    SbiParseStack* pStack;          // Block-Stack
    SbiProcDef* pProc;              // aktuelle Prozedur
    SbiExprNode*  pWithVar;         // aktuelle With-Variable
    SbiToken    eEndTok;            // das Ende-Token
    USHORT      nGblChain;          // Chainkette fuer globale DIMs
    BOOL        bGblDefs;           // TRUE globale Definitionen allgemein
    BOOL        bNewGblDefs;        // TRUE globale Definitionen vor Sub
    BOOL        bSingleLineIf;      // TRUE einzeiliges if-Statement

    SbiSymDef*  VarDecl( SbiDimList**,BOOL,BOOL );// Variablen-Deklaration
    SbiProcDef* ProcDecl(BOOL bDecl);// Prozedur-Deklaration
    void DefProc( BOOL bStatic );   // Prozedur einlesen
    void DefVar( SbiOpcode eOp, BOOL bStatic ); // DIM/REDIM einlesen
    void TypeDecl( SbiSymDef& );    // AS-Deklaration
    void OpenBlock( SbiToken, SbiExprNode* = NULL );    // Block oeffnen
    void CloseBlock();              // Block aufloesen
    BOOL Channel( BOOL=FALSE );     // Kanalnummer parsen
    void StmntBlock( SbiToken );    // Statement-Block abarbeiten

public:
    SbxArrayRef   rTypeArray;       // das Type-Array
    SbiStringPool aGblStrings;      // der String-Pool
    SbiStringPool aLclStrings;      // der String-Pool
    SbiSymPool    aGlobals;         // globale Variable
    SbiSymPool    aPublics;         // modulglobale Variable
    SbiSymPool    aRtlSyms;         // Runtime-Library
    SbiCodeGen    aGen;             // Code-Generator
    StarBASIC*    pBasic;           // StarBASIC-Instanz
    SbiSymPool*   pPool;            // aktueller Pool
    SbiExprType   eCurExpr;         // aktueller Expr-Typ
    short         nBase;            // OPTION BASE-Wert
    BOOL          bText;            // OPTION COMPARE TEXT
    BOOL          bExplicit;        // TRUE: OPTION EXPLICIT
    SbxDataType   eDefTypes[26];    // DEFxxx-Datentypen

    SbiParser( StarBASIC*, SbModule* );
    BOOL Parse();                   // die Aktion
    SbiExprNode* GetWithVar();      // Innerste With-Variable liefern

    // AB 31.3.1996, Symbol in Runtime-Library suchen
    SbiSymDef* CheckRTLForSym( const String& rSym, SbxDataType eType );

    BOOL HasGlobalCode();           // Globaler Code definiert?

    BOOL TestToken( SbiToken );     // bestimmtes TOken?
    BOOL TestSymbol( BOOL=FALSE );  // Symbol?
    BOOL TestComma();               // Komma oder EOLN?
    void TestEoln();                // EOLN?

    void Symbol();                  // Let oder Call
    void ErrorStmnt();              // ERROR n
    void NotImp();                  // nicht implementiert
    void BadBlock();                // LOOP/WEND/NEXT
    void BadSyntax();               // Falsches SbiToken
    void NoIf();                    // ELSE/ELSE IF ohne IF
    void Assign();                  // LET
    void Call();                    // CALL
    void Close();                   // CLOSE
    void Declare();                 // DECLARE
    void DefXXX();                  // DEFxxx
    void Dim();                     // DIM
    void ReDim();                   // ReDim();
    void Erase();                   // ERASE
    void Exit();                    // EXIT
    void For();                     // FOR...NEXT
    void Goto();                    // GOTO / GOSUB
    void If();                      // IF
    void Input();                   // INPUT, INPUT #
    void LineInput();               // LINE INPUT, LINE INPUT #
    void LSet();                    // LSET
    void Name();                    // NAME .. AS ..
    void On();                      // ON ERROR/variable
    void OnGoto();                  // ON...GOTO / GOSUB
    void Open();                    // OPEN
    void Option();                  // OPTION
    void Print();                   // PRINT, PRINT #
    void SubFunc();                 // SUB / FUNCTION
    void Resume();                  // RESUME
    void Return();                  // RETURN
    void RSet();                    // RSET
    void DoLoop();                  // DO...LOOP
    void Select();                  // SELECT ... CASE
    void Set();                     // SET
    void Static();                  // STATIC
    void Stop();                    // STOP/SYSTEM
    void Type();                    // TYPE...AS...END TYPE
    void While();                   // WHILE/WEND
    void With();                    // WITH
    void Write();                   // WRITE

    // JavaScript-Parsing
    void OpenJavaBlock( SbiToken, SbiExprNode* = NULL );    // Block oeffnen
    void CloseJavaBlock();                                  // Block aufloesen
    void JavaStmntBlock( SbiToken );    // Statement-Block abarbeiten
    void JavaBreak();
    void JavaContinue();
    void JavaFor();
    void JavaFunction();
    void JavaIf();
    void JavaNew();
    void JavaReturn();
    void JavaThis();
    void JavaVar();
    void JavaWhile();
    void JavaWith();
};

#endif
<commit_msg>INTEGRATION: CWS jl5vba (1.1.1.1.182); FILE MERGED 2004/01/21 09:22:20 ab 1.1.1.1.182.1: #111934# Merge to src680, for tasks see message INTEGRATION: CWS ab02vba (1.1.1.1.96)<commit_after>/*************************************************************************
 *
 *  $RCSfile: parser.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-03-17 13:34:18 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _PARSER_HXX
#define _PARSER_HXX

#ifndef _EXPR_HXX
#include "expr.hxx"
#endif
#ifndef _CODEGEN_HXX
#include "codegen.hxx"
#endif
#ifndef _SYMTBL_HXX
#include "symtbl.hxx"
#endif

struct SbiParseStack;

class SbiParser : public SbiTokenizer
{
    SbiParseStack* pStack;          // Block-Stack
    SbiProcDef* pProc;              // aktuelle Prozedur
    SbiExprNode*  pWithVar;         // aktuelle With-Variable
    SbiToken    eEndTok;            // das Ende-Token
    USHORT      nGblChain;          // Chainkette fuer globale DIMs
    BOOL        bGblDefs;           // TRUE globale Definitionen allgemein
    BOOL        bNewGblDefs;        // TRUE globale Definitionen vor Sub
    BOOL        bSingleLineIf;      // TRUE einzeiliges if-Statement

    SbiSymDef*  VarDecl( SbiDimList**,BOOL,BOOL );// Variablen-Deklaration
    SbiProcDef* ProcDecl(BOOL bDecl);// Prozedur-Deklaration
    void DefStatic( BOOL bPrivate );
    void DefProc( BOOL bStatic, BOOL bPrivate ); // Prozedur einlesen
    void DefVar( SbiOpcode eOp, BOOL bStatic ); // DIM/REDIM einlesen
    void TypeDecl( SbiSymDef&, BOOL bAsNewAlreadyParsed=FALSE );    // AS-Deklaration
    void OpenBlock( SbiToken, SbiExprNode* = NULL );    // Block oeffnen
    void CloseBlock();              // Block aufloesen
    BOOL Channel( BOOL=FALSE );     // Kanalnummer parsen
    void StmntBlock( SbiToken );    // Statement-Block abarbeiten

public:
    SbxArrayRef   rTypeArray;       // das Type-Array
    SbiStringPool aGblStrings;      // der String-Pool
    SbiStringPool aLclStrings;      // der String-Pool
    SbiSymPool    aGlobals;         // globale Variable
    SbiSymPool    aPublics;         // modulglobale Variable
    SbiSymPool    aRtlSyms;         // Runtime-Library
    SbiCodeGen    aGen;             // Code-Generator
    StarBASIC*    pBasic;           // StarBASIC-Instanz
    SbiSymPool*   pPool;            // aktueller Pool
    SbiExprType   eCurExpr;         // aktueller Expr-Typ
    short         nBase;            // OPTION BASE-Wert
    BOOL          bText;            // OPTION COMPARE TEXT
    BOOL          bExplicit;        // TRUE: OPTION EXPLICIT
    SbxDataType   eDefTypes[26];    // DEFxxx-Datentypen

    SbiParser( StarBASIC*, SbModule* );
    BOOL Parse();                   // die Aktion
    SbiExprNode* GetWithVar();      // Innerste With-Variable liefern

    // AB 31.3.1996, Symbol in Runtime-Library suchen
    SbiSymDef* CheckRTLForSym( const String& rSym, SbxDataType eType );
    void AddConstants( void );

    BOOL HasGlobalCode();           // Globaler Code definiert?

    BOOL TestToken( SbiToken );     // bestimmtes TOken?
    BOOL TestSymbol( BOOL=FALSE );  // Symbol?
    BOOL TestComma();               // Komma oder EOLN?
    void TestEoln();                // EOLN?

    void Symbol();                  // Let oder Call
    void ErrorStmnt();              // ERROR n
    void NotImp();                  // nicht implementiert
    void BadBlock();                // LOOP/WEND/NEXT
    void BadSyntax();               // Falsches SbiToken
    void NoIf();                    // ELSE/ELSE IF ohne IF
    void Assign();                  // LET
    void Call();                    // CALL
    void Close();                   // CLOSE
    void Declare();                 // DECLARE
    void DefXXX();                  // DEFxxx
    void Dim();                     // DIM
    void ReDim();                   // ReDim();
    void Erase();                   // ERASE
    void Exit();                    // EXIT
    void For();                     // FOR...NEXT
    void Goto();                    // GOTO / GOSUB
    void If();                      // IF
    void Input();                   // INPUT, INPUT #
    void LineInput();               // LINE INPUT, LINE INPUT #
    void LSet();                    // LSET
    void Name();                    // NAME .. AS ..
    void On();                      // ON ERROR/variable
    void OnGoto();                  // ON...GOTO / GOSUB
    void Open();                    // OPEN
    void Option();                  // OPTION
    void Print();                   // PRINT, PRINT #
    void SubFunc();                 // SUB / FUNCTION
    void Resume();                  // RESUME
    void Return();                  // RETURN
    void RSet();                    // RSET
    void DoLoop();                  // DO...LOOP
    void Select();                  // SELECT ... CASE
    void Set();                     // SET
    void Static();                  // STATIC
    void Stop();                    // STOP/SYSTEM
    void Type();                    // TYPE...AS...END TYPE
    void While();                   // WHILE/WEND
    void With();                    // WITH
    void Write();                   // WRITE

    // JavaScript-Parsing
    void OpenJavaBlock( SbiToken, SbiExprNode* = NULL );    // Block oeffnen
    void CloseJavaBlock();                                  // Block aufloesen
    void JavaStmntBlock( SbiToken );    // Statement-Block abarbeiten
    void JavaBreak();
    void JavaContinue();
    void JavaFor();
    void JavaFunction();
    void JavaIf();
    void JavaNew();
    void JavaReturn();
    void JavaThis();
    void JavaVar();
    void JavaWhile();
    void JavaWith();
};

#endif
<|endoftext|>


<commit_before>/*
Copyright (c) 2013-2018 Ubidots.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
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.

Developed and maintained by Jose Garcia for Ubidots Inc
@jotathebest at github: https://github.com/jotathebest
*/

#include "UbiUdp.h"
#include "Particle.h"
#include "UbiConstants.h"

/**************************************************************************
 * Overloaded constructors
 ***************************************************************************/

UbiUDP::UbiUDP(const char *host, const int port, const char *user_agent,
               const char *token) {
  _host = host;
  _user_agent = user_agent;
  _token = token;
  _port = port;
}

/**************************************************************************
 * Destructor
 ***************************************************************************/

UbiUDP::~UbiUDP() {
  delete[] _host;
  delete[] _user_agent;
  delete[] _token;
  _client_udp_ubi.flush();
  _client_udp_ubi.stop();
}

bool UbiUDP::sendData(const char *device_label, const char *device_name,
                      char *payload, UbiFlags *flags) {
  /* Obtains the remote host's IP */
  IPAddress serverIpAddress = getServerIp();

  if (!serverIpAddress) {
    if (_debug) {
      Serial.println(
          "[Warning] Could not solve IP Address of the remote host, with your DNS setup. \
          \nUsing default Industrial Ubidots IP: 169.55.61.243");
    }
    serverIpAddress = IPAddress(169,55,61,243);
  }

  /* Sends data to Ubidots */
  _client_udp_ubi.setBuffer(MAX_BUFFER_SIZE + 1);  // Sets the max buffer size to send data
  _client_udp_ubi.begin(UBIDOTS_TCP_PORT);
  if (!(_client_udp_ubi.beginPacket(serverIpAddress, UBIDOTS_TCP_PORT) &&
        _client_udp_ubi.write(payload) && _client_udp_ubi.endPacket())) {
    if (_debug) {
      Serial.println("ERROR sending values with UDP");
    }
    _client_udp_ubi.stop();
    return false;
  }

  _client_udp_ubi.stop();
  return true;
}

float UbiUDP::get(const char *device_label, const char *variable_label) {
  return ERROR_VALUE;
}

/**
 * Makes available debug traces
 */

void UbiUDP::setDebug(bool debug) { _debug = debug; }

/**
 * Obtains the remote host's IP
 */

IPAddress UbiUDP::getServerIp() {
#if (PLATFORM_ID == 12 || PLATFORM_ID == 6)  // Argon(12), Photon(6)
  return = WiFi.resolve(_host);
#elif (PLATFORM_ID == 13 || PLATFORM_ID == 10)  // Boron(13), Electron(10)
  return Cellular.resolve(_host);
#else
  HAL_IPAddress ip;
  network_interface_t t;
  if (inet_gethostbyname(_host, strlen(_host), &ip, t, NULL) == 0) {
    return ip;
  }
  else {
    return IPAddress(169,55,61,243);
  }
#endif

  return IPAddress(169,55,61,243);
}
<commit_msg>fixing issue with return statement at UbiUdp<commit_after>/*
Copyright (c) 2013-2018 Ubidots.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
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.

Developed and maintained by Jose Garcia for Ubidots Inc
@jotathebest at github: https://github.com/jotathebest
*/

#include "UbiUdp.h"
#include "Particle.h"
#include "UbiConstants.h"

/**************************************************************************
 * Overloaded constructors
 ***************************************************************************/

UbiUDP::UbiUDP(const char *host, const int port, const char *user_agent,
               const char *token) {
  _host = host;
  _user_agent = user_agent;
  _token = token;
  _port = port;
}

/**************************************************************************
 * Destructor
 ***************************************************************************/

UbiUDP::~UbiUDP() {
  delete[] _host;
  delete[] _user_agent;
  delete[] _token;
  _client_udp_ubi.flush();
  _client_udp_ubi.stop();
}

bool UbiUDP::sendData(const char *device_label, const char *device_name,
                      char *payload, UbiFlags *flags) {
  /* Obtains the remote host's IP */
  IPAddress serverIpAddress = getServerIp();

  if (!serverIpAddress) {
    if (_debug) {
      Serial.println(
          "[Warning] Could not solve IP Address of the remote host, with your DNS setup. \
          \nUsing default Industrial Ubidots IP: 169.55.61.243");
    }
    serverIpAddress = IPAddress(169,55,61,243);
  }

  /* Sends data to Ubidots */
  _client_udp_ubi.setBuffer(MAX_BUFFER_SIZE + 1);  // Sets the max buffer size to send data
  _client_udp_ubi.begin(UBIDOTS_TCP_PORT);
  if (!(_client_udp_ubi.beginPacket(serverIpAddress, UBIDOTS_TCP_PORT) &&
        _client_udp_ubi.write(payload) && _client_udp_ubi.endPacket())) {
    if (_debug) {
      Serial.println("ERROR sending values with UDP");
    }
    _client_udp_ubi.stop();
    return false;
  }

  _client_udp_ubi.stop();
  return true;
}

float UbiUDP::get(const char *device_label, const char *variable_label) {
  return ERROR_VALUE;
}

/**
 * Makes available debug traces
 */

void UbiUDP::setDebug(bool debug) { _debug = debug; }

/**
 * Obtains the remote host's IP
 */

IPAddress UbiUDP::getServerIp() {
#if (PLATFORM_ID == 12 || PLATFORM_ID == 6)  // Argon(12), Photon(6)
  return WiFi.resolve(_host);
#elif (PLATFORM_ID == 13 || PLATFORM_ID == 10)  // Boron(13), Electron(10)
  return Cellular.resolve(_host);
#else
  HAL_IPAddress ip;
  network_interface_t t;
  if (inet_gethostbyname(_host, strlen(_host), &ip, t, NULL) == 0) {
    return ip;
  }
  else {
    return IPAddress(169,55,61,243);
  }
#endif

  return IPAddress(169,55,61,243);
}
<|endoftext|>


<commit_before>/**
 * @file   AddTaskFMDELoss.C
 * @author Christian Holm Christensen <cholm@dalsgaard.hehi.nbi.dk>
 * @date   Wed Mar 23 12:14:03 2011
 *
 * @brief
 *
 *
 * @ingroup pwglf_forward_scripts_tasks
 */
/**
 * @defgroup pwglf_forward_eloss Energy Loss Fits
 *
 * Fitting the energy loss @f$\Delta/\Delta_{mip}@f$ spectra
 *
 * @ingroup pwglf_forward_topical
 */

/**
 * This is the macro to include the FMD energy fitter in a train.
 *
 * @param mc      Assume MC input
 * @param useCent Use centrality information
 *
 * @return Newly created task
 *
 * @ingroup pwglf_forward_eloss
 */
AliAnalysisTask*
AddTaskFMDELoss(Bool_t mc, Bool_t useCent)
{
  // --- Load libraries ----------------------------------------------
  gROOT->LoadClass("AliAODForwardMult", "libPWGLFforward2");

  // --- Get analysis manager ----------------------------------------
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskFMDELoss", "No analysis manager to connect to.");
    return NULL;
  }

  // --- Make the task and add it to the manager ---------------------
  AliFMDEnergyFitterTask* task = new AliFMDEnergyFitterTask("fmdEnergyFitter");
  // task->SetBLow(blow);
  // task->SetBLow(bhigh);
  mgr->AddTask(task);

  // --- Set parameters on the algorithms ----------------------------
  // Set the number of SPD tracklets for which we consider the event a
  // low flux event
  task->GetEventInspector().SetLowFluxCut(1000);
  // Set the maximum error on v_z [cm]
  task->GetEventInspector().SetMaxVzErr(0.2);
  // Set the eta axis to use - note, this overrides whatever is used
  // by the rest of the algorithms - but only for the energy fitter
  // algorithm.
  task->GetEnergyFitter().SetEtaAxis(200, -4, 6);
  // Set maximum energy loss to consider
  task->GetEnergyFitter().SetMaxE(15);
  // Set number of energy loss bins
  task->GetEnergyFitter().SetNEbins(500);
  // Set whether to use increasing bin sizes
  task->GetEnergyFitter().SetUseIncreasingBins(true);
  // Set whether to do fit the energy distributions
  task->GetEnergyFitter().SetDoFits(kTRUE);
  // Set whether to make the correction object
  task->GetEnergyFitter().SetDoMakeObject(kTRUE);
  // Set the low cut used for energy
  task->GetEnergyFitter().SetLowCut(0.4);
  // Set the number of bins to subtract from maximum of distributions
  // to get the lower bound of the fit range
  task->GetEnergyFitter().SetFitRangeBinWidth(4);
  // Set the maximum number of landaus to try to fit (max 5)
  task->GetEnergyFitter().SetNParticles(5);
  // Set the minimum number of entries in the distribution before
  // trying to fit to the data
  task->GetEnergyFitter().SetMinEntries(1000);
  // --- Set limits on fits the energy -------------------------------
  // Maximum relative error on parameters
  AliFMDCorrELossFit::ELossFit::fgMaxRelError = .12;
  // Least weight to use
  AliFMDCorrELossFit::ELossFit::fgLeastWeight = 1e-5;
  // Maximum value of reduced chi^2
  AliFMDCorrELossFit::ELossFit::fgMaxChi2nu   = 20;

  // --- Make the output container and connect it --------------------
  TString outputfile = ;
  // outputfile += ":PWGLFforwardDnDeta";
  // Form(":%s",pars->GetDndetaAnalysisName());
  AliAnalysisDataContainer* histOut =
    mgr->CreateContainer("Forward", TList::Class(),
			 AliAnalysisManager::kOutputContainer,
			 AliAnalysisManager::GetCommonFileName());
  AliAnalysisDataContainer *output =
    mgr->CreateContainer("ForwardResults", TList::Class(),
			 AliAnalysisManager::kParamContainer,
			 AliAnalysisManager::GetCommonFileName());
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, histOut);
  mgr->ConnectOutput(task, 2, output);

  return task;
}
<commit_msg>Added debug option<commit_after>/**
 * @file   AddTaskFMDELoss.C
 * @author Christian Holm Christensen <cholm@dalsgaard.hehi.nbi.dk>
 * @date   Wed Mar 23 12:14:03 2011
 *
 * @brief
 *
 *
 * @ingroup pwglf_forward_scripts_tasks
 */
/**
 * @defgroup pwglf_forward_eloss Energy Loss Fits
 *
 * Fitting the energy loss @f$\Delta/\Delta_{mip}@f$ spectra
 *
 * @ingroup pwglf_forward_topical
 */

/**
 * This is the macro to include the FMD energy fitter in a train.
 *
 * @param mc      Assume MC input
 * @param useCent Use centrality information
 *
 * @return Newly created task
 *
 * @ingroup pwglf_forward_eloss
 */
AliAnalysisTask*
AddTaskFMDELoss(Bool_t mc, Bool_t useCent, Int_t debug=0)
{
  // --- Load libraries ----------------------------------------------
  gROOT->LoadClass("AliAODForwardMult", "libPWGLFforward2");

  // --- Get analysis manager ----------------------------------------
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskFMDELoss", "No analysis manager to connect to.");
    return NULL;
  }

  // --- Make the task and add it to the manager ---------------------
  AliFMDEnergyFitterTask* task = new AliFMDEnergyFitterTask("fmdEnergyFitter");
  // task->SetBLow(blow);
  // task->SetBLow(bhigh);
  mgr->AddTask(task);

  // --- Set parameters on the algorithms ----------------------------
  // Set the number of SPD tracklets for which we consider the event a
  // low flux event
  task->GetEventInspector().SetLowFluxCut(1000);
  // Set the maximum error on v_z [cm]
  task->GetEventInspector().SetMaxVzErr(0.2);
  // Set the eta axis to use - note, this overrides whatever is used
  // by the rest of the algorithms - but only for the energy fitter
  // algorithm.
  task->GetEnergyFitter().SetEtaAxis(200, -4, 6);
  // Set maximum energy loss to consider
  task->GetEnergyFitter().SetMaxE(15);
  // Set number of energy loss bins
  task->GetEnergyFitter().SetNEbins(500);
  // Set whether to use increasing bin sizes
  task->GetEnergyFitter().SetUseIncreasingBins(true);
  // Set whether to do fit the energy distributions
  task->GetEnergyFitter().SetDoFits(kTRUE);
  // Set whether to make the correction object
  task->GetEnergyFitter().SetDoMakeObject(kTRUE);
  // Set the low cut used for energy
  task->GetEnergyFitter().SetLowCut(0.4);
  // Set the number of bins to subtract from maximum of distributions
  // to get the lower bound of the fit range
  task->GetEnergyFitter().SetFitRangeBinWidth(4);
  // Set the maximum number of landaus to try to fit (max 5)
  task->GetEnergyFitter().SetNParticles(5);
  // Set the minimum number of entries in the distribution before
  // trying to fit to the data
  task->GetEnergyFitter().SetMinEntries(1000);
  // Debug
  task->SetDebug(debug);

  // --- Set limits on fits the energy -------------------------------
  // Maximum relative error on parameters
  AliFMDCorrELossFit::ELossFit::fgMaxRelError = .12;
  // Least weight to use
  AliFMDCorrELossFit::ELossFit::fgLeastWeight = 1e-5;
  // Maximum value of reduced chi^2
  AliFMDCorrELossFit::ELossFit::fgMaxChi2nu   = 20;

  // --- Make the output container and connect it --------------------
  AliAnalysisDataContainer* histOut =
    mgr->CreateContainer("Forward", TList::Class(),
			 AliAnalysisManager::kOutputContainer,
			 AliAnalysisManager::GetCommonFileName());
  AliAnalysisDataContainer *output =
    mgr->CreateContainer("ForwardResults", TList::Class(),
			 AliAnalysisManager::kParamContainer,
			 AliAnalysisManager::GetCommonFileName());
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, histOut);
  mgr->ConnectOutput(task, 2, output);

  return task;
}
<|endoftext|>


<commit_before>/* Copyright (C) 2014 - 2015  James Balamuta, Stephane Guerrier, Roberto Molinari
 *
 * This file is part of GMWM R Methods Package
 *
 * The `gmwm` R package is free software: you can redistribute it and/or modify it
 * under the terms of the Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
 * as the LICENSE file.
 *
 * The `gmwm` R package is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the Attribution-NonCommercial-ShareAlike 4.0 International
 * (CC BY-NC-SA 4.0) along with `gmwm`.  If not, see <http://www.smac-group.com/licensing/>.
 *
 */

#include <RcppArmadillo.h>
#include "dwt.h"

// We use QMF, Haar, Select filter, etc.
#include "wv_filters.h"

// We use reverse vec
#include "armadillo_manipulations.h"

/* --------------------- Start DWT and MODWT Functions --------------------- */

//' @title Discrete Wavelet Transform
//' @description Calculation of the coefficients for the discrete wavelet transformation.
//' @param x           A \code{vector} with dimensions \eqn{N\times 1}{N x 1}.
//' @param filter_name A \code{string} indicating the filter.
//' @param nlevels     An \code{integer}, \eqn{J}, indicating the level of the decomposition.
//' @param boundary    A \code{string} indicating the type of boundary method to use. Either \code{boundary="periodic"} or \code{"reflection"}.
//' @param brickwall   A \code{bool} indicating whether the a brick wall procedure should be applied to the coefficients.
//' @return y A \code{field<vec>} that contains the wavelet coefficients for each decomposition level
//' @details
//' Performs a level J decomposition of the time series using the pyramid algorithm
//' @author JJB
//' @keywords internal
//' @examples
//' set.seed(999)
//' x = rnorm(2^8)
//' dwt_cpp(x, filter_name = "haar", nlevels = 4, boundary = "periodic", brickwall = TRUE)
// [[Rcpp::export]]
arma::field<arma::vec> dwt_cpp(arma::vec x, std::string filter_name,
                                   unsigned int nlevels, std::string boundary, bool brickwall) {

  if(boundary == "periodic"){
    //
  }else if(boundary == "reflection"){
    unsigned int temp_N = x.n_elem;
    arma::vec rev_vec = reverse_vec(x);
    x.resize(2*temp_N);
    x.rows(temp_N, 2*temp_N-1) = rev_vec;
  }else{
      Rcpp::stop("The supplied 'boundary' argument is not supported! Choose either periodic or reflection.");
  }

  unsigned int N = x.n_elem;

  unsigned int J = nlevels;

  unsigned int tau = pow(2,J);

  if(double(N)/double(tau) != floor(double(N)/double(tau))){
    Rcpp::stop("The supplied sample size ('x') must be divisible by 2^(nlevels). Either truncate or expand the number of samples.");
  }
  if(tau > N){
    Rcpp::stop("The number of levels [ 2^(nlevels) ] exceeds sample size ('x'). Supply a lower number of levels.");
  }

  arma::field<arma::vec> filter_info = select_filter(filter_name);

  int L = arma::as_scalar(filter_info(0));
  arma::vec h = filter_info(1); //check the pulls
  arma::vec g = filter_info(2);

  arma::field<arma::vec> y(J);

  for(unsigned int j = 1; j <= J; j++) {

    unsigned int M = N/pow(2,(j-1));
    unsigned int M_over_2 = double(M)/2;

    arma::vec Wj(M_over_2);
    arma::vec Vj(M_over_2);

    for(unsigned t = 0; t < M_over_2; t++) {

      int u = 2*t + 1;

      double Wjt = h(0)*x(u);
      double Vjt = g(0)*x(u);

      for(int n = 1; n < L; n++){
        u -= 1;
        if(u < 0){
          u = M - 1;
        }
        Wjt += h(n)*x(u);
        Vjt += g(n)*x(u);
      }

      Wj[t] = Wjt;
      Vj[t] = Vjt;
    }

    y(j-1) = Wj;
    x = Vj;
  }

  // Apply brickwall
  if(brickwall){
    y = brick_wall(y, filter_info, "dwt");
  }

  return y;
}

//' @title Maximum Overlap Discrete Wavelet Transform
//' @description
//' Calculation of the coefficients for the discrete wavelet transformation
//' @inheritParams dwt_cpp
//' @return y A \code{field<vec>} that contains the wavelet coefficients for each decomposition level
//' @keywords internal
//' @details
//' Performs a level J decomposition of the time series using the pyramid algorithm.
//' Use this implementation to supply custom parameters instead of modwt(x),
//' which serves as a wrapper function.
//' @author JJB
//' @keywords internal
//' @examples
//' set.seed(999)
//' x = rnorm(100)
//' modwt_cpp(x, filter_name = "haar", nlevels = 4, boundary = "periodic", brickwall = TRUE)
// [[Rcpp::export]]
arma::field<arma::vec> modwt_cpp(arma::vec x, std::string filter_name,
                                   unsigned int nlevels, std::string boundary, bool brickwall){

  if(boundary == "periodic"){
    //
  }else if(boundary == "reflection"){
    unsigned int temp_N = x.n_elem;
    arma::vec rev_vec = reverse_vec(x);
    x.resize(2*temp_N);
    x.rows(temp_N, 2*temp_N-1) = rev_vec;
  }else{
    Rcpp::stop("The supplied 'boundary' argument is not supported! Choose either periodic or reflection.");
  }

  unsigned int N = x.n_elem;

  unsigned int J = nlevels;

  unsigned int tau = pow(2,J);

  if(tau > N) Rcpp::stop("The number of levels [ 2^(nlevels) ] exceeds sample size ('x'). Supply a lower number of levels.");

  arma::field<arma::vec> filter_info = select_filter(filter_name);

  int L = arma::as_scalar(filter_info(0));
  arma::vec ht = filter_info(1);
  arma::vec gt = filter_info(2);

  // modwt transform
  double transform_factor = sqrt(2);
  ht /= transform_factor;
  gt /= transform_factor;

  arma::field<arma::vec> y(J);

  arma::vec Wj(N);
  arma::vec Vj(N);

  for(unsigned int j = 1; j <= J; j++) {
    for(unsigned t = 0; t < N; t++) {

      int k = t;

      double Wjt = ht(0)*x(k);
      double Vjt = gt(0)*x(k);

      for(int n = 1; n < L; n++){
        k -= pow(2, j-1);
        if(k < 0){
          k += N;
        }
        Wjt += ht(n)*x(k);
        Vjt += gt(n)*x(k);
      }

      Wj[t] = Wjt;
      Vj[t] = Vjt;
    }

    y(j-1) = Wj;
    x = Vj;
  }

  // Apply brickwall
  if(brickwall){
   y = brick_wall(y, filter_info, "modwt");
  }

  return y;
}

//' @title Removal of Boundary Wavelet Coefficients
//' @description Removes the first n wavelet coefficients.
//' @param x           A \code{field<vec>} that contains the nlevel decomposition using either modwt or dwt.
//' @param wave_filter A \code{field<vec>} containing filter information. Only "haar" is implemented.
//' @param method      A \code{string} to describe the mode. Choose between "modwt" and "dwt"
//' @return A \code{field<vec>} with boundary modwt or dwt taken care of.
//' @keywords internal
//' @details
//' The vectors are truncated by removing the first n wavelet coefficients.
//' These vectors are then stored into the field that is returned.
//' Note: As a result, there are no NA's introduced and hence the na.omit is not needed.
//' @examples
//' x = rnorm(100)
//' me = modwt_cpp(x, filter_name = "haar", nlevels = 4, boundary = "periodic", brickwall = FALSE)
//' brick_wall(me, select_filter("haar"), "modwt")
// [[Rcpp::export]]
arma::field<arma::vec> brick_wall(arma::field<arma::vec> x,
                                  arma::field<arma::vec> wave_filter,
                                  std::string method)
{
    int m = as_scalar(wave_filter(0));

    for(unsigned int j = 0; j < x.n_elem; j++)
    {
        double binary_power = pow(2,j+1);

        unsigned int n = (binary_power - 1.0) * (m - 1.0);

        if (method == "dwt"){
            n = ceil((m - 2) * (1.0 - 1.0/binary_power));
        }
        arma::vec temp = x(j);
        unsigned int temp_size = temp.n_elem;
        n = std::min(n, temp_size);
        x(j) = temp.rows(n,temp_size-1);
    }

    return x;
}

/* -------------------------------- END DWT and MODWT Functions ---------------------- */<commit_msg>Fix on brickwall w/ extended filters for #156<commit_after>/* Copyright (C) 2014 - 2015  James Balamuta, Stephane Guerrier, Roberto Molinari
 *
 * This file is part of GMWM R Methods Package
 *
 * The `gmwm` R package is free software: you can redistribute it and/or modify it
 * under the terms of the Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
 * as the LICENSE file.
 *
 * The `gmwm` R package is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the Attribution-NonCommercial-ShareAlike 4.0 International
 * (CC BY-NC-SA 4.0) along with `gmwm`.  If not, see <http://www.smac-group.com/licensing/>.
 *
 */

#include <RcppArmadillo.h>
#include "dwt.h"

// We use QMF, Haar, Select filter, etc.
#include "wv_filters.h"

// We use reverse vec
#include "armadillo_manipulations.h"

/* --------------------- Start DWT and MODWT Functions --------------------- */

//' @title Discrete Wavelet Transform
//' @description Calculation of the coefficients for the discrete wavelet transformation.
//' @param x           A \code{vector} with dimensions \eqn{N\times 1}{N x 1}.
//' @param filter_name A \code{string} indicating the filter.
//' @param nlevels     An \code{integer}, \eqn{J}, indicating the level of the decomposition.
//' @param boundary    A \code{string} indicating the type of boundary method to use. Either \code{boundary="periodic"} or \code{"reflection"}.
//' @param brickwall   A \code{bool} indicating whether the a brick wall procedure should be applied to the coefficients.
//' @return y A \code{field<vec>} that contains the wavelet coefficients for each decomposition level
//' @details
//' Performs a level J decomposition of the time series using the pyramid algorithm
//' @author JJB
//' @keywords internal
//' @examples
//' set.seed(999)
//' x = rnorm(2^8)
//' dwt_cpp(x, filter_name = "haar", nlevels = 4, boundary = "periodic", brickwall = TRUE)
// [[Rcpp::export]]
arma::field<arma::vec> dwt_cpp(arma::vec x, std::string filter_name,
                                   unsigned int nlevels, std::string boundary, bool brickwall) {

  if(boundary == "periodic"){
    //
  }else if(boundary == "reflection"){
    unsigned int temp_N = x.n_elem;
    arma::vec rev_vec = reverse_vec(x);
    x.resize(2*temp_N);
    x.rows(temp_N, 2*temp_N-1) = rev_vec;
  }else{
      Rcpp::stop("The supplied 'boundary' argument is not supported! Choose either periodic or reflection.");
  }

  unsigned int N = x.n_elem;

  unsigned int J = nlevels;

  unsigned int tau = pow(2,J);

  if(double(N)/double(tau) != floor(double(N)/double(tau))){
    Rcpp::stop("The supplied sample size ('x') must be divisible by 2^(nlevels). Either truncate or expand the number of samples.");
  }
  if(tau > N){
    Rcpp::stop("The number of levels [ 2^(nlevels) ] exceeds sample size ('x'). Supply a lower number of levels.");
  }

  arma::field<arma::vec> filter_info = select_filter(filter_name);

  int L = arma::as_scalar(filter_info(0));
  arma::vec h = filter_info(1); //check the pulls
  arma::vec g = filter_info(2);

  arma::field<arma::vec> y(J);

  for(unsigned int j = 1; j <= J; j++) {

    unsigned int M = N/pow(2,(j-1));
    unsigned int M_over_2 = double(M)/2;

    arma::vec Wj(M_over_2);
    arma::vec Vj(M_over_2);

    for(unsigned t = 0; t < M_over_2; t++) {

      int u = 2*t + 1;

      double Wjt = h(0)*x(u);
      double Vjt = g(0)*x(u);

      for(int n = 1; n < L; n++){
        u -= 1;
        if(u < 0){
          u = M - 1;
        }
        Wjt += h(n)*x(u);
        Vjt += g(n)*x(u);
      }

      Wj[t] = Wjt;
      Vj[t] = Vjt;
    }

    y(j-1) = Wj;
    x = Vj;
  }

  // Apply brickwall
  if(brickwall){
    y = brick_wall(y, filter_info, "dwt");
  }

  return y;
}

//' @title Maximum Overlap Discrete Wavelet Transform
//' @description
//' Calculation of the coefficients for the discrete wavelet transformation
//' @inheritParams dwt_cpp
//' @return y A \code{field<vec>} that contains the wavelet coefficients for each decomposition level
//' @keywords internal
//' @details
//' Performs a level J decomposition of the time series using the pyramid algorithm.
//' Use this implementation to supply custom parameters instead of modwt(x),
//' which serves as a wrapper function.
//' @author JJB
//' @keywords internal
//' @examples
//' set.seed(999)
//' x = rnorm(100)
//' modwt_cpp(x, filter_name = "haar", nlevels = 4, boundary = "periodic", brickwall = TRUE)
// [[Rcpp::export]]
arma::field<arma::vec> modwt_cpp(arma::vec x, std::string filter_name,
                                   unsigned int nlevels, std::string boundary, bool brickwall){

  if(boundary == "periodic"){
    //
  }else if(boundary == "reflection"){
    unsigned int temp_N = x.n_elem;
    arma::vec rev_vec = reverse_vec(x);
    x.resize(2*temp_N);
    x.rows(temp_N, 2*temp_N-1) = rev_vec;
  }else{
    Rcpp::stop("The supplied 'boundary' argument is not supported! Choose either periodic or reflection.");
  }

  unsigned int N = x.n_elem;

  unsigned int J = nlevels;

  unsigned int tau = pow(2,J);

  if(tau > N) Rcpp::stop("The number of levels [ 2^(nlevels) ] exceeds sample size ('x'). Supply a lower number of levels.");

  arma::field<arma::vec> filter_info = select_filter(filter_name);

  int L = arma::as_scalar(filter_info(0));
  arma::vec ht = filter_info(1);
  arma::vec gt = filter_info(2);

  // modwt transform
  double transform_factor = sqrt(2);
  ht /= transform_factor;
  gt /= transform_factor;

  arma::field<arma::vec> y(J);

  arma::vec Wj(N);
  arma::vec Vj(N);

  for(unsigned int j = 1; j <= J; j++) {
    for(unsigned t = 0; t < N; t++) {

      int k = t;

      double Wjt = ht(0)*x(k);
      double Vjt = gt(0)*x(k);

      for(int n = 1; n < L; n++){
        k -= pow(2, j-1);
        if(k < 0){
          k += N;
        }
        Wjt += ht(n)*x(k);
        Vjt += gt(n)*x(k);
      }

      Wj[t] = Wjt;
      Vj[t] = Vjt;
    }

    y(j-1) = Wj;
    x = Vj;
  }

  // Apply brickwall
  if(brickwall){
   y = brick_wall(y, filter_info, "modwt");
  }

  return y;
}

//' @title Removal of Boundary Wavelet Coefficients
//' @description Removes the first n wavelet coefficients.
//' @param x           A \code{field<vec>} that contains the nlevel decomposition using either modwt or dwt.
//' @param wave_filter A \code{field<vec>} containing filter information. Only "haar" is implemented.
//' @param method      A \code{string} to describe the mode. Choose between "modwt" and "dwt"
//' @return A \code{field<vec>} with boundary modwt or dwt taken care of.
//' @keywords internal
//' @details
//' The vectors are truncated by removing the first n wavelet coefficients.
//' These vectors are then stored into the field that is returned.
//' Note: As a result, there are no NA's introduced and hence the na.omit is not needed.
//' @examples
//' x = rnorm(100)
//' me = modwt_cpp(x, filter_name = "haar", nlevels = 4, boundary = "periodic", brickwall = FALSE)
//' brick_wall(me, select_filter("haar"), "modwt")
// [[Rcpp::export]]
arma::field<arma::vec> brick_wall(arma::field<arma::vec> x,
                                  arma::field<arma::vec> wave_filter,
                                  std::string method)
{
    int m = as_scalar(wave_filter(0));

    for(unsigned int j = 0; j < x.n_elem; j++)
    {
        double binary_power = pow(2.0,double(j)+1.0);

        int n = (binary_power - 1.0) * (m - 1.0);

        if (method == "dwt"){
            n = ceil((m - 2.0) * (1.0 - 1.0/binary_power));
        }
        arma::vec temp = x(j);
        int temp_size = temp.n_elem;
        n = std::min(n, temp_size-1);

        // Addresses the case where all scales are removed.
        if(n != (temp_size-1)){
          x(j) = temp.rows(n,temp_size-1);
        }else{
          x(j) = arma::zeros<arma::vec>(0);
        }
    }

    return x;
}

/* -------------------------------- END DWT and MODWT Functions ---------------------- */<|endoftext|>


<commit_before>#include "atlas/tools/MayaCamera.hpp"
#include "atlas/core/Float.hpp"

namespace atlas
{
    namespace tools
    {
        struct MayaCamera::MayaCameraImpl
        {
            MayaCameraImpl() :
                position(30),
                target(0),
                up(0, 1, 0),
                azimuthTarget(target),
                tumble(1.0f),
                fov(45.0f)
            { }

            atlas::math::Matrix4 computeViewMatrix()
            {
                return glm::lookAt(position, target, up) * tumble;
            }

            void reset()
            {
                position = { 30, 30, 30 };
                target = { 0, 0, 0 };
                azimuthTarget = target;
                up = { 0, 1, 0 };
                tumble = glm::mat4(1.0f);
                fov = 45.0f;
            }

            atlas::math::Point position;
            atlas::math::Point target;
            atlas::math::Vector up;
            atlas::math::Point azimuthTarget;
            atlas::math::Matrix4 tumble;
            float fov;

            atlas::math::Point2 lastPos;
            MayaMovements movement;
        };

        MayaCamera::MayaCamera() :
            mImpl(std::make_unique<MayaCameraImpl>())
        { }

        MayaCamera::~MayaCamera()
        { }

        void MayaCamera::mouseDown(atlas::math::Point2 const& point)
        {
            mImpl->lastPos = point;
        }

        void MayaCamera::mouseMove(atlas::math::Point2 const& point)
        {
            auto delta = point - mImpl->lastPos;

            switch (mImpl->movement)
            {
            case MayaMovements::Dolly:
            {
                delta *= -0.5f;

                auto view = glm::normalize(mImpl->position - mImpl->target);

                mImpl->position += (view * delta.x);
                mImpl->target += (view * delta.x);
                break;
            }

            case MayaMovements::Track:
            {
                delta *= 0.05f;

                // Compute the full frame.
                auto view = glm::normalize(mImpl->position - mImpl->target);
                auto right = glm::normalize(glm::cross(mImpl->up, view));
                auto up = glm::cross(view, right);

                right *= -delta.x;
                up *= delta.y;

                mImpl->position += (right + up);
                mImpl->target += (right + up);
                mImpl->azimuthTarget += (right + up);
                break;
            }

            case MayaMovements::Tumble:
            {
                delta *= 0.5f;

                // Compute the full frame.
                auto view = glm::normalize(mImpl->position - mImpl->target);
                auto right = glm::normalize(glm::cross(mImpl->up, view));
                auto up = glm::cross(view, right);

                auto target = math::Vector(0, 0, 0);
                auto azimuth =
                    glm::translate(glm::mat4(1.0f), mImpl->azimuthTarget) *
                    glm::rotate(glm::mat4(1.0f), glm::radians(delta.x),
                        glm::vec3(0, 1, 0)) *
                    glm::translate(glm::mat4(1.0f), -mImpl->azimuthTarget);

                auto elevation =
                    glm::translate(glm::mat4(1.0f), target) *
                    glm::rotate(glm::mat4(1.0f), glm::radians(delta.y), right) *
                    glm::translate(glm::mat4(1.0f), -target);

                mImpl->tumble = elevation * mImpl->tumble * azimuth;
                break;
            }

            case MayaMovements::None:
            {
                break;
            }
            }

            mImpl->lastPos = point;
        }

        void MayaCamera::mouseUp()
        {
            mImpl->movement = MayaMovements::None;
        }

        void MayaCamera::mouseScroll(atlas::math::Point2 const& offset)
        {
            if (core::geq(mImpl->fov, 1.0f) && core::leq(mImpl->fov, 45.0f))
            {
                mImpl->fov -= offset.y;
            }

            mImpl->fov = (core::leq(mImpl->fov, 1.0f)) ? 1.0f : mImpl->fov;
            mImpl->fov = (core::geq(mImpl->fov, 45.0f)) ? 45.0f : mImpl->fov;
        }

        void MayaCamera::resetCamera()
        {
            mImpl->reset();
        }

        void MayaCamera::setMovement(MayaMovements movement)
        {
            mImpl->movement = movement;
        }

        atlas::math::Point MayaCamera::getCameraPosition() const
        {
            return mImpl->position;
        }

        void MayaCamera::setCameraPosition(atlas::math::Point const& pos)
        {
            mImpl->position = pos;
        }

        atlas::math::Matrix4 MayaCamera::getCameraMatrix() const
        {
            return mImpl->computeViewMatrix();
        }

        float MayaCamera::getCameraFOV() const
        {
            return mImpl->fov;
        }
    }
}<commit_msg>[brief] Removes unused up variable.<commit_after>#include "atlas/tools/MayaCamera.hpp"
#include "atlas/core/Float.hpp"

namespace atlas
{
    namespace tools
    {
        struct MayaCamera::MayaCameraImpl
        {
            MayaCameraImpl() :
                position(30),
                target(0),
                up(0, 1, 0),
                azimuthTarget(target),
                tumble(1.0f),
                fov(45.0f)
            { }

            atlas::math::Matrix4 computeViewMatrix()
            {
                return glm::lookAt(position, target, up) * tumble;
            }

            void reset()
            {
                position = { 30, 30, 30 };
                target = { 0, 0, 0 };
                azimuthTarget = target;
                up = { 0, 1, 0 };
                tumble = glm::mat4(1.0f);
                fov = 45.0f;
            }

            atlas::math::Point position;
            atlas::math::Point target;
            atlas::math::Vector up;
            atlas::math::Point azimuthTarget;
            atlas::math::Matrix4 tumble;
            float fov;

            atlas::math::Point2 lastPos;
            MayaMovements movement;
        };

        MayaCamera::MayaCamera() :
            mImpl(std::make_unique<MayaCameraImpl>())
        { }

        MayaCamera::~MayaCamera()
        { }

        void MayaCamera::mouseDown(atlas::math::Point2 const& point)
        {
            mImpl->lastPos = point;
        }

        void MayaCamera::mouseMove(atlas::math::Point2 const& point)
        {
            auto delta = point - mImpl->lastPos;

            switch (mImpl->movement)
            {
            case MayaMovements::Dolly:
            {
                delta *= -0.5f;

                auto view = glm::normalize(mImpl->position - mImpl->target);

                mImpl->position += (view * delta.x);
                mImpl->target += (view * delta.x);
                break;
            }

            case MayaMovements::Track:
            {
                delta *= 0.05f;

                // Compute the full frame.
                auto view = glm::normalize(mImpl->position - mImpl->target);
                auto right = glm::normalize(glm::cross(mImpl->up, view));
                auto up = glm::cross(view, right);

                right *= -delta.x;
                up *= delta.y;

                mImpl->position += (right + up);
                mImpl->target += (right + up);
                mImpl->azimuthTarget += (right + up);
                break;
            }

            case MayaMovements::Tumble:
            {
                delta *= 0.5f;

                // Compute the full frame.
                auto view = glm::normalize(mImpl->position - mImpl->target);
                auto right = glm::normalize(glm::cross(mImpl->up, view));

                auto target = math::Vector(0, 0, 0);
                auto azimuth =
                    glm::translate(glm::mat4(1.0f), mImpl->azimuthTarget) *
                    glm::rotate(glm::mat4(1.0f), glm::radians(delta.x),
                        glm::vec3(0, 1, 0)) *
                    glm::translate(glm::mat4(1.0f), -mImpl->azimuthTarget);

                auto elevation =
                    glm::translate(glm::mat4(1.0f), target) *
                    glm::rotate(glm::mat4(1.0f), glm::radians(delta.y), right) *
                    glm::translate(glm::mat4(1.0f), -target);

                mImpl->tumble = elevation * mImpl->tumble * azimuth;
                break;
            }

            case MayaMovements::None:
            {
                break;
            }
            }

            mImpl->lastPos = point;
        }

        void MayaCamera::mouseUp()
        {
            mImpl->movement = MayaMovements::None;
        }

        void MayaCamera::mouseScroll(atlas::math::Point2 const& offset)
        {
            if (core::geq(mImpl->fov, 1.0f) && core::leq(mImpl->fov, 45.0f))
            {
                mImpl->fov -= offset.y;
            }

            mImpl->fov = (core::leq(mImpl->fov, 1.0f)) ? 1.0f : mImpl->fov;
            mImpl->fov = (core::geq(mImpl->fov, 45.0f)) ? 45.0f : mImpl->fov;
        }

        void MayaCamera::resetCamera()
        {
            mImpl->reset();
        }

        void MayaCamera::setMovement(MayaMovements movement)
        {
            mImpl->movement = movement;
        }

        atlas::math::Point MayaCamera::getCameraPosition() const
        {
            return mImpl->position;
        }

        void MayaCamera::setCameraPosition(atlas::math::Point const& pos)
        {
            mImpl->position = pos;
        }

        atlas::math::Matrix4 MayaCamera::getCameraMatrix() const
        {
            return mImpl->computeViewMatrix();
        }

        float MayaCamera::getCameraFOV() const
        {
            return mImpl->fov;
        }
    }
}<|endoftext|>


<commit_before>#include "family_mask.h"

using namespace Halley;

FamilyMask::Handle::Handle()
	: value(0)
{
}

FamilyMask::Handle::Handle(const Handle& h)
	: value(h.value)
{
}

FamilyMask::Handle::Handle(Handle&& h)
	: value(h.value)
{
}

FamilyMask::Handle::Handle(const RealType& mask)
	: value(mask)
{
}

FamilyMask::Handle::Handle(RealType&& mask)
	: value(mask)
{
}

void FamilyMask::Handle::operator=(const Handle& h)
{
	value = h.value;
}

bool FamilyMask::Handle::operator==(const Handle& h) const
{
	return value == h.value;
}

bool FamilyMask::Handle::operator!=(const Handle& h) const
{
	return value != h.value;
}

bool FamilyMask::Handle::operator<(const Handle& h) const
{
	return value < h.value;
}

FamilyMask::Handle FamilyMask::Handle::operator&(const Handle& h) const
{
	return Handle(value & h.value);
}

const FamilyMask::RealType& FamilyMask::Handle::getRealValue() const
{
	return value;
}

FamilyMask::HandleType FamilyMask::getHandle(RealType mask)
{
	return Handle(mask);
}
<commit_msg>WIP handle for masks...<commit_after>#include "family_mask.h"
#include <set>

using namespace Halley;
using namespace FamilyMask;

struct MaskEntry
{
	RealType mask;
	int idx;

	MaskEntry(MaskEntry&& o)
		: mask(std::move(o.mask))
		, idx(o.idx)
	{}

	MaskEntry(const RealType& m, int i)
		: mask(m)
		, idx(i)
	{}

	bool operator<(const MaskEntry& o) const {
		return mask < o.mask;
	}

	bool operator==(const MaskEntry& o) const {
		return mask == o.mask;
	}
};

class MaskStorage
{
public:
	static MaskStorage& getInstance()
	{
		static MaskStorage* i = nullptr;
		if (!i) {
			i = new MaskStorage();
		}
		return *i;
	}

	std::vector<MaskEntry*> values;
	std::set<MaskEntry> entries;

	static int getHandle(RealType& value)
	{
		auto& instance = getInstance();
		auto entry = MaskEntry(value, 0);
		auto i = instance.entries.find(entry);
		if (i == instance.entries.end()) {
			// Not found
			entry.idx = static_cast<int>(instance.values.size());
			auto result = instance.entries.insert(std::move(entry));
			instance.values.push_back(const_cast<MaskEntry*>(&*result.first));
			return entry.idx;
		} else {
			// Found
			return i->idx;
		}
	}

	static RealType& retrieve(int handle)
	{
		return getInstance().values[handle]->mask;
	}
};

Handle::Handle()
	: value(0)
{
}

Handle::Handle(const Handle& h)
	: value(h.value)
{
}

Handle::Handle(Handle&& h)
	: value(h.value)
{
}

Handle::Handle(const RealType& mask)
	: value(mask)
{
}

Handle::Handle(RealType&& mask)
	: value(mask)
{
}

void Handle::operator=(const Handle& h)
{
	value = h.value;
}

bool Handle::operator==(const Handle& h) const
{
	return value == h.value;
}

bool Handle::operator!=(const Handle& h) const
{
	return value != h.value;
}

bool Handle::operator<(const Handle& h) const
{
	return value < h.value;
}

Handle Handle::operator&(const Handle& h) const
{
	return Handle(value & h.value);
}

const RealType& Handle::getRealValue() const
{
	return value;
}

HandleType FamilyMask::getHandle(RealType mask)
{
	return Handle(mask);
}
<|endoftext|>


<commit_before>#include "SshSetupHandler.hpp"

#include <sys/wait.h>

namespace et {
string genRandom(int len) {
  static const char alphanum[] =
      "0123456789"
      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
      "abcdefghijklmnopqrstuvwxyz";
  string s(len, '\0');

  for (int i = 0; i < len; ++i) {
    s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
  }

  return s;
}

string SshSetupHandler::SetupSsh(string user, string host, string host_alias,
                                 int port, string jumphost, int jport,
                                 bool kill) {
  string CLIENT_TERM(getenv("TERM"));
  string passkey = genRandom(32);
  string id = genRandom(16);
  string SSH_SCRIPT_PREFIX{
      "SERVER_TMP_DIR=${TMPDIR:-${TMP:-${TEMP:-/tmp}}};"
      "TMPFILE=$(mktemp $SERVER_TMP_DIR/et-server.XXXXXXXXXXXX);"
      "PASSKEY=" +
      passkey +
      ";"
      "ID=" +
      id +
      ";"
      "printf \"%s/%s\\n\" \"$ID\" \"$PASSKEY\" > \"${TMPFILE}\";"
      "export TERM=" +
      CLIENT_TERM +
      ";"
      "etserver --idpasskeyfile=\"${TMPFILE}\""};

  // Kill old ET sessions of the user
  if (kill && user != "root") {
    SSH_SCRIPT_PREFIX = "pkill etserver -u " + user + ";" + SSH_SCRIPT_PREFIX;
  }
  string SSH_SCRIPT_DST = SSH_SCRIPT_PREFIX + ";true";

  int link_client[2];
  char buf_client[4096];
  if (pipe(link_client) == -1) {
    LOG(FATAL) << "pipe";
    exit(1);
  }

  pid_t pid = fork();
  string SSH_USER_PREFIX = "";
  if (!user.empty()) {
    SSH_USER_PREFIX += user + "@";
  }
  if (!pid) {
    // start etserver daemon on dst.
    dup2(link_client[1], 1);
    close(link_client[0]);
    close(link_client[1]);
    // run the command in interactive mode
    SSH_SCRIPT_DST = "$SHELL -lc \'" + SSH_SCRIPT_DST + "\'";
    if (!jumphost.empty()) {
      execlp("ssh", "ssh", "-J", (SSH_USER_PREFIX + jumphost).c_str(),
             (SSH_USER_PREFIX + host_alias).c_str(), (SSH_SCRIPT_DST).c_str(),
             NULL);
    } else {
      execlp("ssh", "ssh", (SSH_USER_PREFIX + host_alias).c_str(),
             SSH_SCRIPT_DST.c_str(), NULL);
    }

    LOG(INFO) << "execl error";
    exit(1);
  } else if (pid < 0) {
    LOG(INFO) << "Failed to fork";
    exit(1);
  } else {
    close(link_client[1]);
    wait(NULL);
    int nbytes = read(link_client[0], buf_client, sizeof(buf_client));
    try {
      if (nbytes <= 0 || split(string(buf_client), ':').size() != 2 ||
          split(string(buf_client), ':')[0] != "IDPASSKEY") {
        cout << "Error:  The Eternal Terminal daemon is not running.  "
                "Please (re)start the et daemon on the server."
             << endl;
        exit(1);
      }
      auto idpasskey = split(string(buf_client), ':')[1];
      idpasskey = idpasskey.substr(0, 16 + 1 + 32);
      auto idpasskey_splited = split(idpasskey, '/');
      string returned_id = idpasskey_splited[0];
      string returned_passkey = idpasskey_splited[1];
      if (returned_id == id && returned_passkey == passkey) {
        LOG(INFO) << "etserver started";
      } else {
        LOG(FATAL) << "client/server idpasskey doesn't match: " << id
                   << " != " << returned_id << " or " << passkey
                   << " != " << returned_passkey;
      }
    } catch (const runtime_error &err) {
      cout << "Error initializing connection" << err.what() << endl;
    }
    // start jumpclient daemon on jumphost.
    if (!jumphost.empty()) {
      /* If jumphost is set, we need to pass dst host and port to jumphost
       * and connect to jumphost here */
      int link_jump[2];
      char buf_jump[4096];
      if (pipe(link_jump) == -1) {
        LOG(FATAL) << "pipe";
        exit(1);
      }
      pid_t pid_jump = fork();
      if (pid_jump < 0) {
        LOG(FATAL) << "Failed to fork";
        exit(1);
      } else if (pid_jump == 0) {
        dup2(link_jump[1], 1);
        close(link_jump[0]);
        close(link_jump[1]);
        string cmdoptions = "";
        cmdoptions +=
            " --jump --dsthost=" + host + " --dstport=" + to_string(port);
        string SSH_SCRIPT_JUMP = SSH_SCRIPT_PREFIX + cmdoptions + ";true";
        // start command in interactive mode
        SSH_SCRIPT_JUMP = "$SHELL -lc \'" + SSH_SCRIPT_JUMP + "\'";
        execlp("ssh", "ssh", jumphost.c_str(), SSH_SCRIPT_JUMP.c_str(), NULL);
      } else {
        close(link_jump[1]);
        wait(NULL);
        int nbytes = read(link_jump[0], buf_jump, sizeof(buf_jump));
        if (nbytes <= 0) {
          LOG(FATAL) << "etserver jumpclient failed to start";
          exit(1);
        }
        try {
          auto idpasskey = split(string(buf_jump), ':')[1];
          idpasskey.erase(idpasskey.find_last_not_of(" \n\r\t") + 1);
          idpasskey = idpasskey.substr(0, 16 + 1 + 32);
          auto idpasskey_splited = split(idpasskey, '/');
          string returned_id = idpasskey_splited[0];
          string returned_passkey = idpasskey_splited[1];
          if (returned_id == id && returned_passkey == passkey) {
            LOG(INFO) << "jump client started.";
          } else {
            LOG(INFO) << "ID " << id;
            LOG(INFO) << "Received ID " << returned_id;
            LOG(INFO) << "PASSKEY " << passkey;
            LOG(INFO) << "Received PASSKEY " << returned_passkey;
            LOG(INFO) << "client/server idpasskey doesn't match";
            exit(1);
          }
        } catch (const runtime_error &err) {
          cout << "Error initializing connection" << err.what() << endl;
        }
      }
    }
  }
  return id + "/" + passkey;
}
}  // namespace et
<commit_msg>seed rng for generating id/passkey pairs<commit_after>#include "SshSetupHandler.hpp"

#include <sys/wait.h>

namespace et {
string genRandom(int len) {
  static const char alphanum[] =
      "0123456789"
      "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
      "abcdefghijklmnopqrstuvwxyz";
  string s(len, '\0');

  for (int i = 0; i < len; ++i) {
    s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
  }

  return s;
}

string SshSetupHandler::SetupSsh(string user, string host, string host_alias,
                                 int port, string jumphost, int jport,
                                 bool kill) {
  string CLIENT_TERM(getenv("TERM"));
  srand(time(NULL));
  string passkey = genRandom(32);
  string id = genRandom(16);
  string SSH_SCRIPT_PREFIX{
      "SERVER_TMP_DIR=${TMPDIR:-${TMP:-${TEMP:-/tmp}}};"
      "TMPFILE=$(mktemp $SERVER_TMP_DIR/et-server.XXXXXXXXXXXX);"
      "PASSKEY=" +
      passkey +
      ";"
      "ID=" +
      id +
      ";"
      "printf \"%s/%s\\n\" \"$ID\" \"$PASSKEY\" > \"${TMPFILE}\";"
      "export TERM=" +
      CLIENT_TERM +
      ";"
      "etserver --idpasskeyfile=\"${TMPFILE}\""};

  // Kill old ET sessions of the user
  if (kill && user != "root") {
    SSH_SCRIPT_PREFIX = "pkill etserver -u " + user + ";" + SSH_SCRIPT_PREFIX;
  }
  string SSH_SCRIPT_DST = SSH_SCRIPT_PREFIX + ";true";

  int link_client[2];
  char buf_client[4096];
  if (pipe(link_client) == -1) {
    LOG(FATAL) << "pipe";
    exit(1);
  }

  pid_t pid = fork();
  string SSH_USER_PREFIX = "";
  if (!user.empty()) {
    SSH_USER_PREFIX += user + "@";
  }
  if (!pid) {
    // start etserver daemon on dst.
    dup2(link_client[1], 1);
    close(link_client[0]);
    close(link_client[1]);
    // run the command in interactive mode
    SSH_SCRIPT_DST = "$SHELL -lc \'" + SSH_SCRIPT_DST + "\'";
    if (!jumphost.empty()) {
      execlp("ssh", "ssh", "-J", (SSH_USER_PREFIX + jumphost).c_str(),
             (SSH_USER_PREFIX + host_alias).c_str(), (SSH_SCRIPT_DST).c_str(),
             NULL);
    } else {
      execlp("ssh", "ssh", (SSH_USER_PREFIX + host_alias).c_str(),
             SSH_SCRIPT_DST.c_str(), NULL);
    }

    LOG(INFO) << "execl error";
    exit(1);
  } else if (pid < 0) {
    LOG(INFO) << "Failed to fork";
    exit(1);
  } else {
    close(link_client[1]);
    wait(NULL);
    int nbytes = read(link_client[0], buf_client, sizeof(buf_client));
    try {
      if (nbytes <= 0 || split(string(buf_client), ':').size() != 2 ||
          split(string(buf_client), ':')[0] != "IDPASSKEY") {
        cout << "Error:  The Eternal Terminal daemon is not running.  "
                "Please (re)start the et daemon on the server."
             << endl;
        exit(1);
      }
      auto idpasskey = split(string(buf_client), ':')[1];
      idpasskey = idpasskey.substr(0, 16 + 1 + 32);
      auto idpasskey_splited = split(idpasskey, '/');
      string returned_id = idpasskey_splited[0];
      string returned_passkey = idpasskey_splited[1];
      if (returned_id == id && returned_passkey == passkey) {
        LOG(INFO) << "etserver started";
      } else {
        LOG(FATAL) << "client/server idpasskey doesn't match: " << id
                   << " != " << returned_id << " or " << passkey
                   << " != " << returned_passkey;
      }
    } catch (const runtime_error &err) {
      cout << "Error initializing connection" << err.what() << endl;
    }
    // start jumpclient daemon on jumphost.
    if (!jumphost.empty()) {
      /* If jumphost is set, we need to pass dst host and port to jumphost
       * and connect to jumphost here */
      int link_jump[2];
      char buf_jump[4096];
      if (pipe(link_jump) == -1) {
        LOG(FATAL) << "pipe";
        exit(1);
      }
      pid_t pid_jump = fork();
      if (pid_jump < 0) {
        LOG(FATAL) << "Failed to fork";
        exit(1);
      } else if (pid_jump == 0) {
        dup2(link_jump[1], 1);
        close(link_jump[0]);
        close(link_jump[1]);
        string cmdoptions = "";
        cmdoptions +=
            " --jump --dsthost=" + host + " --dstport=" + to_string(port);
        string SSH_SCRIPT_JUMP = SSH_SCRIPT_PREFIX + cmdoptions + ";true";
        // start command in interactive mode
        SSH_SCRIPT_JUMP = "$SHELL -lc \'" + SSH_SCRIPT_JUMP + "\'";
        execlp("ssh", "ssh", jumphost.c_str(), SSH_SCRIPT_JUMP.c_str(), NULL);
      } else {
        close(link_jump[1]);
        wait(NULL);
        int nbytes = read(link_jump[0], buf_jump, sizeof(buf_jump));
        if (nbytes <= 0) {
          LOG(FATAL) << "etserver jumpclient failed to start";
          exit(1);
        }
        try {
          auto idpasskey = split(string(buf_jump), ':')[1];
          idpasskey.erase(idpasskey.find_last_not_of(" \n\r\t") + 1);
          idpasskey = idpasskey.substr(0, 16 + 1 + 32);
          auto idpasskey_splited = split(idpasskey, '/');
          string returned_id = idpasskey_splited[0];
          string returned_passkey = idpasskey_splited[1];
          if (returned_id == id && returned_passkey == passkey) {
            LOG(INFO) << "jump client started.";
          } else {
            LOG(INFO) << "ID " << id;
            LOG(INFO) << "Received ID " << returned_id;
            LOG(INFO) << "PASSKEY " << passkey;
            LOG(INFO) << "Received PASSKEY " << returned_passkey;
            LOG(INFO) << "client/server idpasskey doesn't match";
            exit(1);
          }
        } catch (const runtime_error &err) {
          cout << "Error initializing connection" << err.what() << endl;
        }
      }
    }
  }
  return id + "/" + passkey;
}
}  // namespace et
<|endoftext|>


<commit_before>
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
//   Cedric Nugteren <www.cedricnugteren.nl>
//
// This file implements the Routine base class (see the header for information about the class).
//
// =================================================================================================

#include <string>
#include <vector>
#include <chrono>
#include <cstdlib>

#include "routine.hpp"

namespace clblast {
// =================================================================================================

// The constructor does all heavy work, errors are returned as exceptions
Routine::Routine(Queue &queue, EventPointer event, const std::string &name,
                 const std::vector<std::string> &routines, const Precision precision,
                 const std::vector<const Database::DatabaseEntry*> &userDatabase,
                 std::initializer_list<const char *> source):
    precision_(precision),
    routine_name_(name),
    queue_(queue),
    event_(event),
    context_(queue_.GetContext()),
    device_(queue_.GetDevice()),
    device_name_(device_.Name()),
    db_(queue_, routines, precision_, userDatabase) {

  // Queries the cache to see whether or not the program (context-specific) is already there
  if (ProgramIsInCache(context_, precision_, routine_name_)) { return; }

  // Sets the build options from an environmental variable (if set)
  auto options = std::vector<std::string>();
  const auto environment_variable = std::getenv("CLBLAST_BUILD_OPTIONS");
  if (environment_variable != nullptr) {
    options.push_back(std::string(environment_variable));
  }

  // Queries the cache to see whether or not the binary (device-specific) is already there. If it
  // is, a program is created and stored in the cache
  if (BinaryIsInCache(device_name_, precision_, routine_name_)) {
    auto& binary = GetBinaryFromCache(device_name_, precision_, routine_name_);
    auto program = Program(device_, context_, binary);
    program.Build(device_, options);
    StoreProgramToCache(program, context_, precision_, routine_name_);
  }

  // Otherwise, the kernel will be compiled and program will be built. Both the binary and the
  // program will be added to the cache.

  // Inspects whether or not cl_khr_fp64 is supported in case of double precision
  const auto extensions = device_.Capabilities();
  if (precision_ == Precision::kDouble || precision_ == Precision::kComplexDouble) {
    if (extensions.find(kKhronosDoublePrecision) == std::string::npos) {
      throw RuntimeErrorCode(StatusCode::kNoDoublePrecision);
    }
  }

  // As above, but for cl_khr_fp16 (half precision)
  if (precision_ == Precision::kHalf) {
    if (extensions.find(kKhronosHalfPrecision) == std::string::npos) {
      throw RuntimeErrorCode(StatusCode::kNoHalfPrecision);
    }
  }

  // Collects the parameters for this device in the form of defines, and adds the precision
  auto source_string = db_.GetDefines();
  source_string += "#define PRECISION "+ToString(static_cast<int>(precision_))+"\n";

  // Adds the name of the routine as a define
  source_string += "#define ROUTINE_"+routine_name_+"\n";

  // For specific devices, use the non-IEE754 compilant OpenCL mad() instruction. This can improve
  // performance, but might result in a reduced accuracy.
  if (device_.IsAMD() && device_.IsGPU()) {
    source_string += "#define USE_CL_MAD 1\n";
  }

  // For specific devices, use staggered/shuffled workgroup indices.
  if (device_.IsAMD() && device_.IsGPU()) {
    source_string += "#define USE_STAGGERED_INDICES 1\n";
  }

  // For specific devices add a global synchronisation barrier to the GEMM kernel to optimize
  // performance through better cache behaviour
  if (device_.IsARM() && device_.IsGPU()) {
    source_string += "#define GLOBAL_MEM_FENCE 1\n";
  }

  // Loads the common header (typedefs and defines and such)
  source_string +=
    #include "kernels/common.opencl"
  ;

  // Adds routine-specific code to the constructed source string
  for (const char *s: source) {
    source_string += s;
  }

  // Prints details of the routine to compile in case of debugging in verbose mode
  #ifdef VERBOSE
    printf("[DEBUG] Compiling routine '%s-%s' for device '%s'\n",
           routine_name_.c_str(), ToString(precision_).c_str(), device_name_.c_str());
    const auto start_time = std::chrono::steady_clock::now();
  #endif

  // Compiles the kernel
  auto program = Program(context_, source_string);
  try {
    program.Build(device_, options);
  } catch (const CLError &e) {
    if (e.status() == CL_BUILD_PROGRAM_FAILURE) {
      fprintf(stdout, "OpenCL compiler error/warning: %s\n",
              program.GetBuildInfo(device_).c_str());
    }
    throw;
  }

  // Store the compiled binary and program in the cache
  const auto binary = program.GetIR();
  StoreBinaryToCache(binary, device_name_, precision_, routine_name_);
  StoreProgramToCache(program, context_, precision_, routine_name_);

  // Prints the elapsed compilation time in case of debugging in verbose mode
  #ifdef VERBOSE
    const auto elapsed_time = std::chrono::steady_clock::now() - start_time;
    const auto timing = std::chrono::duration<double,std::milli>(elapsed_time).count();
    printf("[DEBUG] Completed compilation in %.2lf ms\n", timing);
  #endif
}

// =================================================================================================
} // namespace clblast
<commit_msg>Routine: use PrecisionSupported<>() instead of duplicating the check<commit_after>
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
//   Cedric Nugteren <www.cedricnugteren.nl>
//
// This file implements the Routine base class (see the header for information about the class).
//
// =================================================================================================

#include <string>
#include <vector>
#include <chrono>
#include <cstdlib>

#include "routine.hpp"

namespace clblast {
// =================================================================================================

// The constructor does all heavy work, errors are returned as exceptions
Routine::Routine(Queue &queue, EventPointer event, const std::string &name,
                 const std::vector<std::string> &routines, const Precision precision,
                 const std::vector<const Database::DatabaseEntry*> &userDatabase,
                 std::initializer_list<const char *> source):
    precision_(precision),
    routine_name_(name),
    queue_(queue),
    event_(event),
    context_(queue_.GetContext()),
    device_(queue_.GetDevice()),
    device_name_(device_.Name()),
    db_(queue_, routines, precision_, userDatabase) {

  // Queries the cache to see whether or not the program (context-specific) is already there
  if (ProgramIsInCache(context_, precision_, routine_name_)) { return; }

  // Sets the build options from an environmental variable (if set)
  auto options = std::vector<std::string>();
  const auto environment_variable = std::getenv("CLBLAST_BUILD_OPTIONS");
  if (environment_variable != nullptr) {
    options.push_back(std::string(environment_variable));
  }

  // Queries the cache to see whether or not the binary (device-specific) is already there. If it
  // is, a program is created and stored in the cache
  if (BinaryIsInCache(device_name_, precision_, routine_name_)) {
    auto& binary = GetBinaryFromCache(device_name_, precision_, routine_name_);
    auto program = Program(device_, context_, binary);
    program.Build(device_, options);
    StoreProgramToCache(program, context_, precision_, routine_name_);
  }

  // Otherwise, the kernel will be compiled and program will be built. Both the binary and the
  // program will be added to the cache.

  // Inspects whether or not cl_khr_fp64 is supported in case of double precision
  if ((precision_ == Precision::kDouble && !PrecisionSupported<double>(device_)) ||
      (precision_ == Precision::kComplexDouble && !PrecisionSupported<double2>(device_))) {
    throw RuntimeErrorCode(StatusCode::kNoDoublePrecision);
  }

  // As above, but for cl_khr_fp16 (half precision)
  if (precision_ == Precision::kHalf && !PrecisionSupported<half>(device_)) {
    throw RuntimeErrorCode(StatusCode::kNoHalfPrecision);
  }

  // Collects the parameters for this device in the form of defines, and adds the precision
  auto source_string = db_.GetDefines();
  source_string += "#define PRECISION "+ToString(static_cast<int>(precision_))+"\n";

  // Adds the name of the routine as a define
  source_string += "#define ROUTINE_"+routine_name_+"\n";

  // For specific devices, use the non-IEE754 compilant OpenCL mad() instruction. This can improve
  // performance, but might result in a reduced accuracy.
  if (device_.IsAMD() && device_.IsGPU()) {
    source_string += "#define USE_CL_MAD 1\n";
  }

  // For specific devices, use staggered/shuffled workgroup indices.
  if (device_.IsAMD() && device_.IsGPU()) {
    source_string += "#define USE_STAGGERED_INDICES 1\n";
  }

  // For specific devices add a global synchronisation barrier to the GEMM kernel to optimize
  // performance through better cache behaviour
  if (device_.IsARM() && device_.IsGPU()) {
    source_string += "#define GLOBAL_MEM_FENCE 1\n";
  }

  // Loads the common header (typedefs and defines and such)
  source_string +=
    #include "kernels/common.opencl"
  ;

  // Adds routine-specific code to the constructed source string
  for (const char *s: source) {
    source_string += s;
  }

  // Prints details of the routine to compile in case of debugging in verbose mode
  #ifdef VERBOSE
    printf("[DEBUG] Compiling routine '%s-%s' for device '%s'\n",
           routine_name_.c_str(), ToString(precision_).c_str(), device_name_.c_str());
    const auto start_time = std::chrono::steady_clock::now();
  #endif

  // Compiles the kernel
  auto program = Program(context_, source_string);
  try {
    program.Build(device_, options);
  } catch (const CLError &e) {
    if (e.status() == CL_BUILD_PROGRAM_FAILURE) {
      fprintf(stdout, "OpenCL compiler error/warning: %s\n",
              program.GetBuildInfo(device_).c_str());
    }
    throw;
  }

  // Store the compiled binary and program in the cache
  const auto binary = program.GetIR();
  StoreBinaryToCache(binary, device_name_, precision_, routine_name_);
  StoreProgramToCache(program, context_, precision_, routine_name_);

  // Prints the elapsed compilation time in case of debugging in verbose mode
  #ifdef VERBOSE
    const auto elapsed_time = std::chrono::steady_clock::now() - start_time;
    const auto timing = std::chrono::duration<double,std::milli>(elapsed_time).count();
    printf("[DEBUG] Completed compilation in %.2lf ms\n", timing);
  #endif
}

// =================================================================================================
} // namespace clblast
<|endoftext|>


<commit_before>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

//! @example

#include <DO/Sara/Core/TicToc.hpp>
#include <DO/Sara/FeatureDetectors.hpp>
#include <DO/Sara/FeatureMatching.hpp>
#include <DO/Sara/ImageIO.hpp>
#include <DO/Sara/ImageProcessing.hpp>
#include <DO/Sara/ImageProcessing/FastColorConversion.hpp>
#include <DO/Sara/VideoIO.hpp>
#include <DO/Sara/Visualization.hpp>

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#include <omp.h>

namespace fs = boost::filesystem;
namespace po = boost::program_options;

using namespace std;
using namespace DO::Sara;

auto initialize_crop_region(const Eigen::Vector2i& sizes)
{
  const Eigen::Vector2i& p1 = {0.2 * sizes.x(), 0.2 * sizes.y()};
  const Eigen::Vector2i& p2 = {0.8 * sizes.x(), 0.75 * sizes.y()};
  return std::make_pair(p1, p2);
}

auto imshow(const std::string& window_name, const ImageView<Rgb8>& image)
{
  static auto window_names = std::map<std::string, Window>{};
  auto w_it = window_names.find(window_name);

  auto w = Window{};
  if (w_it == window_names.end())
  {
    w = create_window(image.sizes(), window_name);
    window_names[window_name] = w;
  }
  else
    w = w_it->second;

  set_active_window(w);
  display(image);
}

int main(int argc, char** argv)
{
  DO::Sara::GraphicsApplication app(argc, argv);
  app.register_user_main(__main);
  return app.exec();
}

int __main(int argc, char** argv)
{
  using namespace std::string_literals;

  // Parameter parsing.
  auto video_filepath = std::string{};
  auto downscale_factor = int{};
  auto skip = int{};
  auto show_tracks = bool{};

  po::options_description desc("video_sift_matching");
  desc.add_options()     //
      ("help", "Usage")  //
      ("video,v", po::value<std::string>(&video_filepath),
       "input video file")  //
      ("downscale-factor,d",
       po::value<int>(&downscale_factor)->default_value(2),
       "downscale factor")  //
      ("skip,s", po::value<int>(&skip)->default_value(0),
       "number of frames to skip")  //
      ("show_tracks,t", po::value<bool>(&show_tracks)->default_value(true),
       "show feature tracking")  //
      ;

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  if (vm.count("help"))
  {
    std::cout << desc << "\n";
    return 1;
  }

  if (!vm.count("video"))
  {
    std::cout << "The video file must be specified!\n" << desc << "\n";
    return 1;
  }

  // OpenMP.
  omp_set_num_threads(omp_get_max_threads());

  // Input and output from Sara.
  VideoStream video_stream(video_filepath);
  auto frame = video_stream.frame();
  auto frame_gray32f = Image<float>{};
  const Eigen::Vector2i downscaled_sizes = frame.sizes() / downscale_factor;
  auto frame_gray32f_downscaled = Image<float>{downscaled_sizes};
  auto screen_contents = Image<Rgb8>{frame.sizes()};

  // Output save.
  const auto basename = fs::basename(video_filepath);
  VideoWriter video_writer{
#ifdef __APPLE__
      "/Users/david/Desktop/" + basename + ".sift-matching.mp4",
#else
      "/home/david/Desktop/" + basename + ".sift-matching.mp4",
#endif
      frame.sizes()  //
  };

  // Show the local extrema.
  auto w = create_window(frame.sizes(), "SIFT matching " + basename);
  set_antialiasing();

// #define CROP
#ifdef CROP
  const auto [p1, p2] = initialize_crop_region(frame.sizes());
#else
  const Eigen::Vector2i& p1 = Eigen::Vector2i::Zero();
#endif

  auto image_prev = Image<float>{};
  auto image_curr = Image<float>{};

  auto keys_prev = KeypointList<OERegion, float>{};
  auto keys_curr = KeypointList<OERegion, float>{};

  auto frames_read = 0;
  while (true)
  {
    if (!video_stream.read())
    {
      std::cout << "Reached the end of the video!" << std::endl;
      break;
    }
    ++frames_read;
    if (frames_read % (skip + 1) != 0)
      continue;
    SARA_DEBUG << "Processing frame " << frames_read << std::endl;

#ifdef CROP
    // Reduce our attention to the central part of the image.
    tic();
    const auto frame_cropped = crop(frame, p1, p2);
    toc("Crop");

    tic();
    frame_gray32f = DO::Sara::from_rgb8_to_gray32f(frame_cropped);
    toc("Grayscale");
#else
    tic();
    frame_gray32f = DO::Sara::from_rgb8_to_gray32f(frame);
    toc("Grayscale");
#endif

//    if (downscale_factor > 1)
//    {
//      tic();
//      scale(frame_gray32f, frame_gray32f_downscaled);
//      toc("Downscale");
//    }
//    else
//      frame_gray32f_downscaled.swap(frame_gray32f);

    tic();
    {
      image_prev.swap(image_curr);
      keys_prev.swap(keys_curr);

      image_curr = frame_gray32f;
      static constexpr auto scale_camera = 1.f;
      static constexpr auto num_scales_per_octaves = 1;
      const auto first_octave = static_cast<int>(std::round(std::log(downscale_factor) / std::log(2)));
      const auto scale_geometric_factor = std::pow(2.f, 1.f / num_scales_per_octaves);
      const auto image_pyr_params = ImagePyramidParams(first_octave,
                                                       num_scales_per_octaves + 3,
                                                       scale_geometric_factor,
                                                       /* image_padding_size */ 8,
                                                       scale_camera,
                                                       /* scale_initial */ 1.2f);
      keys_curr = compute_sift_keypoints(frame_gray32f, image_pyr_params);
    }
    toc("SIFT");

    // Compute matches.
    tic();
    auto matches = std::vector<Match>{};
    const auto& fprev = std::get<0>(keys_prev);
    if (!fprev.empty())
    {
      AnnMatcher matcher{keys_prev, keys_curr, 0.6f};
      matches = matcher.compute_matches();
    }
    toc("Matching");

    tic();
    set_active_window(w);
    display(frame);
    if (show_tracks)
    {
      for (size_t i = 0; i < matches.size(); ++i)
      {
        draw(matches[i].x(), Blue8, 1, p1.cast<float>());
        draw(matches[i].y(), Cyan8, 1, p1.cast<float>());
        const Eigen::Vector2f a = p1.cast<float>() + matches[i].x_pos();
        const Eigen::Vector2f b = p1.cast<float>() + matches[i].y_pos();
        draw_arrow(a, b, Yellow8, 2);
      }
    }
    draw_text(100, 100, "SIFT matches = " + std::to_string(matches.size()),
              White8, 40, 0, false, true, false);
    toc("Display");

    //grab_screen_contents(screen_contents, w);
    //video_writer.write(screen_contents);
  }

  return 0;
}
<commit_msg>ENH: add command line options.<commit_after>// ========================================================================== //
// This file is part of Sara, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2013 David Ok <david.ok8@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License v. 2.0. If a copy of the MPL was not distributed with this file,
// you can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================== //

//! @example

#include <DO/Sara/Core/TicToc.hpp>
#include <DO/Sara/FeatureDetectors.hpp>
#include <DO/Sara/FeatureMatching.hpp>
#include <DO/Sara/ImageIO.hpp>
#include <DO/Sara/ImageProcessing.hpp>
#include <DO/Sara/ImageProcessing/FastColorConversion.hpp>
#include <DO/Sara/VideoIO.hpp>
#include <DO/Sara/Visualization.hpp>

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#include <omp.h>

namespace fs = boost::filesystem;
namespace po = boost::program_options;

using namespace std;
using namespace DO::Sara;

auto initialize_crop_region(const Eigen::Vector2i& sizes)
{
  const Eigen::Vector2i& p1 = {0.2 * sizes.x(), 0.2 * sizes.y()};
  const Eigen::Vector2i& p2 = {0.8 * sizes.x(), 0.75 * sizes.y()};
  return std::make_pair(p1, p2);
}

auto imshow(const std::string& window_name, const ImageView<Rgb8>& image)
{
  static auto window_names = std::map<std::string, Window>{};
  auto w_it = window_names.find(window_name);

  auto w = Window{};
  if (w_it == window_names.end())
  {
    w = create_window(image.sizes(), window_name);
    window_names[window_name] = w;
  }
  else
    w = w_it->second;

  set_active_window(w);
  display(image);
}

int main(int argc, char** argv)
{
  DO::Sara::GraphicsApplication app(argc, argv);
  app.register_user_main(__main);
  return app.exec();
}

int __main(int argc, char** argv)
{
  using namespace std::string_literals;

  // Parameter parsing.
  auto video_filepath = std::string{};
  auto downscale_factor = int{};
  auto skip = int{};
  auto hide_tracks = false;
  auto show_features = false;

  po::options_description desc("video_sift_matching");
  desc.add_options()     //
      ("help", "Usage")  //
      ("video,v", po::value<std::string>(&video_filepath),
       "input video file")  //
      ("downscale-factor,d",
       po::value<int>(&downscale_factor)->default_value(2),
       "downscale factor")  //
      ("skip,s", po::value<int>(&skip)->default_value(0),
       "number of frames to skip")  //
      ("hide_tracks,h", po::bool_switch(&hide_tracks),
       "hide feature tracking")  //
      ("show_features,f", po::bool_switch(&show_features),
       "show features")  //
      ;

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  if (vm.count("help"))
  {
    std::cout << desc << "\n";
    return 1;
  }

  if (!vm.count("video"))
  {
    std::cout << "The video file must be specified!\n" << desc << "\n";
    return 1;
  }

  // OpenMP.
  omp_set_num_threads(omp_get_max_threads());

  // Input and output from Sara.
  VideoStream video_stream(video_filepath);
  auto frame = video_stream.frame();
  auto frame_gray32f = Image<float>{};
  const Eigen::Vector2i downscaled_sizes = frame.sizes() / downscale_factor;
  auto frame_gray32f_downscaled = Image<float>{downscaled_sizes};
  auto screen_contents = Image<Rgb8>{frame.sizes()};

  // Output save.
  const auto basename = fs::basename(video_filepath);
  VideoWriter video_writer{
#ifdef __APPLE__
      "/Users/david/Desktop/" + basename + ".sift-matching.mp4",
#else
      "/home/david/Desktop/" + basename + ".sift-matching.mp4",
#endif
      frame.sizes()  //
  };

  // Show the local extrema.
  auto w = create_window(frame.sizes(), "SIFT matching " + basename);
  set_antialiasing();

// #define CROP
#ifdef CROP
  const auto [p1, p2] = initialize_crop_region(frame.sizes());
#else
  const Eigen::Vector2i& p1 = Eigen::Vector2i::Zero();
#endif

  auto image_prev = Image<float>{};
  auto image_curr = Image<float>{};

  auto keys_prev = KeypointList<OERegion, float>{};
  auto keys_curr = KeypointList<OERegion, float>{};

  auto frames_read = 0;
  while (true)
  {
    if (!video_stream.read())
    {
      std::cout << "Reached the end of the video!" << std::endl;
      break;
    }
    ++frames_read;
    if (frames_read % (skip + 1) != 0)
      continue;
    SARA_DEBUG << "Processing frame " << frames_read << std::endl;

#ifdef CROP
    // Reduce our attention to the central part of the image.
    tic();
    const auto frame_cropped = crop(frame, p1, p2);
    toc("Crop");

    tic();
    frame_gray32f = DO::Sara::from_rgb8_to_gray32f(frame_cropped);
    toc("Grayscale");
#else
    tic();
    frame_gray32f = DO::Sara::from_rgb8_to_gray32f(frame);
    toc("Grayscale");
#endif

    tic();
    {
      image_prev.swap(image_curr);
      keys_prev.swap(keys_curr);

      image_curr = frame_gray32f;
      static constexpr auto scale_camera = 1.f;
      static constexpr auto num_scales_per_octaves = 1;
      const auto first_octave = static_cast<int>(
          std::round(std::log(downscale_factor) / std::log(2)));
      const auto scale_geometric_factor =
          std::pow(2.f, 1.f / num_scales_per_octaves);
      const auto image_pyr_params = ImagePyramidParams(
          first_octave, num_scales_per_octaves + 3, scale_geometric_factor,
          /* image_padding_size */ 8, scale_camera,
          /* scale_initial */ 1.2f);
      keys_curr = compute_sift_keypoints(frame_gray32f, image_pyr_params);
    }
    toc("SIFT");

    tic();
    auto matches = std::vector<Match>{};
    const auto& fprev = std::get<0>(keys_prev);
    if (!fprev.empty())
    {
      AnnMatcher matcher{keys_prev, keys_curr, 0.6f};
      matches = matcher.compute_matches();
    }
    toc("Matching");

    tic();
    set_active_window(w);
    display(frame);
    if (!hide_tracks)
    {
      for (size_t i = 0; i < matches.size(); ++i)
      {
        if (show_features)
        {
          draw(matches[i].x(), Blue8, 1, p1.cast<float>());
          draw(matches[i].y(), Cyan8, 1, p1.cast<float>());
        }
        const Eigen::Vector2f a = p1.cast<float>() + matches[i].x_pos();
        const Eigen::Vector2f b = p1.cast<float>() + matches[i].y_pos();
        draw_arrow(a, b, Yellow8, 4);
      }
    }
    draw_text(100, 100, "SIFT matches = " + std::to_string(matches.size()),
              White8, 40, 0, false, true, false);
    toc("Display");

    // grab_screen_contents(screen_contents, w);
    // video_writer.write(screen_contents);
  }

  return 0;
}
<|endoftext|>