<commit_before>/*---------------------------------------------------------------------\
|                                                                      |
|                     _     _   _   _     __     _                     |
|                    | |   | | | \_/ |   /  \   | |                    |
|                    | |   | | | |_| |  / /\ \  | |                    |
|                    | |__ | | | | | | / ____ \ | |__                  |
|                    |____||_| |_| |_|/ /    \ \|____|                 |
|                                                                      |
|                             ca-mgm library                           |
|                                                                      |
|                                         (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/

  File:       CRLReason_Priv.cpp

  Author:     <Michael Calmer>     <mc@suse.de>
  Maintainer: <Michael Calmer>     <mc@suse.de>

  Purpose:

/-*/
#include  "CRLReason_Priv.hpp"

#include <openssl/x509v3.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <openssl/evp.h>

#include  <fstream>
#include  <iostream>

#include  <limal/Exception.hpp>
#include  <blocxx/Format.hpp>
#include  <blocxx/DateTime.hpp>

#include  "Utils.hpp"

using namespace limal;
using namespace limal::ca_mgm;
using namespace blocxx;

CRLReason_Priv::CRLReason_Priv()
    : CRLReason()
{}

CRLReason_Priv::CRLReason_Priv(STACK_OF(X509_EXTENSION) *stack)
    : CRLReason()
{
    for(int x = 0; x < sk_X509_EXTENSION_num(stack); x++) {

        X509_EXTENSION *xe = sk_X509_EXTENSION_value(stack, x);

        int nid = 0;
        String valueString;
        char *value;
        char obj_tmp[80];
        BIO *out;

        i2t_ASN1_OBJECT(obj_tmp, 80, xe->object);
        nid = OBJ_txt2nid(obj_tmp);

        LOGIT_DEBUG("NID: " << obj_tmp << " " << nid);

        out = BIO_new(BIO_s_mem());
        X509V3_EXT_print(out, xe, 0, 1);

        int n = BIO_get_mem_data(out, &value);
        valueString = String(value, n);
        valueString.ltrim();
        valueString.rtrim();
        BIO_free(out);

        LOGIT_DEBUG("Value: " << valueString);

        if(nid == NID_crl_reason) {

            if(valueString == "Unspecified") {
                setReason(CRLReason::unspecified);
            } else if(valueString == "Key Compromise") {
                setReason(CRLReason::keyCompromise);
            } else if(valueString == "CA Compromise") {
                setReason(CRLReason::CACompromise);
            } else if(valueString == "Affiliation Changed") {
                setReason(CRLReason::affiliationChanged);
            } else if(valueString == "Superseded") {
                setReason(CRLReason::superseded);
            } else if(valueString == "Cessation Of Operation") {
                setReason(CRLReason::cessationOfOperation);
            } else if(valueString == "Certificate Hold") {
                setReason(CRLReason::certificateHold);
            } else if(valueString == "Remove From CRL") {
                setReason(CRLReason::removeFromCRL);
            } else {
                LOGIT_INFO("Unknown CRL reason:" << valueString);
            }
        } else if(nid == NID_hold_instruction_code) {

            // FIXME: Test with OID

            if(valueString == "Hold Instruction Call Issuer") {

                setHoldInstruction("holdInstructionCallIssuer");

            } else if(valueString == "Hold Instruction None") {

                setHoldInstruction("holdInstructionNone");

            } else if(valueString == "Hold Instruction Reject") {

                setHoldInstruction("holdInstructionReject");

            } else {
                // OID ?? does this work ?
                setHoldInstruction(valueString);

            }
        } else if(nid == NID_invalidity_date) {

            // e.g. Aug 18 15:56:46 2005 GMT
            DateTime dtime(valueString);

            if(getReason() == CRLReason::keyCompromise) {

                setKeyCompromiseDate(dtime.get());

            } else if(getReason() == CRLReason::CACompromise) {

                setCACompromiseDate(dtime.get());

            } else {
                LOGIT_INFO("Date with wrong reason");
            }

        } else {
            LOGIT_INFO("Unsupported NID: " << nid);
        }
    }
}

CRLReason_Priv::~CRLReason_Priv()
{}
<commit_msg>yes, OIDs are working :-)<commit_after>/*---------------------------------------------------------------------\
|                                                                      |
|                     _     _   _   _     __     _                     |
|                    | |   | | | \_/ |   /  \   | |                    |
|                    | |   | | | |_| |  / /\ \  | |                    |
|                    | |__ | | | | | | / ____ \ | |__                  |
|                    |____||_| |_| |_|/ /    \ \|____|                 |
|                                                                      |
|                             ca-mgm library                           |
|                                                                      |
|                                         (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/

  File:       CRLReason_Priv.cpp

  Author:     <Michael Calmer>     <mc@suse.de>
  Maintainer: <Michael Calmer>     <mc@suse.de>

  Purpose:

/-*/
#include  "CRLReason_Priv.hpp"

#include <openssl/x509v3.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <openssl/evp.h>

#include  <fstream>
#include  <iostream>

#include  <limal/Exception.hpp>
#include  <blocxx/Format.hpp>
#include  <blocxx/DateTime.hpp>

#include  "Utils.hpp"

using namespace limal;
using namespace limal::ca_mgm;
using namespace blocxx;

CRLReason_Priv::CRLReason_Priv()
    : CRLReason()
{}

CRLReason_Priv::CRLReason_Priv(STACK_OF(X509_EXTENSION) *stack)
    : CRLReason()
{
    for(int x = 0; x < sk_X509_EXTENSION_num(stack); x++) {

        X509_EXTENSION *xe = sk_X509_EXTENSION_value(stack, x);

        int nid = 0;
        String valueString;
        char *value;
        char obj_tmp[80];
        BIO *out;

        i2t_ASN1_OBJECT(obj_tmp, 80, xe->object);
        nid = OBJ_txt2nid(obj_tmp);

        LOGIT_DEBUG("NID: " << obj_tmp << " " << nid);

        out = BIO_new(BIO_s_mem());
        X509V3_EXT_print(out, xe, 0, 1);

        int n = BIO_get_mem_data(out, &value);
        valueString = String(value, n);
        valueString.ltrim();
        valueString.rtrim();
        BIO_free(out);

        LOGIT_DEBUG("Value: " << valueString);

        if(nid == NID_crl_reason) {

            if(valueString == "Unspecified") {
                setReason(CRLReason::unspecified);
            } else if(valueString == "Key Compromise") {
                setReason(CRLReason::keyCompromise);
            } else if(valueString == "CA Compromise") {
                setReason(CRLReason::CACompromise);
            } else if(valueString == "Affiliation Changed") {
                setReason(CRLReason::affiliationChanged);
            } else if(valueString == "Superseded") {
                setReason(CRLReason::superseded);
            } else if(valueString == "Cessation Of Operation") {
                setReason(CRLReason::cessationOfOperation);
            } else if(valueString == "Certificate Hold") {
                setReason(CRLReason::certificateHold);
            } else if(valueString == "Remove From CRL") {
                setReason(CRLReason::removeFromCRL);
            } else {
                LOGIT_INFO("Unknown CRL reason:" << valueString);
            }
        } else if(nid == NID_hold_instruction_code) {

            // FIXME: Test with OID

            if(valueString == "Hold Instruction Call Issuer") {

                setHoldInstruction("holdInstructionCallIssuer");

            } else if(valueString == "Hold Instruction None") {

                setHoldInstruction("holdInstructionNone");

            } else if(valueString == "Hold Instruction Reject") {

                setHoldInstruction("holdInstructionReject");

            } else {

                // set an OID as hold instruction
                setHoldInstruction(valueString);

            }
        } else if(nid == NID_invalidity_date) {

            // e.g. Aug 18 15:56:46 2005 GMT
            DateTime dtime(valueString);

            if(getReason() == CRLReason::keyCompromise) {

                setKeyCompromiseDate(dtime.get());

            } else if(getReason() == CRLReason::CACompromise) {

                setCACompromiseDate(dtime.get());

            } else {
                LOGIT_INFO("Date with wrong reason");
            }

        } else {
            LOGIT_INFO("Unsupported NID: " << nid);
        }
    }
}

CRLReason_Priv::~CRLReason_Priv()
{}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// File: factory.hpp
//
// Desc: Device factory - Manage IP Camera.
//
// Copyright (c) 2014-2018 opencvr.com. All rights reserved.
//------------------------------------------------------------------------------

#ifndef __VSC_FACTORY_H_
#define __VSC_FACTORY_H_
#include "confdb.hpp"
#include "device.hpp"
#include "vdb.hpp"
#include "vhdfsdb.hpp"
#include "vplay.hpp"
#include "sysdb.hpp"
#include "hdddevice.hpp"
#include <QThread>
#include <qdebug.h>

typedef enum
{
    FACTORY_DEVICE_ADD = 1,
    FACTORY_DEVICE_DEL,
    FACTORY_DEVICE_ONLINE,
    FACTORY_DEVICE_OFFLINE,
    FACTORY_DEVICE_RECORDING_ON,
    FACTORY_DEVICE_RECORDING_OFF,
    /* The Camera group has been change */
    FACTORY_DEVICE_GROUP_CHANGE,
    FACTORY_VMS_ADD,
    FACTORY_VMS_DEL,
    FACTORY_VIPC_ADD,
    FACTORY_VIPC_DEL,
    /* Camera view add and del */
    FACTORY_VIEW_ADD,
    FACTORY_VIEW_DEL,
    /* Camera group add and del */
    FACTORY_VGROUP_ADD,
    FACTORY_VGROUP_DEL,
    FACTORY_DEVICE_LAST
} FactoryDeviceChangeType;

class FactoryDeviceChangeData
{
public:
	FactoryDeviceChangeType type;
	int id;
};

typedef BOOL (*FactoryDeviceChangeNotify)(void* pParam,
		FactoryDeviceChangeData data);

typedef std::list<LPDevice> DeviceList;
typedef std::list<DeviceParam> DeviceParamList;
typedef std::map<int, LPDevice> DeviceMap;
typedef std::map<int, DeviceParam> DeviceParamMap;
typedef std::map<int, VIPCDeviceParam> VIPCDeviceParamMap;
typedef std::map<void *, FactoryDeviceChangeNotify> DeviceChangeNofityMap;
#define FACTORY_DEVICE_ID_MAX 4096

class Factory;
class FactoryHddTask:public QThread
{
	Q_OBJECT
public:
	FactoryHddTask(Factory &pFactory);
	~FactoryHddTask();
public:
	void run();
private:
	Factory &m_Factory;
};

/* Fatory is Qthread for callback in Qt GUI */
class Factory: public QThread
{
    Q_OBJECT
public:
    Factory();
    ~Factory();
public:
	/* Init function */
	BOOL Init();
	s32 InitAddDevice(DeviceParam & pParam, u32 nIndex);

public:
	BOOL RegDeviceChangeNotify(void * pData, FactoryDeviceChangeNotify callback);
	BOOL CallDeviceChange(FactoryDeviceChangeData data);

public:
	BOOL GetLicense(astring &strLicense, astring &strHostId,
							int &ch, int &type);
	BOOL SetLicense(astring &strLicense);
	BOOL InitLicense();

public:
	BOOL GetAutoLogin();
	BOOL AuthUser(astring &strUser, astring &strPasswd);
	BOOL GetUserData(VSCUserData &pData);
	BOOL SetUserData(VSCUserData &pData);

/* Emap function */
public:
	BOOL GetEmapData(VSCEmapData &pData);
	BOOL SetEmapData(VSCEmapData &pData);
	BOOL AddEmapCamera(s32 nIndex, u32 x, u32 y, u32 w, u32 h);
	BOOL DelEmapCamera(s32 nIndex);
	BOOL GetEmapCamera(s32 nIndex, u32 &x, u32 &y, u32 &w, u32 &h);

	BOOL GetEmapFile(astring &strFile);
	BOOL SetEmapFile(astring &strFile);

public:
	BOOL GetHdfsRecordConf(VSCHdfsRecordData &pData);
	BOOL SetHdfsRecordConf(VSCHdfsRecordData &pData);
	BOOL GetLang(VSCLangType &pLang);
	BOOL SetLang(VSCLangType &pLang);

public:
	/* UI can use this for display device tree */
	BOOL GetDeviceParamMap(DeviceParamMap &pMap);
       BOOL GetVIPCDeviceParamMap(VIPCDeviceParamMap &pMap);
       /* Device function */
	s32 AddDevice(DeviceParam & pParam);
	s32 GetDeviceParamById(DeviceParam & pParam, s32 nIndex);
	BOOL GetDeviceRtspUrl(astring & strUrl, s32 nIndex);
	s32 GetDeviceParamByIdTryLock(DeviceParam & pParam, s32 nIndex);
	BOOL DelDevice(s32 nIndex);
	BOOL UpdateDeviceGroup(s32 nIndex, s32 nGroup);

	/* VIPC function */
	s32 AddVIPC(VIPCDeviceParam & pParam);
	s32 GetVIPCParamById(VIPCDeviceParam & pParam, s32 nIndex);
	BOOL DelVIPC(s32 nIndex);

	/* Video play function */
	BOOL AttachPlayer(s32 nIndex, HWND hWnd, int w, int h,
						DeviceDelCallbackFunctionPtr pCallback, void * pParam);
	BOOL UpdateWidget(s32 nIndex, HWND hWnd, int w, int h);
	BOOL DetachPlayer(s32 nIndex, HWND hWnd, void * pParam);

	BOOL EnablePtz(s32 nIndex, HWND hWnd, bool enable);
	BOOL DrawPtzDirection(s32 nIndex, HWND hWnd, int x1, int y1, int x2,  int y2);
	BOOL ClearPtzDirection(s32 nIndex, HWND hWnd);
	BOOL PtzAction(s32 nIndex, FPtzAction action, float speed);
	BOOL ShowAlarm(s32 nIndex, HWND hWnd);
public:
	/* VMS */
	BOOL GetVms(VSCVmsData &pData);
	s32 AddVms(VSCVmsDataItem &pParam);
	BOOL DelVms(s32 Id);
	BOOL GetVmsById(VSCVmsDataItem &pParam, int nId);

	/* View */
	BOOL GetView(VSCViewData &pData);
	s32 AddView(VSCViewDataItem &pParam);
	BOOL DelView(s32 Id);
	BOOL GetViewById(VSCViewDataItem &pParam, int nId);

	/* Camera group */
	BOOL GetVGroup(VSCVGroupData &pData);
	s32 AddVGroup(VSCVGroupDataItem &pParam);
	BOOL DelVGroup(s32 Id);
	BOOL GetVGroupById(VSCVGroupDataItem &pParam, int nId);

public:
	BOOL StartRecord(s32 nIndex);
	BOOL StopRecord(s32 nIndex);
	BOOL StartHdfsRecord(s32 nIndex);
	BOOL StopHdfsRecord(s32 nIndex);
	BOOL StartRecordAll();
	BOOL StopRecordAll();
	BOOL StartHdfsRecordAll();
	BOOL StopHdfsRecordAll();
public:
	BOOL GetRecordStatus(s32 nIndex, BOOL &bStatus);

public:
	/* Data */
	BOOL RegDataCallback(s32 nIndex, DeviceDataCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegDataCallback(s32 nIndex, void * pParam);
	BOOL GetInfoFrame(s32 nIndex, InfoFrame &pFrame);
	BOOL RegSubDataCallback(s32 nIndex, DeviceDataCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegSubDataCallback(s32 nIndex, void * pParam);
	BOOL GetSubInfoFrame(s32 nIndex, InfoFrame &pFrame);

	/* Raw data */
	BOOL RegRawCallback(s32 nIndex, DeviceRawCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegRawCallback(s32 nIndex, void * pParam);
	BOOL RegSubRawCallback(s32 nIndex, DeviceRawCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegSubRawCallback(s32 nIndex, void * pParam);

	BOOL RegDelCallback(s32 nIndex, DeviceDelCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegDelCallback(s32 nIndex, void * pParam);

	BOOL GetDeviceOnline(s32 nIndex, BOOL &bStatus);
	BOOL GetUrl(s32 nIndex, std::string &url);
	BOOL SetSystemPath(astring &strPath);

	/* Disk function */
	BOOL AddHdd(astring &strHdd, astring & strPath, s64 nSize);
	BOOL DelHdd(astring & strHdd);
	BOOL HddUpdateSize(astring &strHdd, s64 nSize);
	BOOL GetDiskMap(VDBDiskMap &pMap);
	BOOL GetDiskStatus(VDBDiskStatus &pStatus);
	BOOL UpdateDiskStatusMap(VDBDiskStatus &pStatus);

	/* Search function */
	BOOL SearchItems(s32 deviceId, u32 startTime, u32 endTime, u32 recordType,
					RecordItemMap &map);
	BOOL SearchHasItems(s32 deviceId, u32 startTime, u32 endTime,
					u32 recordType);
	BOOL SearchAItem(s32 deviceId, u32 Time, VdbRecordItem &pItem);
	BOOL SearchAItemNear(s32 deviceId, u32 Time, VdbRecordItem &pItem);
	BOOL SearchNextItem(s32 deviceId, s64 LastId, VdbRecordItem &pItem);
	BOOL RequestAMFRead(VdbRecordItem &pItem, astring & strPath);
	BOOL FinishedAMFRead(VdbRecordItem &pItem, astring & strPath);
public:
	void Lock(){m_Lock.lock();}
	bool TryLock(){return m_Lock.try_lock();}
	void UnLock(){m_Lock.unlock();}

public:
	/* Device */
	s32 GetDeviceID(void);
	BOOL ReleaseDeviceID(s32 nID);
	BOOL LockDeviceID(s32 nID);

	/* VIPC */
	s32 GetVIPCID(void);
	BOOL ReleaseVIPCID(s32 nID);
	BOOL LockVIPCID(s32 nID);
public:
	static void Run(void * pParam);
	void run();

private:
	DeviceMap m_DeviceMap;
	DeviceParamMap m_DeviceParamMap;

	/* Virtual IP camera param */
	VIPCDeviceParamMap m_VIPCDeviceParamMap;
	fast_mutex m_Lock;
	tthread::thread *m_pThread;

private:
	DeviceChangeNofityMap m_DeviceChange;

private:
	VDB *m_pVdb;
	VHdfsDB *m_pVHdfsdb;
	FactoryHddTask *m_HddTask;

private:
	s8 m_strDeviceMap[FACTORY_DEVICE_ID_MAX];
	s8 m_strVIPCMap[FACTORY_DEVICE_ID_MAX];
	ConfDB m_Conf;
	SysDB m_SysPath;
};

typedef Factory* LPFactory;

#include "factoryimpl.hpp"

#endif // __VSC_FACTORY_H_
<commit_msg>add oapi conf interface<commit_after>//------------------------------------------------------------------------------
// File: factory.hpp
//
// Desc: Device factory - Manage IP Camera.
//
// Copyright (c) 2014-2018 opencvr.com. All rights reserved.
//------------------------------------------------------------------------------

#ifndef __VSC_FACTORY_H_
#define __VSC_FACTORY_H_
#include "confdb.hpp"
#include "device.hpp"
#include "vdb.hpp"
#include "vhdfsdb.hpp"
#include "vplay.hpp"
#include "sysdb.hpp"
#include "hdddevice.hpp"
#include <QThread>
#include <qdebug.h>

typedef enum
{
    FACTORY_DEVICE_ADD = 1,
    FACTORY_DEVICE_DEL,
    FACTORY_DEVICE_ONLINE,
    FACTORY_DEVICE_OFFLINE,
    FACTORY_DEVICE_RECORDING_ON,
    FACTORY_DEVICE_RECORDING_OFF,
    /* The Camera group has been change */
    FACTORY_DEVICE_GROUP_CHANGE,
    FACTORY_VMS_ADD,
    FACTORY_VMS_DEL,
    FACTORY_VIPC_ADD,
    FACTORY_VIPC_DEL,
    /* Camera view add and del */
    FACTORY_VIEW_ADD,
    FACTORY_VIEW_DEL,
    /* Camera group add and del */
    FACTORY_VGROUP_ADD,
    FACTORY_VGROUP_DEL,
    FACTORY_DEVICE_LAST
} FactoryDeviceChangeType;

class FactoryDeviceChangeData
{
public:
	FactoryDeviceChangeType type;
	int id;
};

typedef BOOL (*FactoryDeviceChangeNotify)(void* pParam,
		FactoryDeviceChangeData data);

typedef std::list<LPDevice> DeviceList;
typedef std::list<DeviceParam> DeviceParamList;
typedef std::map<int, LPDevice> DeviceMap;
typedef std::map<int, DeviceParam> DeviceParamMap;
typedef std::map<int, VIPCDeviceParam> VIPCDeviceParamMap;
typedef std::map<void *, FactoryDeviceChangeNotify> DeviceChangeNofityMap;
#define FACTORY_DEVICE_ID_MAX 4096

class Factory;
class FactoryHddTask:public QThread
{
	Q_OBJECT
public:
	FactoryHddTask(Factory &pFactory);
	~FactoryHddTask();
public:
	void run();
private:
	Factory &m_Factory;
};

/* Fatory is Qthread for callback in Qt GUI */
class Factory: public QThread
{
    Q_OBJECT
public:
    Factory();
    ~Factory();
public:
	/* Init function */
	BOOL Init();
	s32 InitAddDevice(DeviceParam & pParam, u32 nIndex);

public:
	BOOL RegDeviceChangeNotify(void * pData, FactoryDeviceChangeNotify callback);
	BOOL CallDeviceChange(FactoryDeviceChangeData data);

public:
	BOOL GetLicense(astring &strLicense, astring &strHostId,
							int &ch, int &type);
	BOOL SetLicense(astring &strLicense);
	BOOL InitLicense();

public:
	BOOL GetAutoLogin();
	BOOL AuthUser(astring &strUser, astring &strPasswd);
	BOOL GetUserData(VSCUserData &pData);
	BOOL SetUserData(VSCUserData &pData);

/* Emap function */
public:
	BOOL GetEmapData(VSCEmapData &pData);
	BOOL SetEmapData(VSCEmapData &pData);
	BOOL AddEmapCamera(s32 nIndex, u32 x, u32 y, u32 w, u32 h);
	BOOL DelEmapCamera(s32 nIndex);
	BOOL GetEmapCamera(s32 nIndex, u32 &x, u32 &y, u32 &w, u32 &h);

	BOOL GetEmapFile(astring &strFile);
	BOOL SetEmapFile(astring &strFile);

public:
	BOOL GetHdfsRecordConf(VSCHdfsRecordData &pData);
	BOOL SetHdfsRecordConf(VSCHdfsRecordData &pData);
	BOOL GetLang(VSCLangType &pLang);
	BOOL SetLang(VSCLangType &pLang);

	/* OpenCVR API port */
	BOOL GetOAPIPort(u16 &pPort);
	BOOL SetOAPIPort(u16 &pPort);

	/* Defualt HW HWAccel enable or disable */
	BOOL GetDefaultHWAccel(BOOL &pHWAccel);
	BOOL SetDefaultHWAccel(BOOL &pHWAccel);

public:
	/* UI can use this for display device tree */
	BOOL GetDeviceParamMap(DeviceParamMap &pMap);
       BOOL GetVIPCDeviceParamMap(VIPCDeviceParamMap &pMap);
       /* Device function */
	s32 AddDevice(DeviceParam & pParam);
	s32 GetDeviceParamById(DeviceParam & pParam, s32 nIndex);
	BOOL GetDeviceRtspUrl(astring & strUrl, s32 nIndex);
	s32 GetDeviceParamByIdTryLock(DeviceParam & pParam, s32 nIndex);
	BOOL DelDevice(s32 nIndex);
	BOOL UpdateDeviceGroup(s32 nIndex, s32 nGroup);

	/* VIPC function */
	s32 AddVIPC(VIPCDeviceParam & pParam);
	s32 GetVIPCParamById(VIPCDeviceParam & pParam, s32 nIndex);
	BOOL DelVIPC(s32 nIndex);

	/* Video play function */
	BOOL AttachPlayer(s32 nIndex, HWND hWnd, int w, int h,
						DeviceDelCallbackFunctionPtr pCallback, void * pParam);
	BOOL UpdateWidget(s32 nIndex, HWND hWnd, int w, int h);
	BOOL DetachPlayer(s32 nIndex, HWND hWnd, void * pParam);

	BOOL EnablePtz(s32 nIndex, HWND hWnd, bool enable);
	BOOL DrawPtzDirection(s32 nIndex, HWND hWnd, int x1, int y1, int x2,  int y2);
	BOOL ClearPtzDirection(s32 nIndex, HWND hWnd);
	BOOL PtzAction(s32 nIndex, FPtzAction action, float speed);
	BOOL ShowAlarm(s32 nIndex, HWND hWnd);
public:
	/* VMS */
	BOOL GetVms(VSCVmsData &pData);
	s32 AddVms(VSCVmsDataItem &pParam);
	BOOL DelVms(s32 Id);
	BOOL GetVmsById(VSCVmsDataItem &pParam, int nId);

	/* View */
	BOOL GetView(VSCViewData &pData);
	s32 AddView(VSCViewDataItem &pParam);
	BOOL DelView(s32 Id);
	BOOL GetViewById(VSCViewDataItem &pParam, int nId);

	/* Camera group */
	BOOL GetVGroup(VSCVGroupData &pData);
	s32 AddVGroup(VSCVGroupDataItem &pParam);
	BOOL DelVGroup(s32 Id);
	BOOL GetVGroupById(VSCVGroupDataItem &pParam, int nId);

public:
	BOOL StartRecord(s32 nIndex);
	BOOL StopRecord(s32 nIndex);
	BOOL StartHdfsRecord(s32 nIndex);
	BOOL StopHdfsRecord(s32 nIndex);
	BOOL StartRecordAll();
	BOOL StopRecordAll();
	BOOL StartHdfsRecordAll();
	BOOL StopHdfsRecordAll();
public:
	BOOL GetRecordStatus(s32 nIndex, BOOL &bStatus);

public:
	/* Data */
	BOOL RegDataCallback(s32 nIndex, DeviceDataCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegDataCallback(s32 nIndex, void * pParam);
	BOOL GetInfoFrame(s32 nIndex, InfoFrame &pFrame);
	BOOL RegSubDataCallback(s32 nIndex, DeviceDataCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegSubDataCallback(s32 nIndex, void * pParam);
	BOOL GetSubInfoFrame(s32 nIndex, InfoFrame &pFrame);

	/* Raw data */
	BOOL RegRawCallback(s32 nIndex, DeviceRawCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegRawCallback(s32 nIndex, void * pParam);
	BOOL RegSubRawCallback(s32 nIndex, DeviceRawCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegSubRawCallback(s32 nIndex, void * pParam);

	BOOL RegDelCallback(s32 nIndex, DeviceDelCallbackFunctionPtr pCallback, void * pParam);
	BOOL UnRegDelCallback(s32 nIndex, void * pParam);

	BOOL GetDeviceOnline(s32 nIndex, BOOL &bStatus);
	BOOL GetUrl(s32 nIndex, std::string &url);
	BOOL SetSystemPath(astring &strPath);

	/* Disk function */
	BOOL AddHdd(astring &strHdd, astring & strPath, s64 nSize);
	BOOL DelHdd(astring & strHdd);
	BOOL HddUpdateSize(astring &strHdd, s64 nSize);
	BOOL GetDiskMap(VDBDiskMap &pMap);
	BOOL GetDiskStatus(VDBDiskStatus &pStatus);
	BOOL UpdateDiskStatusMap(VDBDiskStatus &pStatus);

	/* Search function */
	BOOL SearchItems(s32 deviceId, u32 startTime, u32 endTime, u32 recordType,
					RecordItemMap &map);
	BOOL SearchHasItems(s32 deviceId, u32 startTime, u32 endTime,
					u32 recordType);
	BOOL SearchAItem(s32 deviceId, u32 Time, VdbRecordItem &pItem);
	BOOL SearchAItemNear(s32 deviceId, u32 Time, VdbRecordItem &pItem);
	BOOL SearchNextItem(s32 deviceId, s64 LastId, VdbRecordItem &pItem);
	BOOL RequestAMFRead(VdbRecordItem &pItem, astring & strPath);
	BOOL FinishedAMFRead(VdbRecordItem &pItem, astring & strPath);
public:
	void Lock(){m_Lock.lock();}
	bool TryLock(){return m_Lock.try_lock();}
	void UnLock(){m_Lock.unlock();}

public:
	/* Device */
	s32 GetDeviceID(void);
	BOOL ReleaseDeviceID(s32 nID);
	BOOL LockDeviceID(s32 nID);

	/* VIPC */
	s32 GetVIPCID(void);
	BOOL ReleaseVIPCID(s32 nID);
	BOOL LockVIPCID(s32 nID);
public:
	static void Run(void * pParam);
	void run();

private:
	DeviceMap m_DeviceMap;
	DeviceParamMap m_DeviceParamMap;

	/* Virtual IP camera param */
	VIPCDeviceParamMap m_VIPCDeviceParamMap;
	fast_mutex m_Lock;
	tthread::thread *m_pThread;

private:
	DeviceChangeNofityMap m_DeviceChange;

private:
	VDB *m_pVdb;
	VHdfsDB *m_pVHdfsdb;
	FactoryHddTask *m_HddTask;

private:
	s8 m_strDeviceMap[FACTORY_DEVICE_ID_MAX];
	s8 m_strVIPCMap[FACTORY_DEVICE_ID_MAX];
	ConfDB m_Conf;
	SysDB m_SysPath;
};

typedef Factory* LPFactory;

#include "factoryimpl.hpp"

#endif // __VSC_FACTORY_H_
<|endoftext|>


<commit_before>/***************************************************************************
//            Modified by Kishora Nayak - 14/06/2016
//            Modified by Enrico Fragiacomo - 15/01/2014
//            Modified by Kunal Garg - 04/02/2017
//            Based on AddAnalysisTaskRsnMini
//            pPb specific settings from AddTaskKStarPPB.C
//
// Macro to configure the KStarPlusMinus analysis task
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
//  1) flag to know if running on MC or data
//  2) collision system, whether pp, pPb or PbPb
// --
// Returns:
//  kTRUE  --> initialization successful
//  kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/

//enum ERsnCollType_t { kPP=0,      kPPb,      kPbPb};

enum pairYCutSet { kPairDefault,    // USED ONLY FOR pA
		   kNegative,       // USED ONLY FOR pA
		   kCentral         // USED ONLY FOR pA
                 };

/*enum eventCutSet { kOld = -1,
		   kEvtDefault, //=0
		   kNoPileUpCut, //=1
		   kPileUpMV, //=2
		   kPileUpSPD3, //=3
		   kDefaultVtx8, //=4
		   kDefaultVtx5 //=5
};*/

enum eventCutSet { kEvtDefault=0,
                   kNoPileUpCut, //=1
                   kDefaultVtx12,//=2
                   kDefaultVtx8, //=3
                   kDefaultVtx5, //=4
                   kMCEvtDefault //=5
};

enum eventMixConfig { kDisabled = -1,
		      kMixDefault,     //=0 //10 events, Dvz = 1cm, DC = 10
		      k5Evts,          //=1 //5 events, Dvz = 1cm, DC = 10
		      k5Cent,          //=2 //10 events, Dvz = 1cm, DC = 5
};

Ali:RsnMiniAnalysisTask *AddTaskKStarPlusMinusRun2
(
 Bool_t      isMC,
 Bool_t      isPP,
 // Int_t     collSyst,
 Float_t     cutV = 10.0,
 Int_t       evtCutSetID = 0,
 Int_t       pairCutSetID = 0,
 Int_t       mixingConfigID = 0,
 Int_t       aodFilterBit = 5,
 Bool_t      enableMonitor=kTRUE,
 TString     monitorOpt="pp",
 Float_t     piPIDCut = 3.0,
 AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidphipp2015,
 Float_t     pi_k0s_PIDCut = 5.0,
 Float_t     massTol = 0.03,
 Float_t     massTolVeto = 0.004,
 Float_t     pLife = 20,
 Float_t     radiuslow = 0.5,
 Float_t     radiushigh = 200,
 Bool_t      Switch = kFALSE,
 Float_t     k0sDCA = 0.3,
 Float_t     k0sCosPoinAn = 0.97,
 Float_t     k0sDaughDCA = 1.0,
 Int_t       NTPCcluster = 70,
 Float_t     maxDiffVzMix = 1.0,
 Float_t     maxDiffMultMix = 10.0,
 Float_t     maxDiffAngleMixDeg = 20.0,
 Int_t       aodN = 68,
 TString     outNameSuffix = "KStarPlusMinus_TestPID",
 Int_t       centr = 0,
 Bool_t      ptDep = kTRUE,
 Float_t     DCAxy = 0.06,
 Bool_t      enableSys = kFALSE,
 Int_t       Sys= 0
 )
{
  //-------------------------------------------
  // event cuts
  //-------------------------------------------
  UInt_t      triggerMask=AliVEvent::kINT7;
  Bool_t      rejectPileUp=kTRUE;
  Double_t    vtxZcut=10.0;//cm, default cut on vtx z
  //   cout<<"EVENTCUTID is    "<<evtCutSetID<<endl;
  if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; //cm
  if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; //cm
  if(evtCutSetID==eventCutSet::kDefaultVtx5) vtxZcut=5.0; //cm
  if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE;

  if(isMC) rejectPileUp=kFALSE;

  //-------------------------------------------
  //mixing settings
  //-------------------------------------------

  Int_t       nmix = 10;
  if (mixingConfigID == eventMixConfig::kMixDefault) nmix = 10;
  if (mixingConfigID == eventMixConfig::k5Evts)      nmix = 5;
  if (mixingConfigID == eventMixConfig::k5Cent)      maxDiffMultMix = 5;

  //
  // -- INITIALIZATION ----------------------------------------------------------------------------
  // retrieve analysis manager
  //

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

   // create the task and configure
    TString taskName = Form("KStarPlusMinus%s%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"));

   AliRsnMiniAnalysisTask* task = new AliRsnMiniAnalysisTask(taskName.Data(),isMC);

   //task->UseESDTriggerMask(AliVEvent::kINT7); //ESD ****** check this *****
   task->SelectCollisionCandidates(triggerMask); //AOD

   //if(isPP)
   task->UseMultiplicity("QUALITY");
   //else task->UseCentrality("V0M");

   // set event mixing options
   task->UseContinuousMix();
   //task->UseBinnedMix();
   task->SetNMix(nmix);
   task->SetMaxDiffVz(maxDiffVzMix);
   task->SetMaxDiffMult(maxDiffMultMix);
   ::Info("AddAnalysisTaskTOFKStar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %\5.3f", nmix, maxDiffVzMix, maxDiffMultMix));

   mgr->AddTask(task);

   //
   // -- EVENT CUTS (same for all configs) ---------------------------------------------------------
   //
   // cut on primary vertex:
   // - 2nd argument --> |Vz| range
   // - 3rd argument --> minimum required number of contributors
   // - 4th argument --> tells if TPC stand-alone vertexes must be accepted

   AliRsnCutPrimaryVertex *cutVertex = new AliRsnCutPrimaryVertex("cutVertex", cutV, 0, kFALSE);
   cutVertex->SetCheckZResolutionSPD();
   cutVertex->SetCheckDispersionSPD();
   cutVertex->SetCheckZDifferenceSPDTrack();

   AliRsnCutEventUtils* cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
   cutEventUtils->SetCheckIncompleteDAQ();
   cutEventUtils->SetCheckSPDClusterVsTrackletBG();

   if(!isMC){ //assume pp data
     cutVertex->SetCheckPileUp(rejectPileUp);// set the check for pileup
     ::Info("AddAnalysisTaskTOFKStar", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF"));
   }

   // define and fill cut set for event cut
   AliRsnCutSet* eventCuts=new AliRsnCutSet("eventCuts",AliRsnTarget::kEvent);
   eventCuts->AddCut(cutEventUtils);
   eventCuts->AddCut(cutVertex);
   eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName()));
   task->SetEventCuts(eventCuts);

   // -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
   //vertex
   Int_t vtxID=task->CreateValue(AliRsnMiniValue::kVz,kFALSE);
   AliRsnMiniOutput* outVtx=task->CreateOutput("eventVtx","HIST","EVENT");
   outVtx->AddAxis(vtxID,240,-12.0,12.0);

   //multiplicity
   Int_t multID=task->CreateValue(AliRsnMiniValue::kMult,kFALSE);
   AliRsnMiniOutput* outMult=task->CreateOutput("eventMult","HIST","EVENT");
   //if(isPP)
   outMult->AddAxis(multID,400,0.5,400.5);
   //else outMult->AddAxis(multID,100,0.,100.);

   TH2F* hvz=new TH2F("hVzVsCent","",100,0.,100., 240,-12.0,12.0);
   task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member

   TH2F* hmc=new TH2F("MultiVsCent","", 100,0.,100., 400,0.5,400.5);
   hmc->GetYaxis()->SetTitle("QUALITY");
   task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member

   //
   // -- PAIR CUTS (common to all resonances) ------------------------------------------------------
   Double_t    minYlab =  -0.5;
   Double_t    maxYlab =  0.5;

   AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
   cutY->SetRangeD(minYlab, maxYlab);

   AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
   cutsPair->AddCut(cutY);
   if (ptDep) {
     cutsPair->SetCutScheme(cutY->GetName());
   } else {
     AliRsnCutMiniPair *cutV0 = new AliRsnCutMiniPair("cutV0", AliRsnCutMiniPair::kContainsV0Daughter);
     cutsPair->AddCut(cutV0);
     cutsPair->SetCutScheme(TString::Format("%s&!%s",cutY->GetName(),cutV0->GetName()).Data());
   }

   //
   // -- CONFIG ANALYSIS --------------------------------------------------------------------------
   gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinusRun2.C");
   //gROOT->LoadMacro("ConfigKStarPlusMinusRun2.C");
   if (isMC) {
     Printf("========================== MC analysis - PID cuts not used");
   } else
     Printf("========================== DATA analysis - PID cuts used");

   if (!ConfigKStarPlusMinusRun2(task, isPP, isMC, piPIDCut, cutPiCandidate, pi_k0s_PIDCut, aodFilterBit, enableMonitor, monitorOpt.Data(), massTol, massTolVeto, pLife, radiuslow, radiushigh, Switch, k0sDCA, k0sCosPoinAn, k0sDaughDCA, NTPCcluster, "", cutsPair, ptDep, DCAxy, enableSys, Sys)) return 0x0;

   //
   // -- CONTAINERS --------------------------------------------------------------------------------
   //
   TString outputFileName = AliAnalysisManager::GetCommonFileName();
   //  outputFileName += ":Rsn";
   Printf("AddTaskKStarPlusMinus - Set OutputFileName : \n %s\n", outputFileName.Data() );

   AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s_%.1f_%.1f_%.2f_%.3f_%.f_%.f_%.f_%.1f_%.2f_%.1f_%.3f_%.1f", outNameSuffix.Data(),piPIDCut,pi_k0s_PIDCut,massTol,massTolVeto,pLife,radiuslow,radiushigh,k0sDCA,k0sCosPoinAn,k0sDaughDCA, DCAxy, Sys), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);

   mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
   mgr->ConnectOutput(task, 1, output);

   return task;
}

<commit_msg>Fix typo in AddTaskKStarPlusMinusRun2.C<commit_after>/***************************************************************************
//            Modified by Kishora Nayak - 14/06/2016
//            Modified by Enrico Fragiacomo - 15/01/2014
//            Modified by Kunal Garg - 04/02/2017
//            Based on AddAnalysisTaskRsnMini
//            pPb specific settings from AddTaskKStarPPB.C
//
// Macro to configure the KStarPlusMinus analysis task
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
//  1) flag to know if running on MC or data
//  2) collision system, whether pp, pPb or PbPb
// --
// Returns:
//  kTRUE  --> initialization successful
//  kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/

//enum ERsnCollType_t { kPP=0,      kPPb,      kPbPb};

enum pairYCutSet { kPairDefault,    // USED ONLY FOR pA
		   kNegative,       // USED ONLY FOR pA
		   kCentral         // USED ONLY FOR pA
                 };

/*enum eventCutSet { kOld = -1,
		   kEvtDefault, //=0
		   kNoPileUpCut, //=1
		   kPileUpMV, //=2
		   kPileUpSPD3, //=3
		   kDefaultVtx8, //=4
		   kDefaultVtx5 //=5
};*/

enum eventCutSet { kEvtDefault=0,
                   kNoPileUpCut, //=1
                   kDefaultVtx12,//=2
                   kDefaultVtx8, //=3
                   kDefaultVtx5, //=4
                   kMCEvtDefault //=5
};

enum eventMixConfig { kDisabled = -1,
		      kMixDefault,     //=0 //10 events, Dvz = 1cm, DC = 10
		      k5Evts,          //=1 //5 events, Dvz = 1cm, DC = 10
		      k5Cent,          //=2 //10 events, Dvz = 1cm, DC = 5
};

AliRsnMiniAnalysisTask *AddTaskKStarPlusMinusRun2
(
 Bool_t      isMC,
 Bool_t      isPP,
 // Int_t     collSyst,
 Float_t     cutV = 10.0,
 Int_t       evtCutSetID = 0,
 Int_t       pairCutSetID = 0,
 Int_t       mixingConfigID = 0,
 Int_t       aodFilterBit = 5,
 Bool_t      enableMonitor=kTRUE,
 TString     monitorOpt="pp",
 Float_t     piPIDCut = 3.0,
 AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidphipp2015,
 Float_t     pi_k0s_PIDCut = 5.0,
 Float_t     massTol = 0.03,
 Float_t     massTolVeto = 0.004,
 Float_t     pLife = 20,
 Float_t     radiuslow = 0.5,
 Float_t     radiushigh = 200,
 Bool_t      Switch = kFALSE,
 Float_t     k0sDCA = 0.3,
 Float_t     k0sCosPoinAn = 0.97,
 Float_t     k0sDaughDCA = 1.0,
 Int_t       NTPCcluster = 70,
 Float_t     maxDiffVzMix = 1.0,
 Float_t     maxDiffMultMix = 10.0,
 Float_t     maxDiffAngleMixDeg = 20.0,
 Int_t       aodN = 68,
 TString     outNameSuffix = "KStarPlusMinus_TestPID",
 Int_t       centr = 0,
 Bool_t      ptDep = kTRUE,
 Float_t     DCAxy = 0.06,
 Bool_t      enableSys = kFALSE,
 Int_t       Sys= 0
 )
{
  //-------------------------------------------
  // event cuts
  //-------------------------------------------
  UInt_t      triggerMask=AliVEvent::kINT7;
  Bool_t      rejectPileUp=kTRUE;
  Double_t    vtxZcut=10.0;//cm, default cut on vtx z
  //   cout<<"EVENTCUTID is    "<<evtCutSetID<<endl;
  if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; //cm
  if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; //cm
  if(evtCutSetID==eventCutSet::kDefaultVtx5) vtxZcut=5.0; //cm
  if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE;

  if(isMC) rejectPileUp=kFALSE;

  //-------------------------------------------
  //mixing settings
  //-------------------------------------------

  Int_t       nmix = 10;
  if (mixingConfigID == eventMixConfig::kMixDefault) nmix = 10;
  if (mixingConfigID == eventMixConfig::k5Evts)      nmix = 5;
  if (mixingConfigID == eventMixConfig::k5Cent)      maxDiffMultMix = 5;

  //
  // -- INITIALIZATION ----------------------------------------------------------------------------
  // retrieve analysis manager
  //

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

   // create the task and configure
    TString taskName = Form("KStarPlusMinus%s%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"));

   AliRsnMiniAnalysisTask* task = new AliRsnMiniAnalysisTask(taskName.Data(),isMC);

   //task->UseESDTriggerMask(AliVEvent::kINT7); //ESD ****** check this *****
   task->SelectCollisionCandidates(triggerMask); //AOD

   //if(isPP)
   task->UseMultiplicity("QUALITY");
   //else task->UseCentrality("V0M");

   // set event mixing options
   task->UseContinuousMix();
   //task->UseBinnedMix();
   task->SetNMix(nmix);
   task->SetMaxDiffVz(maxDiffVzMix);
   task->SetMaxDiffMult(maxDiffMultMix);
   ::Info("AddAnalysisTaskTOFKStar", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %\5.3f", nmix, maxDiffVzMix, maxDiffMultMix));

   mgr->AddTask(task);

   //
   // -- EVENT CUTS (same for all configs) ---------------------------------------------------------
   //
   // cut on primary vertex:
   // - 2nd argument --> |Vz| range
   // - 3rd argument --> minimum required number of contributors
   // - 4th argument --> tells if TPC stand-alone vertexes must be accepted

   AliRsnCutPrimaryVertex *cutVertex = new AliRsnCutPrimaryVertex("cutVertex", cutV, 0, kFALSE);
   cutVertex->SetCheckZResolutionSPD();
   cutVertex->SetCheckDispersionSPD();
   cutVertex->SetCheckZDifferenceSPDTrack();

   AliRsnCutEventUtils* cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
   cutEventUtils->SetCheckIncompleteDAQ();
   cutEventUtils->SetCheckSPDClusterVsTrackletBG();

   if(!isMC){ //assume pp data
     cutVertex->SetCheckPileUp(rejectPileUp);// set the check for pileup
     ::Info("AddAnalysisTaskTOFKStar", Form(":::::::::::::::::: Pile-up rejection mode: %s", (rejectPileUp)?"ON":"OFF"));
   }

   // define and fill cut set for event cut
   AliRsnCutSet* eventCuts=new AliRsnCutSet("eventCuts",AliRsnTarget::kEvent);
   eventCuts->AddCut(cutEventUtils);
   eventCuts->AddCut(cutVertex);
   eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName()));
   task->SetEventCuts(eventCuts);

   // -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
   //vertex
   Int_t vtxID=task->CreateValue(AliRsnMiniValue::kVz,kFALSE);
   AliRsnMiniOutput* outVtx=task->CreateOutput("eventVtx","HIST","EVENT");
   outVtx->AddAxis(vtxID,240,-12.0,12.0);

   //multiplicity
   Int_t multID=task->CreateValue(AliRsnMiniValue::kMult,kFALSE);
   AliRsnMiniOutput* outMult=task->CreateOutput("eventMult","HIST","EVENT");
   //if(isPP)
   outMult->AddAxis(multID,400,0.5,400.5);
   //else outMult->AddAxis(multID,100,0.,100.);

   TH2F* hvz=new TH2F("hVzVsCent","",100,0.,100., 240,-12.0,12.0);
   task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member

   TH2F* hmc=new TH2F("MultiVsCent","", 100,0.,100., 400,0.5,400.5);
   hmc->GetYaxis()->SetTitle("QUALITY");
   task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member

   //
   // -- PAIR CUTS (common to all resonances) ------------------------------------------------------
   Double_t    minYlab =  -0.5;
   Double_t    maxYlab =  0.5;

   AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
   cutY->SetRangeD(minYlab, maxYlab);

   AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
   cutsPair->AddCut(cutY);
   if (ptDep) {
     cutsPair->SetCutScheme(cutY->GetName());
   } else {
     AliRsnCutMiniPair *cutV0 = new AliRsnCutMiniPair("cutV0", AliRsnCutMiniPair::kContainsV0Daughter);
     cutsPair->AddCut(cutV0);
     cutsPair->SetCutScheme(TString::Format("%s&!%s",cutY->GetName(),cutV0->GetName()).Data());
   }

   //
   // -- CONFIG ANALYSIS --------------------------------------------------------------------------
   gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPlusMinusRun2.C");
   //gROOT->LoadMacro("ConfigKStarPlusMinusRun2.C");
   if (isMC) {
     Printf("========================== MC analysis - PID cuts not used");
   } else
     Printf("========================== DATA analysis - PID cuts used");

   if (!ConfigKStarPlusMinusRun2(task, isPP, isMC, piPIDCut, cutPiCandidate, pi_k0s_PIDCut, aodFilterBit, enableMonitor, monitorOpt.Data(), massTol, massTolVeto, pLife, radiuslow, radiushigh, Switch, k0sDCA, k0sCosPoinAn, k0sDaughDCA, NTPCcluster, "", cutsPair, ptDep, DCAxy, enableSys, Sys)) return 0x0;

   //
   // -- CONTAINERS --------------------------------------------------------------------------------
   //
   TString outputFileName = AliAnalysisManager::GetCommonFileName();
   //  outputFileName += ":Rsn";
   Printf("AddTaskKStarPlusMinus - Set OutputFileName : \n %s\n", outputFileName.Data() );

   AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s_%.1f_%.1f_%.2f_%.3f_%.f_%.f_%.f_%.1f_%.2f_%.1f_%.3f_%.1f", outNameSuffix.Data(),piPIDCut,pi_k0s_PIDCut,massTol,massTolVeto,pLife,radiuslow,radiushigh,k0sDCA,k0sCosPoinAn,k0sDaughDCA, DCAxy, Sys), TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName);

   mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
   mgr->ConnectOutput(task, 1, output);

   return task;
}

<|endoftext|>


<commit_before>#include "Continuous.h"
#include "Bpe.h"
#include "../BaseDistributions/BaseDistribution.h"
ContinuousBpe::ContinuousBpe(const Options& iOptions, const Data& iData) : Continuous(iOptions, iData),
      mInterpolator(NULL),
      mUseStep(false) {
   // TODO: Use a distribution outside the ensemble
   std::string distributionTag;
   // Tag of distribution to use outside ensemble
   // iOptions. getRequiredValue("distribution", distributionTag);
   // mBaseDistribution = BaseDistribution::getScheme(distributionTag, iData);

   // Note about interpolation
   // The classical approach is to count fraction of members below the threshold. In this case the
   // Cdfs are:
   //    0    (below ens)
   //    0.25 (between 1st pair)
   //    0.50 (between 2nd pair)
   //    0.75 (between 3rd pair)
   //    1    (above ens)
   // To achieve this, a step interpolator is used with points (0.25, ens1), ... (1, ens4)
   //
   // Linear interpolation can also be used. In this case the interpolation points are different:
   // (0, ens1), (0.333, ens2), (0.667, ens3), (1, ens4)
   // The difference in the x points is handled by mUseStep

   std::string interpolatorTag;
   //! Tag of interpolation scheme to use between ensemble members
   //! If not specified, use a step function
   if(iOptions.getValue("interp", interpolatorTag))
      mInterpolator = Interpolator::getScheme(interpolatorTag, iData);
   else {
      mUseStep = true;
      mInterpolator = Interpolator::getScheme(Options("tag=step class=InterpolatorStep"), iData);
   }

   mHandleOutside = false;
}
ContinuousBpe::~ContinuousBpe() {
   //delete mBaseDistribution;
   delete mInterpolator;
}

float ContinuousBpe::getCdfCore(float iX, const Ensemble& iEnsemble, const Parameters& iParameters) const {
   std::vector<float> x;
   std::vector<float> y;
   getXY(iEnsemble, x, y);

   if(x.size() == 0)
      return Global::MV;

   float cdf = Global::MV;
   // Below ensemble
   if(iX < x[0]) {
      // TODO:
      return 0;
   }
   // Above ensemble
   else if(iX > x[x.size()-1]) {
      // TODO:
      return 1;
   }
   // Inside ensemble
   else {
      if(x.size() == 1)
         return 0.5;
      cdf = mInterpolator->interpolate(iX, x, y);
   }

   return cdf;
}
float ContinuousBpe::getPdfCore(float iX, const Ensemble& iEnsemble, const Parameters& iParameters) const {
   if(!Global::isValid(iEnsemble.getMin()) || !Global::isValid(iEnsemble.getMax()))
      return Global::MV;
   if(iX < iEnsemble.getMin())
      return 0;
   if(iX > iEnsemble.getMax())
      return 0;
   else {
      std::vector<float> x;
      std::vector<float> y;
      getXY(iEnsemble, x, y);
      return mInterpolator->slope(iX, x, y);
   }
}

float ContinuousBpe::getInvCore(float iCdf, const Ensemble& iEnsemble, const Parameters& iParameters) const {
   std::vector<float> x;
   std::vector<float> y;
   getXY(iEnsemble, x, y);

   if(x.size() == 0)
      return Global::MV;

   float x0 = Global::MV;
   // Below ensemble
   if(iCdf <= y[0]) {
      // TODO:
      x0 = x[0];
   }
   // Above ensemble
   else if(iCdf >= y[y.size()-1]) {
      // TODO:
      x0 = x[x.size()-1];
   }
   // Inside ensemble
   else {
      x0 = mInterpolator->interpolate(iCdf, y, x);
   }

   return x0;
}

void ContinuousBpe::getXY(const Ensemble& iEnsemble, std::vector<float>& iX, std::vector<float>& iY) const {
   int N = iEnsemble.size();
   int Nvalid = 0;
   iX.clear();
   iY.clear();
   // Create x and y vectors for interpolation
   for(int i = 0; i < N; i++) {
      if(Global::isValid(iEnsemble[i])) {
         Nvalid++;
         iX.push_back(iEnsemble[i]);
      }
   }
   std::sort(iX.begin(), iX.end());

   for(int i = 1; i <= Nvalid; i++) {
      if(mUseStep)
         iY.push_back((float) i/(Nvalid));
      else
         iY.push_back((float) (i-1)/(Nvalid-1));
   }
   assert(iX.size() == iY.size());
}
<commit_msg>Compute BPE probability on boundaries correctly<commit_after>#include "Continuous.h"
#include "Bpe.h"
#include "../Variables/Variable.h"
#include "../BaseDistributions/BaseDistribution.h"
ContinuousBpe::ContinuousBpe(const Options& iOptions, const Data& iData) : Continuous(iOptions, iData),
      mInterpolator(NULL),
      mUseStep(false) {
   // TODO: Use a distribution outside the ensemble
   std::string distributionTag;
   // Tag of distribution to use outside ensemble
   // iOptions. getRequiredValue("distribution", distributionTag);
   // mBaseDistribution = BaseDistribution::getScheme(distributionTag, iData);

   // Note about interpolation
   // The classical approach is to count fraction of members below the threshold. In this case the
   // Cdfs are:
   //    0    (below ens)
   //    0.25 (between 1st pair)
   //    0.50 (between 2nd pair)
   //    0.75 (between 3rd pair)
   //    1    (above ens)
   // To achieve this, a step interpolator is used with points (0.25, ens1), ... (1, ens4)
   //
   // Linear interpolation can also be used. In this case the interpolation points are different:
   // (0, ens1), (0.333, ens2), (0.667, ens3), (1, ens4)
   // The difference in the x points is handled by mUseStep

   std::string interpolatorTag;
   //! Tag of interpolation scheme to use between ensemble members
   //! If not specified, use a step function
   if(iOptions.getValue("interp", interpolatorTag))
      mInterpolator = Interpolator::getScheme(interpolatorTag, iData);
   else {
      mUseStep = true;
      mInterpolator = Interpolator::getScheme(Options("tag=step class=InterpolatorStep"), iData);
   }

   mHandleOutside = false;
}
ContinuousBpe::~ContinuousBpe() {
   //delete mBaseDistribution;
   delete mInterpolator;
}

float ContinuousBpe::getCdfCore(float iX, const Ensemble& iEnsemble, const Parameters& iParameters) const {
   std::vector<float> x;
   std::vector<float> y;
   getXY(iEnsemble, x, y);

   const Variable* var = Variable::get(iEnsemble.getVariable());
   // On the boundaries, use the count of members, instead of interpolating
   if(   (var->isLowerDiscrete() && var->getMin() == iX)
      || (var->isUpperDiscrete() && var->getMax() == iX)) {
      int num = 0;
      int total = 0;
      for(int i = 0; i < iEnsemble.size(); i++) {
         float value = iEnsemble[i];
         if(Global::isValid(value)) {
            if(value == iX)
               num++;
            total++;
         }
      }
      if(total == 0)
         return Global::MV;
      if(total == 1 && num == 1 && var->getMin() == iX)
         return 1;
      if(total == 1 && num == 1 && var->getMax() == iX)
         return 0;

      if(num == 0 && var->getMin() == iX)
         return 0;
      else if(num == 0 && var->getMax() == iX)
         return 1;

      if(var->getMin() == iX) {
         // Lower boundary
         if(mUseStep)
            return (float) num/total;
         else
            return (float) (num-1)/(total-1);
      }
      else {
         // Upper boundary
         if(mUseStep)
            return (float) 1-num/total;
         else
            return (float) 1-(num-1)/(total-1);
      }
   }

   if(x.size() == 0)
      return Global::MV;

   float cdf = Global::MV;
   // Below ensemble
   if(iX < x[0]) {
      // TODO:
      return 0;
   }
   // Above ensemble
   else if(iX > x[x.size()-1]) {
      // TODO:
      return 1;
   }
   // Inside ensemble
   else {
      if(x.size() == 1)
         return 0.5;
      cdf = mInterpolator->interpolate(iX, x, y);
   }

   return cdf;
}
float ContinuousBpe::getPdfCore(float iX, const Ensemble& iEnsemble, const Parameters& iParameters) const {
   if(!Global::isValid(iEnsemble.getMin()) || !Global::isValid(iEnsemble.getMax()))
      return Global::MV;
   if(iX < iEnsemble.getMin())
      return 0;
   if(iX > iEnsemble.getMax())
      return 0;
   else {
      std::vector<float> x;
      std::vector<float> y;
      getXY(iEnsemble, x, y);
      return mInterpolator->slope(iX, x, y);
   }
}

float ContinuousBpe::getInvCore(float iCdf, const Ensemble& iEnsemble, const Parameters& iParameters) const {
   std::vector<float> x;
   std::vector<float> y;
   getXY(iEnsemble, x, y);

   if(x.size() == 0)
      return Global::MV;

   float x0 = Global::MV;
   // Below ensemble
   if(iCdf <= y[0]) {
      // TODO:
      x0 = x[0];
   }
   // Above ensemble
   else if(iCdf >= y[y.size()-1]) {
      // TODO:
      x0 = x[x.size()-1];
   }
   // Inside ensemble
   else {
      x0 = mInterpolator->interpolate(iCdf, y, x);
   }

   return x0;
}

void ContinuousBpe::getXY(const Ensemble& iEnsemble, std::vector<float>& iX, std::vector<float>& iY) const {
   int N = iEnsemble.size();
   int Nvalid = 0;
   iX.clear();
   iY.clear();
   // Create x and y vectors for interpolation
   for(int i = 0; i < N; i++) {
      if(Global::isValid(iEnsemble[i])) {
         Nvalid++;
         iX.push_back(iEnsemble[i]);
      }
   }
   std::sort(iX.begin(), iX.end());

   for(int i = 1; i <= Nvalid; i++) {
      if(mUseStep)
         iY.push_back((float) i/(Nvalid));
      else
         iY.push_back((float) (i-1)/(Nvalid-1));
   }
   assert(iX.size() == iY.size());
}
<|endoftext|>


<commit_before>// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*
	The initial source for the model's creation came from the document of
	Z. Qawaqneh et al.: "Deep Convolutional Neural Network for Age Estimation
	based on VGG-Face Model". However, our research has led us to significant
	improvements in the CNN model, allowing us to estimate the age of a person
	outperforming the state-of-the-art results in terms of the exact accuracy
	and for 1-off accuracy.

	This model is thus an age predictor leveraging a ResNet-10 architecture and
	trained using a private dataset of about 110k different labelled images.
	During the training, we used an optimization and data augmentation pipeline
	and considered several sizes for the entry image.
*/

#include "dlib/data_io.h"
#include "dlib/string.h"
#include <dlib/cmd_line_parser.h>
#include <dlib/image_transforms.h>
#include <dlib/dir_nav.h>
#include <dlib/dnn.h>
#include <dlib/data_io.h>
#include <dlib/image_processing/frontal_face_detector.h>

#include <iostream>
#include <iterator>

using namespace std;
using namespace dlib;

const char* VERSION = "1.0";

// ----------------------------------------------------------------------------------------

// This block of statements defines a Resnet-10 architecture for the age predictor.
// We will use 81 classes (0-80 years old) to predict the age of a face.
const unsigned long number_of_age_classes = 81;

// The resnet basic block.
template<
	int num_filters,
	template<typename> class BN,  // some kind of batch normalization or affine layer
	int stride,
	typename SUBNET
>
using basicblock = BN<con<num_filters, 3, 3, 1, 1, relu<BN<con<num_filters, 3, 3, stride, stride, SUBNET>>>>>;

// A residual making use of the skip layer mechanism.
template<
	template<int, template<typename> class, int, typename> class BLOCK,  // a basic block defined before
	int num_filters,
	template<typename> class BN,  // some kind of batch normalization or affine layer
	typename SUBNET
> // adds the block to the result of tag1 (the subnet)
using residual = add_prev1<BLOCK<num_filters, BN, 1, tag1<SUBNET>>>;

// A residual that does subsampling (we need to subsample the output of the subnet, too).
template<
	template<int, template<typename> class, int, typename> class BLOCK,  // a basic block defined before
	int num_filters,
	template<typename> class BN,
	typename SUBNET
>
using residual_down = add_prev2<avg_pool<2, 2, 2, 2, skip1<tag2<BLOCK<num_filters, BN, 2, tag1<SUBNET>>>>>>;

// Residual block with optional downsampling and batch normalization.
template<
	template<template<int, template<typename> class, int, typename> class, int, template<typename>class, typename> class RESIDUAL,
	template<int, template<typename> class, int, typename> class BLOCK,
	int num_filters,
	template<typename> class BN,
	typename SUBNET
>
using residual_block = relu<RESIDUAL<BLOCK, num_filters, BN, SUBNET>>;

template<int num_filters, typename SUBNET>
using aresbasicblock_down = residual_block<residual_down, basicblock, num_filters, affine, SUBNET>;

// Some useful definitions to design the affine versions for inference.
template<typename SUBNET> using aresbasicblock256 = residual_block<residual, basicblock, 256, affine, SUBNET>;
template<typename SUBNET> using aresbasicblock128 = residual_block<residual, basicblock, 128, affine, SUBNET>;
template<typename SUBNET> using aresbasicblock64  = residual_block<residual, basicblock, 64, affine, SUBNET>;

// Common input for standard resnets.
template<typename INPUT>
using aresnet_input = max_pool<3, 3, 2, 2, relu<affine<con<64, 7, 7, 2, 2, INPUT>>>>;

// Resnet-10 architecture for estimating.
template<typename SUBNET>
using aresnet10_level1 = aresbasicblock256<aresbasicblock_down<256, SUBNET>>;
template<typename SUBNET>
using aresnet10_level2 = aresbasicblock128<aresbasicblock_down<128, SUBNET>>;
template<typename SUBNET>
using aresnet10_level3 = aresbasicblock64<SUBNET>;
// The resnet 10 backbone.
template<typename INPUT>
using aresnet10_backbone = avg_pool_everything<
	aresnet10_level1<
	aresnet10_level2<
	aresnet10_level3<
	aresnet_input<INPUT>>>>>;

using apredictor_t = loss_multiclass_log<fc<number_of_age_classes, aresnet10_backbone<input_rgb_image>>>;

// ----------------------------------------------------------------------------------------

// Helper function to estimage the age
uint8_t get_estimated_age(matrix<float, 1, number_of_age_classes>& p, float& confidence)
{
	float estimated_age = (0.25f * p(0));
	confidence = p(0);

	for (uint16_t i = 1; i < number_of_age_classes; i++) {
		estimated_age += (static_cast<float>(i) * p(i));
		if (p(i) > confidence) confidence = p(i);
	}

	return std::lround(estimated_age);
}

int main(int argc, char** argv) try {
	// Use a parser to set parameters.
	command_line_parser parser;

	parser.add_option("h", "");
	parser.add_option("help", "Displays this information");
	parser.add_option("version", "Display version");
	parser.add_option("predict-age", "Predict the age of a person ./image.jpg", 1);
	parser.parse(argc, argv);

	parser.check_incompatible_options("help", "version");
	parser.check_incompatible_options("help", "predict-age");
	parser.check_incompatible_options("version", "predict-age");

	if (parser.option("help") || parser.option("h"))
	{
		cout << "Usage: ./dnn_age_predictor_v1_ex [options]\n";
		parser.print_options(cout);
		cout << endl << "Note:" << endl << "You will need two different models to predict the age.";
		cout << endl << "First, download and then decompress the age predictor model from: " << endl;
		cout << "http://dlib.net/files/dnn_age_predictor_v1.dat.bz2" << endl;
		cout << "Then, you also need the face landmarking model file from:" << endl;
		cout << "http://dlib.net/files/shape_predictor_5_face_landmarks.dat.bz2" << endl;
		cout << endl << endl;
		return EXIT_SUCCESS;
	}
	if (parser.option("version"))
	{
		cout << "dnn_age_predictor_v1_ex v" << VERSION
			 << "\nCompiled: " << __TIME__ << " " << __DATE__ << endl << endl;
		return EXIT_SUCCESS;
	}

	if (parser.option("predict-age"))
	{
		// Initialize networks.
		frontal_face_detector detector = get_frontal_face_detector();
		shape_predictor sp;
		deserialize("shape_predictor_5_face_landmarks.dat") >> sp;

		static const char* model_net_filename = "dnn_age_predictor_v1.dat";
		apredictor_t net;
		deserialize(model_net_filename) >> net;

		// Load the source image.
		matrix<rgb_pixel> in;
		load_image(in, parser.option("predict-age").argument(0));

		// Usea Softmax for the last layer to estimate the age.
		softmax<apredictor_t::subnet_type> snet;
		snet.subnet() = net.subnet();

		// Age prediction using machine learning.
		int32_t cur_face = 0;
		for (auto face : detector(in))
		{
			auto shape = sp(in, face);
			if (shape.num_parts())
			{
				float confidence;
				matrix<rgb_pixel> face_chip;
				extract_image_chip(in, get_face_chip_details(shape, 64), face_chip);
				matrix<float, 1, number_of_age_classes> p = mat(snet(face_chip));
				cout << "face#" << cur_face++ << " - age prediction: " << to_string(get_estimated_age(p, confidence)) << " years old";
				cout << std::fixed << std::setprecision(1) << " [" << (confidence * 100.0f) << "%]" << endl;
			}
		}
		return EXIT_SUCCESS;
	}
}
catch(std::exception& e)
{
    cout << e.what() << endl;
}<commit_msg>Delete dnn_age_predictor_v1_ex.cpp<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "PresetsDataView.h"

#include <absl/strings/str_cat.h>
#include <absl/strings/str_split.h>
#include <errno.h>

#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <filesystem>
#include <functional>

#include "App.h"
#include "CoreUtils.h"
#include "DataViewTypes.h"
#include "OrbitBase/Logging.h"
#include "OrbitBase/SafeStrerror.h"
#include "PresetLoadState.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"

using orbit_client_protos::PresetFile;
using orbit_client_protos::PresetInfo;

constexpr const char* kLoadableColumnName = "Loadable";
constexpr const char* kPresetColumnName = "Preset";
constexpr const char* kModulesColumnName = "Modules";
constexpr const char* kHookedFunctionsColumnName = "Hooked Functions";

constexpr const float kLoadableColumnWidth = 0.14f;
constexpr const float kPresetColumnWidth = 0.34f;
constexpr const float kModulesColumnWidth = 0.34f;
constexpr const float kHookedFunctionsColumnWidth = 0.16f;

namespace {
std::string GetLoadStateString(OrbitApp* app,
                               const std::shared_ptr<orbit_client_protos::PresetFile>& preset) {
  PresetLoadState load_state = app->GetPresetLoadState(preset);
  return load_state.GetName();
}
}  // namespace

PresetsDataView::PresetsDataView(OrbitApp* app) : DataView(DataViewType::kPresets, app) {}

std::string PresetsDataView::GetModulesList(const std::vector<ModuleView>& modules) const {
  return absl::StrJoin(modules, "\n", [](std::string* out, const ModuleView& module) {
    absl::StrAppend(out, module.module_name);
  });
}

std::string PresetsDataView::GetFunctionCountList(const std::vector<ModuleView>& modules) const {
  return absl::StrJoin(modules, "\n", [](std::string* out, const ModuleView& module) {
    absl::StrAppend(out, module.function_count);
  });
}

const std::vector<DataView::Column>& PresetsDataView::GetColumns() {
  static const std::vector<Column> columns = [] {
    std::vector<Column> columns;
    columns.resize(kNumColumns);
    columns[kColumnLoadState] = {kLoadableColumnName, kLoadableColumnWidth,
                                 SortingOrder::kAscending};
    columns[kColumnSessionName] = {kPresetColumnName, kPresetColumnWidth, SortingOrder::kAscending};
    columns[kColumnModules] = {kModulesColumnName, kModulesColumnWidth, SortingOrder::kAscending};
    columns[kColumnFunctionCount] = {kHookedFunctionsColumnName, kHookedFunctionsColumnWidth,
                                     SortingOrder::kAscending};
    return columns;
  }();
  return columns;
}

std::string PresetsDataView::GetValue(int row, int column) {
  const std::shared_ptr<PresetFile>& preset = GetPreset(row);

  switch (column) {
    case kColumnLoadState:
      return GetLoadStateString(app_, preset);
    case kColumnSessionName:
      return std::filesystem::path(preset->file_name()).filename().string();
    case kColumnModules:
      return GetModulesList(GetModules(row));
    case kColumnFunctionCount:
      return GetFunctionCountList(GetModules(row));
    default:
      return "";
  }
}

std::string PresetsDataView::GetToolTip(int row, int /*column*/) {
  const std::shared_ptr<PresetFile>& preset = GetPreset(row);
  return absl::StrCat(preset->file_name(),
                      app_->GetPresetLoadState(preset).state == PresetLoadState::kNotLoadable
                          ? "

None of the modules in the preset can be loaded."
                          : "");
}

void PresetsDataView::DoSort() {
  bool ascending = sorting_orders_[sorting_column_] == SortingOrder::kAscending;
  std::function<bool(int a, int b)> sorter = nullptr;

  switch (sorting_column_) {
    case kColumnLoadState:
      sorter = [&](int a, int b) {
        return orbit_core::Compare(app_->GetPresetLoadState(presets_[a]).state,
                                   app_->GetPresetLoadState(presets_[b]).state, ascending);
      };
      break;
    case kColumnSessionName:
      sorter = [&](int a, int b) {
        return orbit_core::Compare(presets_[a]->file_name(), presets_[b]->file_name(), ascending);
      };
      break;
    default:
      break;
  }

  if (sorter) {
    std::stable_sort(indices_.begin(), indices_.end(), sorter);
  }
}

const std::string PresetsDataView::kMenuActionLoad = "Load Preset";
const std::string PresetsDataView::kMenuActionDelete = "Delete Preset";

std::vector<std::string> PresetsDataView::GetContextMenu(int clicked_index,
                                                         const std::vector<int>& selected_indices) {
  std::vector<std::string> menu;
  // Note that the UI already enforces a single selection.
  if (selected_indices.size() == 1) {
    const std::shared_ptr<PresetFile>& preset = GetPreset(selected_indices[0]);
    if (app_->GetPresetLoadState(preset).state != PresetLoadState::kNotLoadable) {
      menu.emplace_back(kMenuActionLoad);
    }
    menu.emplace_back(kMenuActionDelete);
  }
  Append(menu, DataView::GetContextMenu(clicked_index, selected_indices));
  return menu;
}

void PresetsDataView::OnContextMenu(const std::string& action, int menu_index,
                                    const std::vector<int>& item_indices) {
  if (action == kMenuActionLoad) {
    if (item_indices.size() != 1) {
      return;
    }
    const std::shared_ptr<PresetFile>& preset = GetPreset(item_indices[0]);
    app_->LoadPreset(preset);

  } else if (action == kMenuActionDelete) {
    if (item_indices.size() != 1) {
      return;
    }
    int row = item_indices[0];
    const std::shared_ptr<PresetFile>& preset = GetPreset(row);
    const std::string& filename = preset->file_name();
    int ret = remove(filename.c_str());
    if (ret == 0) {
      presets_.erase(presets_.begin() + indices_[row]);
      OnDataChanged();
    } else {
      ERROR("Deleting preset \"%s\": %s", filename, SafeStrerror(errno));
      app_->SendErrorToUi("Error deleting preset",
                          absl::StrFormat("Could not delete preset \"%s\".", filename));
    }

  } else {
    DataView::OnContextMenu(action, menu_index, item_indices);
  }
}

void PresetsDataView::OnDoubleClicked(int index) {
  const std::shared_ptr<PresetFile>& preset = GetPreset(index);
  if (app_->GetPresetLoadState(preset).state != PresetLoadState::kNotLoadable) {
    app_->LoadPreset(preset);
  }
}

void PresetsDataView::DoFilter() {
  std::vector<uint64_t> indices;

  std::vector<std::string> tokens = absl::StrSplit(ToLower(filter_), ' ');

  for (size_t i = 0; i < presets_.size(); ++i) {
    const PresetFile& preset = *presets_[i];
    std::string name = ToLower(std::filesystem::path(preset.file_name()).filename().string());

    bool match = true;

    for (std::string& filter_token : tokens) {
      if (name.find(filter_token) == std::string::npos) {
        match = false;
        break;
      }
    }

    if (match) {
      indices.push_back(i);
    }
  }

  indices_ = std::move(indices);
}

void PresetsDataView::OnDataChanged() {
  indices_.resize(presets_.size());
  modules_.resize(presets_.size());
  for (size_t i = 0; i < presets_.size(); ++i) {
    indices_[i] = i;
    std::vector<ModuleView> modules;
    for (const auto& pair : presets_[i]->preset_info().path_to_module()) {
      modules.emplace_back(std::filesystem::path(pair.first).filename().string(),
                           pair.second.function_hashes_size());
    }
    modules_[i] = std::move(modules);
  }

  DataView::OnDataChanged();
}

bool PresetsDataView::GetDisplayColor(int row, int /*column*/, unsigned char& red,
                                      unsigned char& green, unsigned char& blue) {
  const std::shared_ptr<PresetFile> preset = GetPreset(row);
  PresetLoadState load_state = app_->GetPresetLoadState(preset);
  load_state.GetDisplayColor(red, green, blue);
  return true;
}

void PresetsDataView::SetPresets(const std::vector<std::shared_ptr<PresetFile> >& presets) {
  presets_ = presets;
  OnDataChanged();
}

const std::shared_ptr<PresetFile>& PresetsDataView::GetPreset(unsigned int row) const {
  return presets_[indices_[row]];
}
const std::vector<PresetsDataView::ModuleView>& PresetsDataView::GetModules(uint32_t row) const {
  return modules_[indices_[row]];
}
<commit_msg>Address lint warning in PresetsDataView<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "PresetsDataView.h"

#include <absl/strings/str_cat.h>
#include <absl/strings/str_split.h>
#include <errno.h>

#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <filesystem>
#include <functional>

#include "App.h"
#include "CoreUtils.h"
#include "DataViewTypes.h"
#include "OrbitBase/Logging.h"
#include "OrbitBase/SafeStrerror.h"
#include "PresetLoadState.h"
#include "absl/strings/str_format.h"
#include "absl/strings/str_join.h"

using orbit_client_protos::PresetFile;

constexpr const char* kLoadableColumnName = "Loadable";
constexpr const char* kPresetColumnName = "Preset";
constexpr const char* kModulesColumnName = "Modules";
constexpr const char* kHookedFunctionsColumnName = "Hooked Functions";

constexpr const float kLoadableColumnWidth = 0.14f;
constexpr const float kPresetColumnWidth = 0.34f;
constexpr const float kModulesColumnWidth = 0.34f;
constexpr const float kHookedFunctionsColumnWidth = 0.16f;

namespace {
std::string GetLoadStateString(OrbitApp* app,
                               const std::shared_ptr<orbit_client_protos::PresetFile>& preset) {
  PresetLoadState load_state = app->GetPresetLoadState(preset);
  return load_state.GetName();
}
}  // namespace

PresetsDataView::PresetsDataView(OrbitApp* app) : DataView(DataViewType::kPresets, app) {}

std::string PresetsDataView::GetModulesList(const std::vector<ModuleView>& modules) const {
  return absl::StrJoin(modules, "\n", [](std::string* out, const ModuleView& module) {
    absl::StrAppend(out, module.module_name);
  });
}

std::string PresetsDataView::GetFunctionCountList(const std::vector<ModuleView>& modules) const {
  return absl::StrJoin(modules, "\n", [](std::string* out, const ModuleView& module) {
    absl::StrAppend(out, module.function_count);
  });
}

const std::vector<DataView::Column>& PresetsDataView::GetColumns() {
  static const std::vector<Column> columns = [] {
    std::vector<Column> columns;
    columns.resize(kNumColumns);
    columns[kColumnLoadState] = {kLoadableColumnName, kLoadableColumnWidth,
                                 SortingOrder::kAscending};
    columns[kColumnSessionName] = {kPresetColumnName, kPresetColumnWidth, SortingOrder::kAscending};
    columns[kColumnModules] = {kModulesColumnName, kModulesColumnWidth, SortingOrder::kAscending};
    columns[kColumnFunctionCount] = {kHookedFunctionsColumnName, kHookedFunctionsColumnWidth,
                                     SortingOrder::kAscending};
    return columns;
  }();
  return columns;
}

std::string PresetsDataView::GetValue(int row, int column) {
  const std::shared_ptr<PresetFile>& preset = GetPreset(row);

  switch (column) {
    case kColumnLoadState:
      return GetLoadStateString(app_, preset);
    case kColumnSessionName:
      return std::filesystem::path(preset->file_name()).filename().string();
    case kColumnModules:
      return GetModulesList(GetModules(row));
    case kColumnFunctionCount:
      return GetFunctionCountList(GetModules(row));
    default:
      return "";
  }
}

std::string PresetsDataView::GetToolTip(int row, int /*column*/) {
  const std::shared_ptr<PresetFile>& preset = GetPreset(row);
  return absl::StrCat(preset->file_name(),
                      app_->GetPresetLoadState(preset).state == PresetLoadState::kNotLoadable
                          ? "

None of the modules in the preset can be loaded."
                          : "");
}

void PresetsDataView::DoSort() {
  bool ascending = sorting_orders_[sorting_column_] == SortingOrder::kAscending;
  std::function<bool(int a, int b)> sorter = nullptr;

  switch (sorting_column_) {
    case kColumnLoadState:
      sorter = [&](int a, int b) {
        return orbit_core::Compare(app_->GetPresetLoadState(presets_[a]).state,
                                   app_->GetPresetLoadState(presets_[b]).state, ascending);
      };
      break;
    case kColumnSessionName:
      sorter = [&](int a, int b) {
        return orbit_core::Compare(presets_[a]->file_name(), presets_[b]->file_name(), ascending);
      };
      break;
    default:
      break;
  }

  if (sorter) {
    std::stable_sort(indices_.begin(), indices_.end(), sorter);
  }
}

const std::string PresetsDataView::kMenuActionLoad = "Load Preset";
const std::string PresetsDataView::kMenuActionDelete = "Delete Preset";

std::vector<std::string> PresetsDataView::GetContextMenu(int clicked_index,
                                                         const std::vector<int>& selected_indices) {
  std::vector<std::string> menu;
  // Note that the UI already enforces a single selection.
  if (selected_indices.size() == 1) {
    const std::shared_ptr<PresetFile>& preset = GetPreset(selected_indices[0]);
    if (app_->GetPresetLoadState(preset).state != PresetLoadState::kNotLoadable) {
      menu.emplace_back(kMenuActionLoad);
    }
    menu.emplace_back(kMenuActionDelete);
  }
  Append(menu, DataView::GetContextMenu(clicked_index, selected_indices));
  return menu;
}

void PresetsDataView::OnContextMenu(const std::string& action, int menu_index,
                                    const std::vector<int>& item_indices) {
  if (action == kMenuActionLoad) {
    if (item_indices.size() != 1) {
      return;
    }
    const std::shared_ptr<PresetFile>& preset = GetPreset(item_indices[0]);
    app_->LoadPreset(preset);

  } else if (action == kMenuActionDelete) {
    if (item_indices.size() != 1) {
      return;
    }
    int row = item_indices[0];
    const std::shared_ptr<PresetFile>& preset = GetPreset(row);
    const std::string& filename = preset->file_name();
    int ret = remove(filename.c_str());
    if (ret == 0) {
      presets_.erase(presets_.begin() + indices_[row]);
      OnDataChanged();
    } else {
      ERROR("Deleting preset \"%s\": %s", filename, SafeStrerror(errno));
      app_->SendErrorToUi("Error deleting preset",
                          absl::StrFormat("Could not delete preset \"%s\".", filename));
    }

  } else {
    DataView::OnContextMenu(action, menu_index, item_indices);
  }
}

void PresetsDataView::OnDoubleClicked(int index) {
  const std::shared_ptr<PresetFile>& preset = GetPreset(index);
  if (app_->GetPresetLoadState(preset).state != PresetLoadState::kNotLoadable) {
    app_->LoadPreset(preset);
  }
}

void PresetsDataView::DoFilter() {
  std::vector<uint64_t> indices;

  std::vector<std::string> tokens = absl::StrSplit(ToLower(filter_), ' ');

  for (size_t i = 0; i < presets_.size(); ++i) {
    const PresetFile& preset = *presets_[i];
    std::string name = ToLower(std::filesystem::path(preset.file_name()).filename().string());

    bool match = true;

    for (std::string& filter_token : tokens) {
      if (name.find(filter_token) == std::string::npos) {
        match = false;
        break;
      }
    }

    if (match) {
      indices.push_back(i);
    }
  }

  indices_ = std::move(indices);
}

void PresetsDataView::OnDataChanged() {
  indices_.resize(presets_.size());
  modules_.resize(presets_.size());
  for (size_t i = 0; i < presets_.size(); ++i) {
    indices_[i] = i;
    std::vector<ModuleView> modules;
    for (const auto& pair : presets_[i]->preset_info().path_to_module()) {
      modules.emplace_back(std::filesystem::path(pair.first).filename().string(),
                           pair.second.function_hashes_size());
    }
    modules_[i] = std::move(modules);
  }

  DataView::OnDataChanged();
}

bool PresetsDataView::GetDisplayColor(int row, int /*column*/, unsigned char& red,
                                      unsigned char& green, unsigned char& blue) {
  const std::shared_ptr<PresetFile> preset = GetPreset(row);
  PresetLoadState load_state = app_->GetPresetLoadState(preset);
  load_state.GetDisplayColor(red, green, blue);
  return true;
}

void PresetsDataView::SetPresets(const std::vector<std::shared_ptr<PresetFile> >& presets) {
  presets_ = presets;
  OnDataChanged();
}

const std::shared_ptr<PresetFile>& PresetsDataView::GetPreset(unsigned int row) const {
  return presets_[indices_[row]];
}
const std::vector<PresetsDataView::ModuleView>& PresetsDataView::GetModules(uint32_t row) const {
  return modules_[indices_[row]];
}
<|endoftext|>


<commit_before>/*
   Copyright (c) 2009-2011, Jack Poulson
   All rights reserved.

   This file is part of Elemental.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

    - Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

    - Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

    - Neither the name of the owner nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE.
*/

// Distributed E := alpha (A^{T/H} B^{T/H} + C^{T/H} D^{T/H}) + beta E
template<typename T>
inline void
elemental::basic::internal::Trr2kTTNT
( UpperOrLower uplo,
  Orientation orientationOfA, Orientation orientationOfB,
  Orientation orientationOfC, Orientation orientationOfD,
  T alpha, const DistMatrix<T,MC,MR>& A, const DistMatrix<T,MC,MR>& B,
           const DistMatrix<T,MC,MR>& C, const DistMatrix<T,MC,MR>& D,
  T beta,        DistMatrix<T,MC,MR>& E )
{
#ifndef RELEASE
    PushCallStack("basic::internal::Trr2kTTTT");
    if( E.Height() != E.Width()  || A.Height() != C.Height() ||
        A.Width()  != E.Height() || C.Width()  != E.Height() ||
        B.Height() != E.Width()  || D.Height() != E.Width()  ||
        A.Height() != B.Width()  || C.Height() != D.Width() )
        throw std::logic_error("Nonconformal Trr2kTTTT");
#endif
    const Grid& g = E.Grid();

    DistMatrix<T,MC,MR> AT(g),  A0(g),
                        AB(g),  A1(g),
                                A2(g);
    DistMatrix<T,MC,MR> BL(g), BR(g),
                        B0(g), B1(g), B2(g);

    DistMatrix<T,MC,MR> CT(g),  C0(g),
                        CB(g),  C1(g),
                                C2(g);
    DistMatrix<T,MC,MR> DL(g), DR(g),
                        D0(g), D1(g), D2(g);

    DistMatrix<T,STAR,MC  > A1_STAR_MC(g);
    DistMatrix<T,VR,  STAR> B1_VR_STAR(g);
    DistMatrix<T,STAR,MR  > B1AdjOrTrans_STAR_MR(g);
    DistMatrix<T,STAR,MC  > C1_STAR_MC(g);
    DistMatrix<T,VR,  STAR> D1_VR_STAR(g);
    DistMatrix<T,STAR,MR  > D1AdjOrTrans_STAR_MR(g);

    LockedPartitionDown
    ( A, AT,
         AB, 0 );
    LockedPartitionRight( B, BL, BR, 0 );
    LockedPartitionDown
    ( C, CT,
         CB, 0 );
    LockedPartitionRight( D, DL, DR, 0 );
    while( AT.Height() < A.Height() )
    {
        LockedRepartitionDown
        ( AT,  A0,
         /**/ /**/
               A1,
          AB,  A2 );
        LockedRepartitionRight
        ( BL, /**/ BR,
          B0, /**/ B1, B2 );
        LockedRepartitionDown
        ( CT,  C0,
         /**/ /**/
               C1,
          CB,  C2 );
        LockedRepartitionRight
        ( DL, /**/ DR,
          D0, /**/ D1, D2 );

        A1_STAR_MC.AlignWith( E );
        B1_VR_STAR.AlignWith( E );
        B1AdjOrTrans_STAR_MR.AlignWith( E );
        C1_STAR_MC.AlignWith( E );
        D1_VR_STAR.AlignWith( E );
        D1AdjOrTrans_STAR_MR.AlignWith( E );
        //--------------------------------------------------------------------//
        A1_STAR_MC = A1;
        C1_STAR_MC = C1;
        B1_VR_STAR = B1;
        D1_VR_STAR = D1;
        if( orientationOfB == ADJOINT )
            B1AdjOrTrans_STAR_MR.AdjointFrom( B1_VR_STAR );
        else
            B1AdjOrTrans_STAR_MR.TransposeFrom( B1_VR_STAR );
        if( orientationOfD == ADJOINT )
            D1AdjOrTrans_STAR_MR.AdjointFrom( D1_VR_STAR );
        else
            D1AdjOrTrans_STAR_MR.TransposeFrom( D1_VR_STAR );
        basic::internal::LocalTrr2k
        ( uplo, orientationOfA, orientationOfC,
          alpha, A1_STAR_MC, B1AdjOrTrans_STAR_MR,
                 C1_STAR_MC, D1AdjOrTrans_STAR_MR,
          beta,  E );
        //--------------------------------------------------------------------//
        D1AdjOrTrans_STAR_MR.FreeAlignments();
        D1_VR_STAR.FreeAlignments();
        C1_STAR_MC.FreeAlignments();
        B1AdjOrTrans_STAR_MR.FreeAlignments();
        B1_VR_STAR.FreeAlignments();
        A1_STAR_MC.FreeAlignments();

        SlideLockedPartitionRight
        ( DL,     /**/ DR,
          D0, D1, /**/ D2 );
        SlideLockedPartitionDown
        ( CT,  C0,
               C1,
         /**/ /**/
          CB,  C2 );
        SlideLockedPartitionRight
        ( BL,     /**/ BR,
          B0, B1, /**/ B2 );
        SlideLockedPartitionDown
        ( AT,  A0,
               A1,
         /**/ /**/
          AB,  A2 );
    }
#ifndef RELEASE
    PopCallStack();
#endif
}

<commit_msg>Fixing bug in basic::internal::Trr2kTTTT implementation's function name.<commit_after>/*
   Copyright (c) 2009-2011, Jack Poulson
   All rights reserved.

   This file is part of Elemental.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

    - Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

    - Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

    - Neither the name of the owner nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE.
*/

// Distributed E := alpha (A^{T/H} B^{T/H} + C^{T/H} D^{T/H}) + beta E
template<typename T>
inline void
elemental::basic::internal::Trr2kTTTT
( UpperOrLower uplo,
  Orientation orientationOfA, Orientation orientationOfB,
  Orientation orientationOfC, Orientation orientationOfD,
  T alpha, const DistMatrix<T,MC,MR>& A, const DistMatrix<T,MC,MR>& B,
           const DistMatrix<T,MC,MR>& C, const DistMatrix<T,MC,MR>& D,
  T beta,        DistMatrix<T,MC,MR>& E )
{
#ifndef RELEASE
    PushCallStack("basic::internal::Trr2kTTTT");
    if( E.Height() != E.Width()  || A.Height() != C.Height() ||
        A.Width()  != E.Height() || C.Width()  != E.Height() ||
        B.Height() != E.Width()  || D.Height() != E.Width()  ||
        A.Height() != B.Width()  || C.Height() != D.Width() )
        throw std::logic_error("Nonconformal Trr2kTTTT");
#endif
    const Grid& g = E.Grid();

    DistMatrix<T,MC,MR> AT(g),  A0(g),
                        AB(g),  A1(g),
                                A2(g);
    DistMatrix<T,MC,MR> BL(g), BR(g),
                        B0(g), B1(g), B2(g);

    DistMatrix<T,MC,MR> CT(g),  C0(g),
                        CB(g),  C1(g),
                                C2(g);
    DistMatrix<T,MC,MR> DL(g), DR(g),
                        D0(g), D1(g), D2(g);

    DistMatrix<T,STAR,MC  > A1_STAR_MC(g);
    DistMatrix<T,VR,  STAR> B1_VR_STAR(g);
    DistMatrix<T,STAR,MR  > B1AdjOrTrans_STAR_MR(g);
    DistMatrix<T,STAR,MC  > C1_STAR_MC(g);
    DistMatrix<T,VR,  STAR> D1_VR_STAR(g);
    DistMatrix<T,STAR,MR  > D1AdjOrTrans_STAR_MR(g);

    LockedPartitionDown
    ( A, AT,
         AB, 0 );
    LockedPartitionRight( B, BL, BR, 0 );
    LockedPartitionDown
    ( C, CT,
         CB, 0 );
    LockedPartitionRight( D, DL, DR, 0 );
    while( AT.Height() < A.Height() )
    {
        LockedRepartitionDown
        ( AT,  A0,
         /**/ /**/
               A1,
          AB,  A2 );
        LockedRepartitionRight
        ( BL, /**/ BR,
          B0, /**/ B1, B2 );
        LockedRepartitionDown
        ( CT,  C0,
         /**/ /**/
               C1,
          CB,  C2 );
        LockedRepartitionRight
        ( DL, /**/ DR,
          D0, /**/ D1, D2 );

        A1_STAR_MC.AlignWith( E );
        B1_VR_STAR.AlignWith( E );
        B1AdjOrTrans_STAR_MR.AlignWith( E );
        C1_STAR_MC.AlignWith( E );
        D1_VR_STAR.AlignWith( E );
        D1AdjOrTrans_STAR_MR.AlignWith( E );
        //--------------------------------------------------------------------//
        A1_STAR_MC = A1;
        C1_STAR_MC = C1;
        B1_VR_STAR = B1;
        D1_VR_STAR = D1;
        if( orientationOfB == ADJOINT )
            B1AdjOrTrans_STAR_MR.AdjointFrom( B1_VR_STAR );
        else
            B1AdjOrTrans_STAR_MR.TransposeFrom( B1_VR_STAR );
        if( orientationOfD == ADJOINT )
            D1AdjOrTrans_STAR_MR.AdjointFrom( D1_VR_STAR );
        else
            D1AdjOrTrans_STAR_MR.TransposeFrom( D1_VR_STAR );
        basic::internal::LocalTrr2k
        ( uplo, orientationOfA, orientationOfC,
          alpha, A1_STAR_MC, B1AdjOrTrans_STAR_MR,
                 C1_STAR_MC, D1AdjOrTrans_STAR_MR,
          beta,  E );
        //--------------------------------------------------------------------//
        D1AdjOrTrans_STAR_MR.FreeAlignments();
        D1_VR_STAR.FreeAlignments();
        C1_STAR_MC.FreeAlignments();
        B1AdjOrTrans_STAR_MR.FreeAlignments();
        B1_VR_STAR.FreeAlignments();
        A1_STAR_MC.FreeAlignments();

        SlideLockedPartitionRight
        ( DL,     /**/ DR,
          D0, D1, /**/ D2 );
        SlideLockedPartitionDown
        ( CT,  C0,
               C1,
         /**/ /**/
          CB,  C2 );
        SlideLockedPartitionRight
        ( BL,     /**/ BR,
          B0, B1, /**/ B2 );
        SlideLockedPartitionDown
        ( AT,  A0,
               A1,
         /**/ /**/
          AB,  A2 );
    }
#ifndef RELEASE
    PopCallStack();
#endif
}

<|endoftext|>


<commit_before>//===- CVTypeVisitor.cpp ----------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"

#include "llvm/DebugInfo/CodeView/CodeViewError.h"
#include "llvm/DebugInfo/MSF/ByteStream.h"

using namespace llvm;
using namespace llvm::codeview;

CVTypeVisitor::CVTypeVisitor(TypeVisitorCallbacks &Callbacks)
    : Callbacks(Callbacks) {}

template <typename T>
static Error visitKnownRecord(const CVRecord<TypeLeafKind> &Record,
                              TypeVisitorCallbacks &Callbacks) {
  TypeRecordKind RK = static_cast<TypeRecordKind>(Record.Type);
  T KnownRecord(RK);
  if (auto EC = Callbacks.visitKnownRecord(Record, KnownRecord))
    return EC;
  return Error::success();
}

Error CVTypeVisitor::visitTypeRecord(const CVRecord<TypeLeafKind> &Record) {
  ArrayRef<uint8_t> LeafData = Record.Data;
  if (auto EC = Callbacks.visitTypeBegin(Record))
    return EC;

  switch (Record.Type) {
  default:
    if (auto EC = Callbacks.visitUnknownType(Record))
      return EC;
    break;
#define TYPE_RECORD(EnumName, EnumVal, Name)                                   \
  case EnumName: {                                                             \
    if (auto EC = visitKnownRecord<Name##Record>(Record, Callbacks))           \
      return EC;                                                               \
    break;                                                                     \
  }
#define TYPE_RECORD_ALIAS(EnumName, EnumVal, Name, AliasName)                  \
  TYPE_RECORD(EnumVal, EnumVal, AliasName)
#define MEMBER_RECORD(EnumName, EnumVal, Name)
#include "llvm/DebugInfo/CodeView/TypeRecords.def"
  }

  if (auto EC = Callbacks.visitTypeEnd(Record))
    return EC;

  return Error::success();
}

/// Visits the type records in Data. Sets the error flag on parse failures.
Error CVTypeVisitor::visitTypeStream(const CVTypeArray &Types) {
  for (const auto &I : Types) {
    if (auto EC = visitTypeRecord(I))
      return EC;
  }
  return Error::success();
}
<commit_msg>CodeView: Remove an unused variable<commit_after>//===- CVTypeVisitor.cpp ----------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"

#include "llvm/DebugInfo/CodeView/CodeViewError.h"
#include "llvm/DebugInfo/MSF/ByteStream.h"

using namespace llvm;
using namespace llvm::codeview;

CVTypeVisitor::CVTypeVisitor(TypeVisitorCallbacks &Callbacks)
    : Callbacks(Callbacks) {}

template <typename T>
static Error visitKnownRecord(const CVRecord<TypeLeafKind> &Record,
                              TypeVisitorCallbacks &Callbacks) {
  TypeRecordKind RK = static_cast<TypeRecordKind>(Record.Type);
  T KnownRecord(RK);
  if (auto EC = Callbacks.visitKnownRecord(Record, KnownRecord))
    return EC;
  return Error::success();
}

Error CVTypeVisitor::visitTypeRecord(const CVRecord<TypeLeafKind> &Record) {
  if (auto EC = Callbacks.visitTypeBegin(Record))
    return EC;

  switch (Record.Type) {
  default:
    if (auto EC = Callbacks.visitUnknownType(Record))
      return EC;
    break;
#define TYPE_RECORD(EnumName, EnumVal, Name)                                   \
  case EnumName: {                                                             \
    if (auto EC = visitKnownRecord<Name##Record>(Record, Callbacks))           \
      return EC;                                                               \
    break;                                                                     \
  }
#define TYPE_RECORD_ALIAS(EnumName, EnumVal, Name, AliasName)                  \
  TYPE_RECORD(EnumVal, EnumVal, AliasName)
#define MEMBER_RECORD(EnumName, EnumVal, Name)
#include "llvm/DebugInfo/CodeView/TypeRecords.def"
  }

  if (auto EC = Callbacks.visitTypeEnd(Record))
    return EC;

  return Error::success();
}

/// Visits the type records in Data. Sets the error flag on parse failures.
Error CVTypeVisitor::visitTypeStream(const CVTypeArray &Types) {
  for (const auto &I : Types) {
    if (auto EC = visitTypeRecord(I))
      return EC;
  }
  return Error::success();
}
<|endoftext|>