<commit_before>#include <StdAfx.h>
#include <UI/ViewPane/TreePane.h>
#include <UI/UIFunctions.h>
#include <utility>

namespace viewpane
{
	static std::wstring CLASS = L"TreePane";

	TreePane* TreePane::Create(int paneID, UINT uidLabel, bool bReadOnly)
	{
		auto pane = new (std::nothrow) TreePane();
		if (pane)
		{
			if (uidLabel)
			{
				pane->SetLabel(uidLabel);
				pane->m_bCollapsible = true;
			}

			pane->SetReadOnly(bReadOnly);
			pane->m_paneID = paneID;
		}

		return pane;
	}

	bool TreePane::IsDirty() { return m_bDirty; }

	void TreePane::Initialize(_In_ CWnd* pParent, _In_ HDC hdc)
	{
		ViewPane::Initialize(pParent, hdc);
		m_Tree.Create(pParent, 0);

		// TODO: Don't leave this here
		TVINSERTSTRUCTW tvInsert = {nullptr};
		auto szName = std::wstring(L"TEST");
		tvInsert.hParent = nullptr;
		tvInsert.hInsertAfter = TVI_SORT;
		tvInsert.item.mask = TVIF_CHILDREN | TVIF_TEXT;
		tvInsert.item.cChildren = I_CHILDRENCALLBACK;
		tvInsert.item.pszText = const_cast<LPWSTR>(szName.c_str());
		::SendMessage(m_Tree.GetSafeHwnd(), TVM_INSERTITEMW, 0, reinterpret_cast<LPARAM>(&tvInsert));

		m_bInitialized = true;
	}

	int TreePane::GetMinWidth(_In_ HDC /*hdc*/)
	{
		return 100;
		//return max(
		//	ViewPane::GetMinWidth(hdc), (int) (NUMLISTBUTTONS * m_iButtonWidth + m_iMargin * (NUMLISTBUTTONS - 1)));
	}

	int TreePane::GetFixedHeight()
	{
		auto iHeight = 0;
		if (0 != m_paneID) iHeight += m_iSmallHeightMargin; // Top margin

		const auto labelHeight = GetLabelHeight();

		if (labelHeight)
		{
			iHeight += labelHeight;
		}

		if (m_bCollapsible && !m_bCollapsed)
		{
			iHeight += m_iSmallHeightMargin;
		}

		iHeight += m_iSmallHeightMargin;

		return iHeight;
	}

	int TreePane::GetLines()
	{
		if (m_bCollapsed)
		{
			return 0;
		}

		return 4;
	}

	ULONG TreePane::HandleChange(UINT nID)
	{
		//switch (nID)
		//{
		//}

		return ViewPane::HandleChange(nID);
	}

	void TreePane::DeferWindowPos(
		_In_ HDWP hWinPosInfo,
		_In_ const int x,
		_In_ const int y,
		_In_ const int width,
		_In_ const int height)
	{
		output::DebugPrint(DBGDraw, L"TreePane::DeferWindowPos x:%d y:%d width:%d height:%d \n", x, y, width, height);

		auto curY = y;
		const auto labelHeight = GetLabelHeight();
		if (0 != m_paneID)
		{
			curY += m_iSmallHeightMargin;
		}

		EC_B_S(m_Tree.ShowWindow(m_bCollapsed ? SW_HIDE : SW_SHOW));
		// Layout our label
		ViewPane::DeferWindowPos(hWinPosInfo, x, curY, width, height - (curY - y));

		if (labelHeight)
		{
			curY += labelHeight + m_iSmallHeightMargin;
		}

		auto treeHeight = height - (curY - y) - m_iSmallHeightMargin;

		EC_B_S(::DeferWindowPos(hWinPosInfo, m_Tree.GetSafeHwnd(), nullptr, x, curY, width, treeHeight, SWP_NOZORDER));
	}

	void TreePane::CommitUIValues() {}
} // namespace viewpane<commit_msg>Fix treepane min width<commit_after>#include <StdAfx.h>
#include <UI/ViewPane/TreePane.h>
#include <UI/UIFunctions.h>
#include <utility>

namespace viewpane
{
	static std::wstring CLASS = L"TreePane";

	TreePane* TreePane::Create(int paneID, UINT uidLabel, bool bReadOnly)
	{
		auto pane = new (std::nothrow) TreePane();
		if (pane)
		{
			if (uidLabel)
			{
				pane->SetLabel(uidLabel);
				pane->m_bCollapsible = true;
			}

			pane->SetReadOnly(bReadOnly);
			pane->m_paneID = paneID;
		}

		return pane;
	}

	bool TreePane::IsDirty() { return m_bDirty; }

	void TreePane::Initialize(_In_ CWnd* pParent, _In_ HDC hdc)
	{
		ViewPane::Initialize(pParent, hdc);
		m_Tree.Create(pParent, 0);

		// TODO: Don't leave this here
		TVINSERTSTRUCTW tvInsert = {nullptr};
		auto szName = std::wstring(L"TEST");
		tvInsert.hParent = nullptr;
		tvInsert.hInsertAfter = TVI_SORT;
		tvInsert.item.mask = TVIF_CHILDREN | TVIF_TEXT;
		tvInsert.item.cChildren = I_CHILDRENCALLBACK;
		tvInsert.item.pszText = const_cast<LPWSTR>(szName.c_str());
		::SendMessage(m_Tree.GetSafeHwnd(), TVM_INSERTITEMW, 0, reinterpret_cast<LPARAM>(&tvInsert));

		m_bInitialized = true;
	}

	int TreePane::GetMinWidth(_In_ HDC hdc) { return ViewPane::GetMinWidth(hdc); }

	int TreePane::GetFixedHeight()
	{
		auto iHeight = 0;
		if (0 != m_paneID) iHeight += m_iSmallHeightMargin; // Top margin

		const auto labelHeight = GetLabelHeight();

		if (labelHeight)
		{
			iHeight += labelHeight;
		}

		if (m_bCollapsible && !m_bCollapsed)
		{
			iHeight += m_iSmallHeightMargin;
		}

		iHeight += m_iSmallHeightMargin;

		return iHeight;
	}

	int TreePane::GetLines()
	{
		if (m_bCollapsed)
		{
			return 0;
		}

		return 4;
	}

	ULONG TreePane::HandleChange(UINT nID)
	{
		//switch (nID)
		//{
		//}

		return ViewPane::HandleChange(nID);
	}

	void TreePane::DeferWindowPos(
		_In_ HDWP hWinPosInfo,
		_In_ const int x,
		_In_ const int y,
		_In_ const int width,
		_In_ const int height)
	{
		output::DebugPrint(DBGDraw, L"TreePane::DeferWindowPos x:%d y:%d width:%d height:%d \n", x, y, width, height);

		auto curY = y;
		const auto labelHeight = GetLabelHeight();
		if (0 != m_paneID)
		{
			curY += m_iSmallHeightMargin;
		}

		EC_B_S(m_Tree.ShowWindow(m_bCollapsed ? SW_HIDE : SW_SHOW));
		// Layout our label
		ViewPane::DeferWindowPos(hWinPosInfo, x, curY, width, height - (curY - y));

		if (labelHeight)
		{
			curY += labelHeight + m_iSmallHeightMargin;
		}

		auto treeHeight = height - (curY - y) - m_iSmallHeightMargin;

		EC_B_S(::DeferWindowPos(hWinPosInfo, m_Tree.GetSafeHwnd(), nullptr, x, curY, width, treeHeight, SWP_NOZORDER));
	}

	void TreePane::CommitUIValues() {}
} // namespace viewpane<|endoftext|>


<commit_before>#include <cstdio>
#include <vector>
#include <algorithm>
struct odcinek
{
    int x1,y1,x2,y2,index;
    bool poczatek;
};
inline int sgn(int wartosc)
{
    if(wartosc<0)
        return -1;
    else if(wartosc>0)
        return 1;
    else
        return 0;
}
inline int deg(int x1,int y1,int x2,int y2,int x3,int y3)
{
    return x1*y2+x2*y3+x3*y1-x1*y3-x2*y1-x3*y2;
}
inline bool przecinanie(odcinek odc1,odcinek odc2)
{
    return (sgn(deg(odc1.x1,odc1.y1,odc1.x2,odc1.y2,odc2.x1,odc2.y1))==-1*sgn(deg(odc1.x1,odc1.y1,odc1.x2,odc1.y2,odc2.x2,odc2.y2)) && sgn(deg(odc2.x1,odc2.y1,odc2.x2,odc2.y2,odc1.x1,odc1.y1))==-1*sgn(deg(odc2.x1,odc2.y1,odc2.x2,odc2.y2,odc1.x2,odc1.y2)));
}
inline bool sorting(odcinek odc1,odcinek odc2)
{
    return odc1.x1<odc2.x1;
}
inline bool po_prawej(odcinek odc1,odcinek odc2)
{
    return deg(odc1.x1,odc1.y1,odc1.x2,odc1.y2,odc2.x1,odc2.y1)>0;
}
int szukaj(std::vector<int> &miotla,std::vector <odcinek> &dane,int start,int koniec,odcinek odc2)
{
    if(koniec==start)
        return koniec + po_prawej(dane.at(miotla.at(koniec)),odc2);
    int suma=koniec+start;
    int srodek=(suma+(suma&1))>>1;
    if(po_prawej(dane.at(miotla.at(srodek)),odc2))
        return szukaj(miotla,dane,srodek,koniec,odc2);
    return szukaj(miotla,dane,start,srodek-1,odc2);
}
int main()
{
    int n;
    scanf("%d",&n);
    std::vector <odcinek> dane(2*n);
    for(int i=0; i<n; i++)
    {
        scanf("%d%d%d%d",&dane.at(2*i).x1,&dane.at(2*i).y1,&dane.at(2*i).x2,&dane.at(2*i).y2);
        if(dane.at(2*i).x1>dane.at(2*i).x2)
        {
            std::swap(dane.at(2*i).x1,dane.at(2*i).x2);
            std::swap(dane.at(2*i).y1,dane.at(2*i).y2);
        }
        dane.at(2*i).poczatek=true;
        dane.at(2*i).index=i;
        dane.at(2*i+1).x1=dane.at(2*i).x2;
        dane.at(2*i+1).x2=dane.at(2*i).x1;
        dane.at(2*i+1).y1=dane.at(2*i).y2;
        dane.at(2*i+1).y2=dane.at(2*i).y1;
        dane.at(2*i+1).poczatek=false;
        dane.at(2*i+1).index=i;
    }
    sort(dane.begin(),dane.end(),sorting);
    std::vector <int> miotla;
    bool odp=false;
    for(int i=0; i<2*n && !odp; i++)
    {
        if(dane.at(i).poczatek)
            if(miotla.size())
            {
                int index=szukaj(miotla,dane,0,miotla.size()-1,dane.at(i));
                miotla.insert(miotla.begin()+index,i);
                if(index>0)
                    if(przecinanie(dane.at(miotla.at(index-1)),dane.at(miotla.at(index))))
                    {
                        printf("TRUE\n");
                        return 0;
                    }
                if(index<miotla.size()-1)
                    if(przecinanie(dane.at(miotla.at(index+1)),dane.at(miotla.at(index))))
                        odp=true;
            }
            else
                miotla.push_back(i);
        else
        {
            int index=0;
            while(dane.at(miotla.at(index)).index!=dane.at(i).index)
                index++;
            if(index>0 && index<miotla.size()-1)
                if(przecinanie(dane.at(miotla.at(index-1)),dane.at(miotla.at(index+1))))
                {
                    printf("TRUE\n");
                    return 0;
                }
            miotla.erase(miotla.begin()+index);
        }
    }
    if(odp)
        printf("TRUE\n");
    else
        printf("FALSE\n");
    return 0;
}
<commit_msg>Update zamiatanie.cpp<commit_after>#include <cstdio>
#include <vector>
#include <algorithm>
struct odcinek
{
    int x1,y1,x2,y2,index;
    bool poczatek;
};
inline int sgn(int wartosc)
{
    if(wartosc<0)
        return -1;
    else if(wartosc>0)
        return 1;
    else
        return false;
}
inline int deg(int x1,int y1,int x2,int y2,int x3,int y3)
{
    return x1*y2+x2*y3+x3*y1-x1*y3-x2*y1-x3*y2;
}
inline bool przecinanie(odcinek odc1,odcinek odc2)
{
    return (sgn(deg(odc1.x1,odc1.y1,odc1.x2,odc1.y2,odc2.x1,odc2.y1))==-1*sgn(deg(odc1.x1,odc1.y1,odc1.x2,odc1.y2,odc2.x2,odc2.y2)) && sgn(deg(odc2.x1,odc2.y1,odc2.x2,odc2.y2,odc1.x1,odc1.y1))==-1*sgn(deg(odc2.x1,odc2.y1,odc2.x2,odc2.y2,odc1.x2,odc1.y2)));
}
inline bool sorting(odcinek odc1,odcinek odc2)
{
    return odc1.x1<odc2.x1;
}
inline bool po_prawej(odcinek odc1,odcinek odc2)
{
    return deg(odc1.x1,odc1.y1,odc1.x2,odc1.y2,odc2.x1,odc2.y1)>0;
}
int szukaj(std::vector<int> &miotla,std::vector <odcinek> &dane,int start,int koniec,odcinek odc2)
{
    if(koniec==start)
        return koniec + po_prawej(dane.at(miotla.at(koniec)),odc2);
    int suma=koniec+start;
    int srodek=(suma+(suma&1))>>1;
    if(po_prawej(dane.at(miotla.at(srodek)),odc2))
        return szukaj(miotla,dane,srodek,koniec,odc2);
    return szukaj(miotla,dane,start,srodek-1,odc2);
}
int main()
{
    int n;
    scanf("%d",&n);
    std::vector <odcinek> dane(2*n);
    for(int i=0; i<n; i++)
    {
        scanf("%d%d%d%d",&dane.at(2*i).x1,&dane.at(2*i).y1,&dane.at(2*i).x2,&dane.at(2*i).y2);
        if(dane.at(2*i).x1>dane.at(2*i).x2)
        {
            std::swap(dane.at(2*i).x1,dane.at(2*i).x2);
            std::swap(dane.at(2*i).y1,dane.at(2*i).y2);
        }
        dane.at(2*i).poczatek=true;
        dane.at(2*i).index=i;
        dane.at(2*i+1).x1=dane.at(2*i).x2;
        dane.at(2*i+1).x2=dane.at(2*i).x1;
        dane.at(2*i+1).y1=dane.at(2*i).y2;
        dane.at(2*i+1).y2=dane.at(2*i).y1;
        dane.at(2*i+1).poczatek=false;
        dane.at(2*i+1).index=i;
    }
    sort(dane.begin(),dane.end(),sorting);
    std::vector <int> miotla;
    bool odp=false;
    for(int i=0; i<2*n && !odp; i++)
    {
        if(dane.at(i).poczatek)
            if(miotla.size())
            {
                int index=szukaj(miotla,dane,0,miotla.size()-1,dane.at(i));
                miotla.insert(miotla.begin()+index,i);
                if(index>0)
                    if(przecinanie(dane.at(miotla.at(index-1)),dane.at(miotla.at(index))))
                        odp=true;
                if(index<miotla.size()-1)
                    if(przecinanie(dane.at(miotla.at(index+1)),dane.at(miotla.at(index))))
                        odp=true;
            }
            else
                miotla.push_back(i);
        else
        {
            int index=0;
            while(dane.at(miotla.at(index)).index!=dane.at(i).index)
                index++;
            if(index>0 && index<miotla.size()-1)
                if(przecinanie(dane.at(miotla.at(index-1)),dane.at(miotla.at(index+1))))
                    odp=true;
            miotla.erase(miotla.begin()+index);
        }
    }
    if(odp)
        printf("TRUE\n");
    else
        printf("FALSE\n");
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int main()
{

}<commit_msg>Replace input/output stream with Native IO Board<commit_after>#include <Headers\Native IO Board\MainStream IO\Native MainInput\IO Board.h>

using namespace std;

int main()
{

}<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//

// A very simple utility for converting trajectory files like DCD
// into rigid transformations
//

#include <BALL/KERNEL/system.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/DOCKING/COMMON/poseClustering.h>
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/FORMAT/lineBasedFile.h>

#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"

using namespace BALL;
using namespace std;

int main(int argc, char** argv)
{
	CommandlineParser parpars("Trajectory2RigidTransformation", "converts a trajectory file into a rigid transformation file ", VERSION, String(__DATE__), "Convert, combine and store");

	parpars.registerParameter("i_dcd", "input trajectory file", INFILE, true);
	parpars.registerParameter("i_pdb",  "input pdb-file", INFILE, true);

	parpars.registerParameter("o", "output dat-file name for the rigid transformations", STRING, true, "", true);

	// the manual
	String man = "This tool converts SnapShots of a given TrajectoryFile and the reference PDBFile into a rigid transformation file.\n\nParameters are the input SnapShots as TrajectoryFile (-i_dcd), the corresponding reference pdb file that was originally used to create the TrajectoryFile (-i_pdb) and a naming schema for the resulting transformation file (-o).\n\nOutput of this tool is a file storing each given SnapShot as rigid transformation per line.";

	parpars.setToolManual(man);

	// here we set the types of I/O files, for example sdf is also allowed
	parpars.setSupportedFormats("i_dcd", "dcd");
	parpars.setSupportedFormats("i_pdb", "pdb");
	parpars.setSupportedFormats("o",     "txt");

	parpars.parse(argc, argv);

	//////////////////////////////////////////////////

	// read the input
	PDBFile pdb;
	pdb.open(parpars.get("i_pdb"));
	System sys;
	pdb.read(sys);

	ConformationSet cs;
	cs.setup(sys);
	cs.readDCDFile(parpars.get("i_dcd"));
	cs.resetScoring();

	PoseClustering pc;
	pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::RIGID_RMSD);
	pc.setConformationSet(&cs);

	// now convert
	pc.convertSnaphots2Transformations();
	std::vector< PoseClustering::PosePointer > poses = pc.getPoses();

	String outfile_name = String(parpars.get("o"));
	LineBasedFile file(outfile_name, ios::out);
	if (file.bad())
	{
		Log.error() << "cannot write file " << outfile_name << endl;
		return 2;
	}

	Log << "write rigid poses into file " << outfile_name << endl;

	for (Size i=0; i<poses.size(); i++)
	{
		Eigen::Matrix3f const & rot    = poses[i].trafo->rotation;
		Eigen::Vector3f const & transl = poses[i].trafo->translation;
		file << "A A " << " 0.0 "
			   << rot(0) << " " << rot(1) << " " << rot(2) << " " << transl[0] << " "
				 << rot(3) << " " << rot(4) << " " << rot(5) << " " << transl[1] << " "
				 << rot(6) << " " << rot(7) << " " << rot(8) << " " << transl[2]
				 << endl;
	}

	file.close();

	Log << "done." << endl;

	return 0;
}
<commit_msg>Trajectory2RigidTransformation tool: add decent galaxy outfile format<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//

// A very simple utility for converting trajectory files like DCD
// into rigid transformations
//

#include <BALL/KERNEL/system.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/DOCKING/COMMON/poseClustering.h>
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/FORMAT/lineBasedFile.h>

#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"

using namespace BALL;
using namespace std;

int main(int argc, char** argv)
{
	CommandlineParser parpars("Trajectory2RigidTransformation", "converts a trajectory file into a rigid transformation file ", VERSION, String(__DATE__), "Convert, combine and store");

	parpars.registerParameter("i_dcd", "input trajectory file", INFILE, true);
	parpars.registerParameter("i_pdb",  "input pdb-file", INFILE, true);

	parpars.registerParameter("o", "output dat-file name for the rigid transformations", OUTFILE, true, "", true);

	// the manual
	String man = "This tool converts SnapShots of a given TrajectoryFile and the reference PDBFile into a rigid transformation file.\n\nParameters are the input SnapShots as TrajectoryFile (-i_dcd), the corresponding reference pdb file that was originally used to create the TrajectoryFile (-i_pdb) and a naming schema for the resulting transformation file (-o).\n\nOutput of this tool is a file storing each given SnapShot as rigid transformation per line.";

	parpars.setToolManual(man);

	// here we set the types of I/O files, for example sdf is also allowed
	parpars.setSupportedFormats("i_dcd", "dcd");
	parpars.setSupportedFormats("i_pdb", "pdb");
	parpars.setSupportedFormats("o",     "txt");

	parpars.parse(argc, argv);

	//////////////////////////////////////////////////

	// read the input
	PDBFile pdb;
	pdb.open(parpars.get("i_pdb"));
	System sys;
	pdb.read(sys);

	ConformationSet cs;
	cs.setup(sys);
	cs.readDCDFile(parpars.get("i_dcd"));
	cs.resetScoring();

	PoseClustering pc;
	pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::RIGID_RMSD);
	pc.setConformationSet(&cs);

	// now convert
	pc.convertSnaphots2Transformations();
	std::vector< PoseClustering::PosePointer > poses = pc.getPoses();

	String outfile_name = String(parpars.get("o"));
	LineBasedFile file(outfile_name, ios::out);
	if (file.bad())
	{
		Log.error() << "cannot write file " << outfile_name << endl;
		return 2;
	}

	Log << "write rigid poses into file " << outfile_name << endl;

	for (Size i=0; i<poses.size(); i++)
	{
		Eigen::Matrix3f const & rot    = poses[i].trafo->rotation;
		Eigen::Vector3f const & transl = poses[i].trafo->translation;
		file << "A A " << " 0.0 "
			   << rot(0) << " " << rot(1) << " " << rot(2) << " " << transl[0] << " "
				 << rot(3) << " " << rot(4) << " " << rot(5) << " " << transl[1] << " "
				 << rot(6) << " " << rot(7) << " " << rot(8) << " " << transl[2]
				 << endl;
	}

	file.close();

	Log << "done." << endl;

	return 0;
}
<|endoftext|>


<commit_before>/* Copyright 2013-present Barefoot Networks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include <bm/bm_apps/learn.h>
#include <bm/Standard.h>
#include <bm/SimplePre.h>

#include <iostream>
#include <string>
#include <vector>

#include <cassert>

namespace {

bm_apps::LearnListener *listener;

struct sample_t {
  char src_addr[6];
  uint16_t ingress_port;
} __attribute__((packed));

}  // namespace

namespace runtime = bm_runtime::standard;

namespace {

void learn_cb(const bm_apps::LearnListener::MsgInfo &msg_info,
              const char *data, void *cookie) {
  (void) cookie;
  std::cout << "CB with " << msg_info.num_samples << " samples\n";

  boost::shared_ptr<runtime::StandardClient> client = listener->get_client();
  assert(client);

  for (unsigned int i = 0; i < msg_info.num_samples; i++) {
    const sample_t *sample = ((const sample_t *) data) + i;

    std::cout << "ingress port is " << ntohs(sample->ingress_port)
              << std::endl;

    runtime::BmMatchParam match_param;
    match_param.type = runtime::BmMatchParamType::type::EXACT;
    runtime::BmMatchParamExact match_param_exact;
    match_param_exact.key =
      std::string(sample->src_addr, sizeof(sample->src_addr));
    match_param.__set_exact(match_param_exact);

    runtime::BmAddEntryOptions options;

    client->bm_mt_add_entry(0, "smac", {match_param},
                            "_nop", std::vector<std::string>(),
                            options);

    std::vector<std::string> action_data =
      {std::string(reinterpret_cast<const char *>(&sample->ingress_port), 2)};

    client->bm_mt_add_entry(0, "dmac", {match_param},
                            "forward", std::move(action_data),
                            options);
  }

  client->bm_learning_ack_buffer(0, msg_info.list_id, msg_info.buffer_id);
}

}  // namespace

int main() {
  listener = new bm_apps::LearnListener("ipc:///tmp/bmv2-0-notifications.ipc");
  listener->register_cb(learn_cb, nullptr);
  listener->start();

  while (true) std::this_thread::sleep_for(std::chrono::seconds(100));

  return 0;
}
<commit_msg>Improve learn_client to catch table exceptions (#288)<commit_after>/* Copyright 2013-present Barefoot Networks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include <bm/bm_apps/learn.h>
#include <bm/Standard.h>
#include <bm/SimplePre.h>

#include <iostream>
#include <string>
#include <vector>

#include <cassert>

namespace {

bm_apps::LearnListener *listener;

struct sample_t {
  char src_addr[6];
  uint16_t ingress_port;
} __attribute__((packed));

}  // namespace

namespace runtime = bm_runtime::standard;

namespace {

void learn_cb(const bm_apps::LearnListener::MsgInfo &msg_info,
              const char *data, void *cookie) {
  (void) cookie;
  std::cout << "CB with " << msg_info.num_samples << " samples\n";

  boost::shared_ptr<runtime::StandardClient> client = listener->get_client();
  assert(client);

  for (unsigned int i = 0; i < msg_info.num_samples; i++) {
    const sample_t *sample = ((const sample_t *) data) + i;

    std::cout << "ingress port is " << ntohs(sample->ingress_port)
              << std::endl;

    auto add_entry = [client](
        const std::string &t_name, const runtime::BmMatchParams &match_params,
        const std::string &a_name, const runtime::BmActionData &action_data) {
      runtime::BmAddEntryOptions options;
      try {
        client->bm_mt_add_entry(0, t_name, match_params, a_name, action_data,
                                options);
      } catch (runtime::InvalidTableOperation &ito) {
        auto what = runtime::_TableOperationErrorCode_VALUES_TO_NAMES.find(
            ito.code)->second;
        std::cout << "Invalid table (" << t_name << ") operation ("
                  << ito.code << "): " << what << std::endl;
      }
    };

    runtime::BmMatchParam match_param;
    match_param.type = runtime::BmMatchParamType::type::EXACT;
    runtime::BmMatchParamExact match_param_exact;
    match_param_exact.key =
      std::string(sample->src_addr, sizeof(sample->src_addr));
    match_param.__set_exact(match_param_exact);
    runtime::BmMatchParams match_params({match_param});

    add_entry("smac", match_params, "_nop", std::vector<std::string>());

    std::vector<std::string> action_data =
      {std::string(reinterpret_cast<const char *>(&sample->ingress_port), 2)};
    add_entry("dmac", match_params, "forward", action_data);
  }

  client->bm_learning_ack_buffer(0, msg_info.list_id, msg_info.buffer_id);
}

}  // namespace

int main() {
  listener = new bm_apps::LearnListener("ipc:///tmp/bmv2-0-notifications.ipc");
  listener->register_cb(learn_cb, nullptr);
  listener->start();

  while (true) std::this_thread::sleep_for(std::chrono::seconds(100));

  return 0;
}
<|endoftext|>


<commit_before>// Copyright 2016 AUV-IITK
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "ros/ros.h"
#include "std_msgs/Float64.h"
#include <fstream>
#include <vector>
#include <cv.h>
#include <highgui.h>
#include "std_msgs/String.h"
#include "std_msgs/Int8.h"
#include <std_msgs/Bool.h>
#include <opencv2/core/core.hpp>
#include <opencv2/opencv.hpp>
#include <opencv/highgui.h>
#include <image_transport/image_transport.h>
#include "std_msgs/Float64MultiArray.h"
#include <cv_bridge/cv_bridge.h>
#include <sstream>
#include <string>
#include "std_msgs/Header.h"
using cv::Mat;
using cv::split;
using cv::Size;
using cv::Scalar;
using cv::normalize;
using cv::Point;
using cv::VideoCapture;
using cv::NORM_MINMAX;
using cv::MORPH_ELLIPSE;
using cv::COLOR_BGR2HSV;
using cv::destroyAllWindows;
using cv::getStructuringElement;
using cv::Vec4i;
using cv::namedWindow;
using std::vector;
using std::endl;
using std::cout;

int w = -2, x = -2, y = -2, z = -2;
bool IP = true;
bool flag = false;
bool video = false;
int t1min = 0, t1max = 88, t2min = 89, t2max = 251, t3min = 0, t3max = 255, lineCount = 0;  // Default Params

std_msgs::Float64 msg;
// parameters in param file should be nearly the same as the commented values
// params for an orange strip
int LowH = 0;   // 0
int HighH = 88;  // 88

int LowS = 0;   // 0
int HighS = 251;  // 251

int LowV = 0;   // 0
int HighV = 255;  // 255

// params for hough line transform
int lineThresh = 60;     // 60
int minLineLength = 70;  // 70
int maxLineGap = 10;     // 10
int houghThresh = 15;    // 15

double rho = 0.1;
double finalAngle = -1;
double minDeviation = 0.02;

cv::Mat frame;
cv::Mat newframe, sent_to_callback, imgLines;
int count = 0, count_avg = 0;

double computeMean(vector<double> &newAngles)
{
  double sum = 0;
  for (size_t i = 0; i < newAngles.size(); i++)
  {
    sum = sum + newAngles[i];
  }
  return sum / newAngles.size();
}
// called when few lines are detected
// to remove errors due to any stray results
double computeMode(vector<double> &newAngles)
{
  double mode = newAngles[0];
  int freq = 1;
  int tempFreq;
  double diff;
  for (int i = 0; i < newAngles.size(); i++)
  {
    tempFreq = 1;

    for (int j = i + 1; j < newAngles.size(); j++)
    {
      diff = newAngles[j] - newAngles[i] > 0.0 ? newAngles[j] - newAngles[i] : newAngles[i] - newAngles[j];
      if (diff <= minDeviation)
      {
        tempFreq++;
        newAngles.erase(newAngles.begin() + j);
        j = j - 1;
      }
    }

    if (tempFreq >= freq)
    {
      mode = newAngles[i];
      freq = tempFreq;
    }
  }

  return mode;
}

void callback(int, void *)
{
  vector<Vec4i> lines;
  HoughLinesP(sent_to_callback, lines, 1, CV_PI / 180, lineThresh, minLineLength, maxLineGap);

  frame.copyTo(imgLines);
  imgLines = Scalar(0, 0, 0);
  vector<double> angles(lines.size());

  lineCount = lines.size();
  int j = 0;
  for (size_t i = 0; i < lines.size(); i++)
  {
    Vec4i l = lines[i];
    line(imgLines, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 255, 0), 1, CV_AA);
    if ((l[2] == l[0]) || (l[1] == l[3])) continue;
    angles[j] = atan(static_cast<double>(l[2] - l[0]) / (l[1] - l[3]));
    j++;
  }

  imshow("LINES", imgLines + frame);

  // if num of lines are large than one or two stray lines won't affect the mean
  // much
  // but if they are small in number than mode has to be taken to save the error
  // due to those stray line

  if (lines.size() > 0 && lines.size() < 10)
    finalAngle = computeMode(angles);
  else if (lines.size() > 0)
    finalAngle = computeMean(angles);
}

void gateListener(std_msgs::Bool msg)
{
  IP = msg.data;
}

void imageCallback(const sensor_msgs::ImageConstPtr &msg)
{
  try
  {
    count++;
    newframe = cv_bridge::toCvShare(msg, "bgr8")->image;
    cvNamedWindow("newframe", CV_WINDOW_NORMAL);
    ///////////////////////////// DO NOT REMOVE THIS, IT COULD BE INGERIOUS TO HEALTH /////////////////////
    newframe.copyTo(frame);
    cv::imshow("newframe", newframe);
    ////////////////////////// FATAL ///////////////////////////////////////////////////
  }
  catch (cv_bridge::Exception &e)
  {
    ROS_ERROR("Could not convert from '%s' to 'bgr8'.", msg->encoding.c_str());
  }
}

int main(int argc, char* argv[])
{
  int height, width, step, channels;  // parameters of the image we are working on
  std::string Video_Name = "Random_Video";
  if (argc >= 2)
    flag = true;
  if (argc == 3)
  {
    video = true;
    std::string avi = ".avi";
    Video_Name = (argv[2]) + avi;
  }

  cv::VideoWriter output_cap(Video_Name, CV_FOURCC('D', 'I', 'V', 'X'), 9, cv::Size(640, 480));

  ros::init(argc, argv, "gate_detection");
  ros::NodeHandle n;

  ros::Publisher pub = n.advertise<std_msgs::Float64>("/varun/ip/line_angle", 1000);
  ros::Subscriber sub = n.subscribe<std_msgs::Bool>("line_angle_switch", 1000, &gateListener);
  ros::Rate loop_rate(10);

  image_transport::ImageTransport it(n);
  image_transport::Subscriber sub1 = it.subscribe("/varun/sensors/bottom_camera/image_raw", 1, imageCallback);

  cvNamedWindow("After Color Filtering", CV_WINDOW_NORMAL);
  cvNamedWindow("Contours", CV_WINDOW_NORMAL);
  cvNamedWindow("LINES", CV_WINDOW_NORMAL);

  if (flag)
  {
    cvNamedWindow("F1", CV_WINDOW_NORMAL);
    cvNamedWindow("F2", CV_WINDOW_NORMAL);
    cvNamedWindow("F3", CV_WINDOW_NORMAL);

    cvCreateTrackbar("t1min", "F1", &t1min, 260, NULL);
    cvCreateTrackbar("t1max", "F1", &t1max, 260, NULL);
    cvCreateTrackbar("t2min", "F2", &t2min, 260, NULL);
    cvCreateTrackbar("t2max", "F2", &t2max, 260, NULL);
    cvCreateTrackbar("t3min", "F3", &t3min, 260, NULL);
    cvCreateTrackbar("t3max", "F3", &t3max, 260, NULL);
  }
  // capture size -
  CvSize size = cvSize(width, height);

  // Initialize different images that are going to be used in the program
  cv::Mat hsv_frame, thresholded, thresholded1, thresholded2, thresholded3, filtered;  // image converted to HSV plane
  // asking for the minimum distance where bwe fire torpedo

  while (ros::ok())
  {
    loop_rate.sleep();
    // Get one frame
    if (frame.empty())
    {
      std::cout << "empty frame \n";
      ros::spinOnce();
      continue;
    }

    if (video)
      output_cap.write(frame);

    // get the image data
    height = frame.rows;
    width = frame.cols;
    step = frame.step;

    // Covert color space to HSV as it is much easier to filter colors in the HSV color-space.
    cv::cvtColor(frame, hsv_frame, CV_BGR2HSV);

    cv::Scalar hsv_min = cv::Scalar(t1min, t2min, t3min, 0);
    cv::Scalar hsv_max = cv::Scalar(t1max, t2max, t3max, 0);

    // Filter out colors which are out of range.
    cv::inRange(hsv_frame, hsv_min, hsv_max, thresholded);
    // Split image into its 3 one dimensional images
    cv::Mat thresholded_hsv[3];
    cv::split(hsv_frame, thresholded_hsv);

    // Filter out colors which are out of range.
    cv::inRange(thresholded_hsv[0], cv::Scalar(t1min, 0, 0, 0), cv::Scalar(t1max, 0, 0, 0), thresholded_hsv[0]);
    cv::inRange(thresholded_hsv[1], cv::Scalar(t2min, 0, 0, 0), cv::Scalar(t2max, 0, 0, 0), thresholded_hsv[1]);
    cv::inRange(thresholded_hsv[2], cv::Scalar(t3min, 0, 0, 0), cv::Scalar(t3max, 0, 0, 0), thresholded_hsv[2]);

    cv::GaussianBlur(thresholded, thresholded, cv::Size(9, 9), 0, 0, 0);
    cv::imshow("After Color Filtering", thresholded);  // The stream after color filtering

    if (flag)
    {
      cv::imshow("F1", thresholded_hsv[0]);              // individual filters
      cv::imshow("F2", thresholded_hsv[1]);
      cv::imshow("F3", thresholded_hsv[2]);
    }

    if ((cvWaitKey(10) & 255) == 27)
      break;

    if (!IP)
    {
      // find contours
      std::vector<std::vector<cv::Point> > contours;
      cv::Mat thresholded_Mat = thresholded;
      findContours(thresholded_Mat, contours, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);  // Find the contours in the image
      double largest_area = 0, largest_contour_index = 0;
      if (contours.empty())
      {
        msg.data = -finalAngle * (180 / 3.14)+90;
        pub.publish(msg);
        ros::spinOnce();
        // If ESC key pressed, Key=0x10001B under OpenCV 0.9.7(linux version),
        // remove higher bits using AND operator
        if ((cvWaitKey(10) & 255) == 27)
          break;
        continue;
      }

      for (int i = 0; i < contours.size(); i++)  // iterate through each contour.
      {
        double a = contourArea(contours[i], false);  //  Find the area of contour
        if (a > largest_area)
        {
          largest_area = a;
          largest_contour_index = i;  // Store the index of largest contour
        }
      }
      // Convex HULL
      std::vector<std::vector<cv::Point> > hull(contours.size());
      convexHull(cv::Mat(contours[largest_contour_index]), hull[largest_contour_index], false);

      cv::Mat Drawing(thresholded_Mat.rows, thresholded_Mat.cols, CV_8UC1, cv::Scalar::all(0));
      std::vector<cv::Vec4i> hierarchy;
      cv::Scalar color(255, 255, 255);
      drawContours(Drawing, contours, largest_contour_index, color, 2, 8, hierarchy);
      cv::imshow("Contours", Drawing);

      std_msgs::Float64 msg;
      Drawing.copyTo(sent_to_callback);
      /*
      msg.data never takes positive 90
      when the angle is 90 it will show -90
      -------------TO BE CORRECTED-------------
      */
      msg.data = -finalAngle * (180 / 3.14)+90;
      if (lineCount > 0)
      {
        pub.publish(msg);
      }
      callback(0, 0);        // for displaying the thresholded image initially
      ros::spinOnce();
      // loop_rate.sleep();

      // If ESC key pressed, Key=0x10001B under OpenCV 0.9.7(linux version),
      // remove higher bits using AND operator
      if ((cvWaitKey(10) & 255) == 27)
        break;
    }
    else
    {
       std::cout << "waiting\n";
       ros::spinOnce();
    }
  }
  output_cap.release();
  return 0;
}
<commit_msg>fixed a few errors<commit_after>// Copyright 2016 AUV-IITK
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "ros/ros.h"
#include "std_msgs/Float64.h"
#include <fstream>
#include <vector>
#include <cv.h>
#include <highgui.h>
#include "std_msgs/String.h"
#include "std_msgs/Int8.h"
#include <std_msgs/Bool.h>
#include <opencv2/core/core.hpp>
#include <opencv2/opencv.hpp>
#include <opencv/highgui.h>
#include <image_transport/image_transport.h>
#include "std_msgs/Float64MultiArray.h"
#include <cv_bridge/cv_bridge.h>
#include <sstream>
#include <string>
#include "std_msgs/Header.h"
using cv::Mat;
using cv::split;
using cv::Size;
using cv::Scalar;
using cv::normalize;
using cv::Point;
using cv::VideoCapture;
using cv::NORM_MINMAX;
using cv::MORPH_ELLIPSE;
using cv::COLOR_BGR2HSV;
using cv::destroyAllWindows;
using cv::getStructuringElement;
using cv::Vec4i;
using cv::namedWindow;
using std::vector;
using std::endl;
using std::cout;

int w = -2, x = -2, y = -2, z = -2;
bool IP = true;
bool flag = false;
bool video = false;
int t1min = 0, t1max = 88, t2min = 89, t2max = 251, t3min = 0, t3max = 255, lineCount = 0;  // Default Params

std_msgs::Float64 msg;
// parameters in param file should be nearly the same as the commented values
// params for an orange strip
int LowH = 0;   // 0
int HighH = 88;  // 88

int LowS = 0;   // 0
int HighS = 251;  // 251

int LowV = 0;   // 0
int HighV = 255;  // 255

// params for hough line transform
int lineThresh = 60;     // 60
int minLineLength = 70;  // 70
int maxLineGap = 10;     // 10
int houghThresh = 15;    // 15

double rho = 0.1;
double finalAngle = -1;
double minDeviation = 0.02;

cv::Mat frame;
cv::Mat newframe, sent_to_callback, imgLines;
int count = 0, count_avg = 0;

double computeMean(vector<double> &newAngles)
{
  double sum = 0;
  for (size_t i = 0; i < newAngles.size(); i++)
  {
    sum = sum + newAngles[i];
  }
  return sum / newAngles.size();
}
// called when few lines are detected
// to remove errors due to any stray results
double computeMode(vector<double> &newAngles)
{
  double mode = newAngles[0];
  int freq = 1;
  int tempFreq;
  double diff;
  for (int i = 0; i < newAngles.size(); i++)
  {
    tempFreq = 1;

    for (int j = i + 1; j < newAngles.size(); j++)
    {
      diff = newAngles[j] - newAngles[i] > 0.0 ? newAngles[j] - newAngles[i] : newAngles[i] - newAngles[j];
      if (diff <= minDeviation)
      {
        tempFreq++;
        newAngles.erase(newAngles.begin() + j);
        j = j - 1;
      }
    }

    if (tempFreq >= freq)
    {
      mode = newAngles[i];
      freq = tempFreq;
    }
  }

  return mode;
}

void callback(int, void *)
{
  vector<Vec4i> lines;
  HoughLinesP(sent_to_callback, lines, 1, CV_PI / 180, lineThresh, minLineLength, maxLineGap);

  frame.copyTo(imgLines);
  imgLines = Scalar(0, 0, 0);
  vector<double> angles(lines.size());

  lineCount = lines.size();
  int j = 0;
  for (size_t i = 0; i < lines.size(); i++)
  {
    Vec4i l = lines[i];
    line(imgLines, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 255, 0), 1, CV_AA);
    if ((l[2] == l[0]) || (l[1] == l[3])) continue;
    angles[j] = atan(static_cast<double>(l[2] - l[0]) / (l[1] - l[3]));
    j++;
  }

  imshow("LINES", imgLines + frame);

  // if num of lines are large than one or two stray lines won't affect the mean
  // much
  // but if they are small in number than mode has to be taken to save the error
  // due to those stray line

  if (lines.size() > 0 && lines.size() < 10)
    finalAngle = computeMode(angles);
  else if (lines.size() > 0)
    finalAngle = computeMean(angles);
}

void lineAngleListener(std_msgs::Bool msg)
{
  IP = msg.data;
}

void imageCallback(const sensor_msgs::ImageConstPtr &msg)
{
  try
  {
    count++;
    newframe = cv_bridge::toCvShare(msg, "bgr8")->image;
    cvNamedWindow("newframe", CV_WINDOW_NORMAL);
    ///////////////////////////// DO NOT REMOVE THIS, IT COULD BE INGERIOUS TO HEALTH /////////////////////
    newframe.copyTo(frame);
    cv::imshow("newframe", newframe);
    ////////////////////////// FATAL ///////////////////////////////////////////////////
  }
  catch (cv_bridge::Exception &e)
  {
    ROS_ERROR("Could not convert from '%s' to 'bgr8'.", msg->encoding.c_str());
  }
}

int main(int argc, char* argv[])
{
  int height, width, step, channels;  // parameters of the image we are working on
  std::string Video_Name = "Random_Video";
  if (argc >= 2)
    flag = true;
  if (argc == 3)
  {
    video = true;
    std::string avi = ".avi";
    Video_Name = (argv[2]) + avi;
  }

  cv::VideoWriter output_cap(Video_Name, CV_FOURCC('D', 'I', 'V', 'X'), 9, cv::Size(640, 480));

  ros::init(argc, argv, "gate_detection");
  ros::NodeHandle n;

  ros::Publisher pub = n.advertise<std_msgs::Float64>("/varun/ip/line_angle", 1000);
  ros::Subscriber sub = n.subscribe<std_msgs::Bool>("line_angle_switch", 1000, &lineAngleListener);
  ros::Rate loop_rate(10);

  image_transport::ImageTransport it(n);
  image_transport::Subscriber sub1 = it.subscribe("/varun/sensors/bottom_camera/image_raw", 1, imageCallback);

  cvNamedWindow("After Color Filtering", CV_WINDOW_NORMAL);
  cvNamedWindow("Contours", CV_WINDOW_NORMAL);
  cvNamedWindow("LINES", CV_WINDOW_NORMAL);

  if (flag)
  {
    cvNamedWindow("F1", CV_WINDOW_NORMAL);
    cvNamedWindow("F2", CV_WINDOW_NORMAL);
    cvNamedWindow("F3", CV_WINDOW_NORMAL);

    cvCreateTrackbar("t1min", "F1", &t1min, 260, NULL);
    cvCreateTrackbar("t1max", "F1", &t1max, 260, NULL);
    cvCreateTrackbar("t2min", "F2", &t2min, 260, NULL);
    cvCreateTrackbar("t2max", "F2", &t2max, 260, NULL);
    cvCreateTrackbar("t3min", "F3", &t3min, 260, NULL);
    cvCreateTrackbar("t3max", "F3", &t3max, 260, NULL);
  }
  // capture size -
  CvSize size = cvSize(width, height);

  // Initialize different images that are going to be used in the program
  cv::Mat hsv_frame, thresholded, thresholded1, thresholded2, thresholded3, filtered;  // image converted to HSV plane
  // asking for the minimum distance where bwe fire torpedo

  while (ros::ok())
  {
    loop_rate.sleep();
    // Get one frame
    if (frame.empty())
    {
      std::cout << "empty frame \n";
      ros::spinOnce();
      continue;
    }

    if (video)
      output_cap.write(frame);

    // get the image data
    height = frame.rows;
    width = frame.cols;
    step = frame.step;

    // Covert color space to HSV as it is much easier to filter colors in the HSV color-space.
    cv::cvtColor(frame, hsv_frame, CV_BGR2HSV);

    cv::Scalar hsv_min = cv::Scalar(t1min, t2min, t3min, 0);
    cv::Scalar hsv_max = cv::Scalar(t1max, t2max, t3max, 0);

    // Filter out colors which are out of range.
    cv::inRange(hsv_frame, hsv_min, hsv_max, thresholded);
    // Split image into its 3 one dimensional images
    cv::Mat thresholded_hsv[3];
    cv::split(hsv_frame, thresholded_hsv);

    // Filter out colors which are out of range.
    cv::inRange(thresholded_hsv[0], cv::Scalar(t1min, 0, 0, 0), cv::Scalar(t1max, 0, 0, 0), thresholded_hsv[0]);
    cv::inRange(thresholded_hsv[1], cv::Scalar(t2min, 0, 0, 0), cv::Scalar(t2max, 0, 0, 0), thresholded_hsv[1]);
    cv::inRange(thresholded_hsv[2], cv::Scalar(t3min, 0, 0, 0), cv::Scalar(t3max, 0, 0, 0), thresholded_hsv[2]);

    cv::GaussianBlur(thresholded, thresholded, cv::Size(9, 9), 0, 0, 0);
    cv::imshow("After Color Filtering", thresholded);  // The stream after color filtering

    if (flag)
    {
      cv::imshow("F1", thresholded_hsv[0]);              // individual filters
      cv::imshow("F2", thresholded_hsv[1]);
      cv::imshow("F3", thresholded_hsv[2]);
    }

    if ((cvWaitKey(10) & 255) == 27)
      break;

    if (!IP)
    {
      // find contours
      std::vector<std::vector<cv::Point> > contours;
      cv::Mat thresholded_Mat = thresholded;
      findContours(thresholded_Mat, contours, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);  // Find the contours in the image
      double largest_area = 0, largest_contour_index = 0;
      if (contours.empty())
      {
        msg.data = -finalAngle * (180 / 3.14)+90;
        pub.publish(msg);
        ros::spinOnce();
        // If ESC key pressed, Key=0x10001B under OpenCV 0.9.7(linux version),
        // remove higher bits using AND operator
        if ((cvWaitKey(10) & 255) == 27)
          break;
        continue;
      }

      for (int i = 0; i < contours.size(); i++)  // iterate through each contour.
      {
        double a = contourArea(contours[i], false);  //  Find the area of contour
        if (a > largest_area)
        {
          largest_area = a;
          largest_contour_index = i;  // Store the index of largest contour
        }
      }
      // Convex HULL
      std::vector<std::vector<cv::Point> > hull(contours.size());
      convexHull(cv::Mat(contours[largest_contour_index]), hull[largest_contour_index], false);

      cv::Mat Drawing(thresholded_Mat.rows, thresholded_Mat.cols, CV_8UC1, cv::Scalar::all(0));
      std::vector<cv::Vec4i> hierarchy;
      cv::Scalar color(255, 255, 255);
      drawContours(Drawing, contours, largest_contour_index, color, 2, 8, hierarchy);
      cv::imshow("Contours", Drawing);

      std_msgs::Float64 msg;
      Drawing.copyTo(sent_to_callback);
      /*
      msg.data never takes positive 90
      when the angle is 90 it will show -90
      -------------TO BE CORRECTED-------------
      */
      msg.data = -finalAngle * (180 / 3.14);
      if (lineCount > 0)
      {
        pub.publish(msg);
      }
      callback(0, 0);        // for displaying the thresholded image initially
      ros::spinOnce();
      // loop_rate.sleep();

      // If ESC key pressed, Key=0x10001B under OpenCV 0.9.7(linux version),
      // remove higher bits using AND operator
      if ((cvWaitKey(10) & 255) == 27)
        break;
    }
    else
    {
       std::cout << "waiting\n";
       ros::spinOnce();
    }
  }
  output_cap.release();
  return 0;
}
<|endoftext|>


<commit_before>///
/// @file   cmdoptions.cpp
/// @brief  Parse command-line options for the primesieve console
///         (terminal) application.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesieve.hpp>
#include "cmdoptions.hpp"
#include "calculator.hpp"

#include <string>
#include <map>
#include <cstddef>
#include <stdint.h>

void help();
void version();

using namespace std;
using namespace primesieve;

namespace {

/// Command-line option
/// e.g. id = "--threads", value = "4"
struct Option
{
  string id;
  string value;
  template <typename T>
  T getValue() const
  {
    return calculator::eval<T>(value);
  }
};

enum OptionValues
{
  OPTION_COUNT,
  OPTION_HELP,
  OPTION_NTHPRIME,
  OPTION_NO_STATUS,
  OPTION_NUMBER,
  OPTION_DISTANCE,
  OPTION_PRINT,
  OPTION_QUIET,
  OPTION_SIZE,
  OPTION_THREADS,
  OPTION_TIME,
  OPTION_VERSION
};

/// Command-line options
map<string, OptionValues> optionMap =
{
  { "-c",          OPTION_COUNT },
  { "--count",     OPTION_COUNT },
  { "-h",          OPTION_HELP },
  { "--help",      OPTION_HELP },
  { "-n",          OPTION_NTHPRIME },
  { "--nthprime",  OPTION_NTHPRIME },
  { "--no-status", OPTION_NO_STATUS },
  { "--number",    OPTION_NUMBER },
  { "-d",          OPTION_DISTANCE },
  { "--dist",      OPTION_DISTANCE },
  { "-p",          OPTION_PRINT },
  { "--print",     OPTION_PRINT },
  { "-q",          OPTION_QUIET },
  { "--quiet",     OPTION_QUIET },
  { "-s",          OPTION_SIZE },
  { "--size",      OPTION_SIZE },
  { "-t",          OPTION_THREADS },
  { "--threads",   OPTION_THREADS },
  { "--time",      OPTION_TIME },
  { "-v",          OPTION_VERSION },
  { "--version",   OPTION_VERSION }
};

int check(int primeType)
{
  primeType--;

  if (primeType < 0 ||
      primeType > 5)
    help();

  return primeType;
}

int getCountFlags(int n)
{
  int flags = 0;

  do {
    int primeType = check(n % 10);
    flags |= PrimeSieve::COUNT_PRIMES << primeType;
    n /= 10;
  } while (n > 0);

  return flags;
}

int getPrintFlags(int n)
{
  n = check(n);
  return PrimeSieve::PRINT_PRIMES << n;
}

/// e.g. "--threads=8" -> (id = "--threads", value = "8")
Option makeOption(const string& str)
{
  Option option;
  size_t delimiter = str.find_first_of("=0123456789");

  if (delimiter == string::npos)
    option.id = str;
  else
  {
    option.id = str.substr(0, delimiter);
    option.value = str.substr(delimiter + (str.at(delimiter) == '=' ? 1 : 0));
  }

  if (option.id.empty() && !option.value.empty())
    option.id = "--number";
  if (optionMap.count(option.id) == 0)
    option.id = "--help";

  return option;
}

} // namespace

CmdOptions parseOptions(int argc, char** argv)
{
  CmdOptions opts;

  for (int i = 1; i < argc; i++)
  {
    Option option = makeOption(argv[i]);

    switch (optionMap[option.id])
    {
      case OPTION_COUNT:     if (option.value.empty())
                               option.value = "1";
                             opts.flags |= getCountFlags(option.getValue<int>());
                             break;
      case OPTION_PRINT:     if (option.value.empty())
                               option.value = "1";
                             opts.flags |= getPrintFlags(option.getValue<int>());
                             opts.quiet = true;
                             break;
      case OPTION_SIZE:      opts.sieveSize = option.getValue<int>(); break;
      case OPTION_THREADS:   opts.threads = option.getValue<int>(); break;
      case OPTION_QUIET:     opts.quiet = true; break;
      case OPTION_NTHPRIME:  opts.nthPrime = true; break;
      case OPTION_NO_STATUS: opts.status = false; break;
      case OPTION_TIME:      opts.time = true; break;
      case OPTION_NUMBER:    opts.numbers.push_back(option.getValue<uint64_t>()); break;
      case OPTION_DISTANCE:  opts.numbers.push_back(option.getValue<uint64_t>() + opts.numbers.front()); break;
      case OPTION_VERSION:   version(); break;
      case OPTION_HELP:      help(); break;
    }
  }

  if (opts.numbers.size() < 1 ||
      opts.numbers.size() > 2)
    help();

  if (opts.quiet)
    opts.status = false;
  else
    opts.time = true;

  return opts;
}
<commit_msg>Add optionCount() & optionPrint()<commit_after>///
/// @file   cmdoptions.cpp
/// @brief  Parse command-line options for the primesieve console
///         (terminal) application.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesieve.hpp>
#include "cmdoptions.hpp"
#include "calculator.hpp"

#include <string>
#include <map>
#include <cstddef>
#include <stdint.h>

void help();
void version();

using namespace std;
using namespace primesieve;

namespace {

/// Command-line option
/// e.g. str = "--threads", value = "4"
struct Option
{
  string str;
  string value;
  template <typename T>
  T getValue() const
  {
    return calculator::eval<T>(value);
  }
};

enum OptionID
{
  OPTION_COUNT,
  OPTION_HELP,
  OPTION_NTHPRIME,
  OPTION_NO_STATUS,
  OPTION_NUMBER,
  OPTION_DISTANCE,
  OPTION_PRINT,
  OPTION_QUIET,
  OPTION_SIZE,
  OPTION_THREADS,
  OPTION_TIME,
  OPTION_VERSION
};

/// Command-line options
map<string, OptionID> optionMap =
{
  { "-c",          OPTION_COUNT },
  { "--count",     OPTION_COUNT },
  { "-h",          OPTION_HELP },
  { "--help",      OPTION_HELP },
  { "-n",          OPTION_NTHPRIME },
  { "--nthprime",  OPTION_NTHPRIME },
  { "--no-status", OPTION_NO_STATUS },
  { "--number",    OPTION_NUMBER },
  { "-d",          OPTION_DISTANCE },
  { "--dist",      OPTION_DISTANCE },
  { "-p",          OPTION_PRINT },
  { "--print",     OPTION_PRINT },
  { "-q",          OPTION_QUIET },
  { "--quiet",     OPTION_QUIET },
  { "-s",          OPTION_SIZE },
  { "--size",      OPTION_SIZE },
  { "-t",          OPTION_THREADS },
  { "--threads",   OPTION_THREADS },
  { "--time",      OPTION_TIME },
  { "-v",          OPTION_VERSION },
  { "--version",   OPTION_VERSION }
};

int check(int primeType)
{
  primeType--;

  if (primeType < 0 ||
      primeType > 5)
    help();

  return primeType;
}

void optionPrint(Option& opt,
                 CmdOptions& opts)
{
  opts.quiet = true;

  if (opt.value.empty())
   opt.value = "1";

  int i = opt.getValue<int>();
  i = check(i);
  opts.flags |= PrimeSieve::PRINT_PRIMES << i;
}

void optionCount(Option& opt,
                 CmdOptions& opts)
{
  if (opt.value.empty())
    opt.value = "1";

  int n = opt.getValue<int>();

  for (; n > 0; n /= 10)
  {
    int i = check(n % 10);
    opts.flags |= PrimeSieve::COUNT_PRIMES << i;
  }
}

/// e.g. "--threads=8"
/// -> option.str = "--threads"
/// -> option.value = "8"
///
Option makeOption(const string& str)
{
  Option option;
  size_t delimiter = str.find_first_of("=0123456789");

  if (delimiter == string::npos)
    option.str = str;
  else
  {
    option.str = str.substr(0, delimiter);
    option.value = str.substr(delimiter + (str.at(delimiter) == '=' ? 1 : 0));
  }

  if (option.str.empty() && !option.value.empty())
    option.str = "--number";
  if (optionMap.count(option.str) == 0)
    option.str = "--help";

  return option;
}

} // namespace

CmdOptions parseOptions(int argc, char* argv[])
{
  CmdOptions opts;

  for (int i = 1; i < argc; i++)
  {
    Option opt = makeOption(argv[i]);

    switch (optionMap[opt.str])
    {
      case OPTION_COUNT:     optionCount(opt, opts); break;
      case OPTION_PRINT:     optionPrint(opt, opts); break;
      case OPTION_SIZE:      opts.sieveSize = opt.getValue<int>(); break;
      case OPTION_THREADS:   opts.threads = opt.getValue<int>(); break;
      case OPTION_QUIET:     opts.quiet = true; break;
      case OPTION_NTHPRIME:  opts.nthPrime = true; break;
      case OPTION_NO_STATUS: opts.status = false; break;
      case OPTION_TIME:      opts.time = true; break;
      case OPTION_NUMBER:    opts.numbers.push_back(opt.getValue<uint64_t>()); break;
      case OPTION_DISTANCE:  opts.numbers.push_back(opt.getValue<uint64_t>() + opts.numbers[0]); break;
      case OPTION_VERSION:   version(); break;
      case OPTION_HELP:      help(); break;
    }
  }

  if (opts.numbers.size() < 1 ||
      opts.numbers.size() > 2)
    help();

  if (opts.quiet)
    opts.status = false;
  else
    opts.time = true;

  return opts;
}
<|endoftext|>


<commit_before><commit_msg>Change OmniboxEditModel to always use virtual URL instead of actual URL<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium 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 "chrome/browser/views/frame/browser_frame_gtk.h"

#include "base/logging.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/status_bubble.h"
#include "chrome/browser/views/frame/browser_root_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/frame/opaque_browser_frame_view.h"
#include "views/widget/root_view.h"

// static (Factory method.)
BrowserFrame* BrowserFrame::Create(BrowserView* browser_view,
                                   Profile* profile) {
  BrowserFrameGtk* frame = new BrowserFrameGtk(browser_view, profile);
  frame->Init();
  return frame;
}

BrowserFrameGtk::BrowserFrameGtk(BrowserView* browser_view, Profile* profile)
    : WindowGtk(browser_view),
      browser_view_(browser_view),
      browser_frame_view_(NULL),
      root_view_(NULL),
      profile_(profile) {
  browser_view_->set_frame(this);
  browser_frame_view_ = new OpaqueBrowserFrameView(this, browser_view_);
  GetNonClientView()->SetFrameView(browser_frame_view_);
  // Don't focus anything on creation, selecting a tab will set the focus.
}

BrowserFrameGtk::~BrowserFrameGtk() {
}

void BrowserFrameGtk::Init() {
  WindowGtk::Init(NULL, gfx::Rect());
}

views::Window* BrowserFrameGtk::GetWindow() {
  return this;
}

void BrowserFrameGtk::TabStripCreated(TabStrip* tabstrip) {
}

int BrowserFrameGtk::GetMinimizeButtonOffset() const {
  NOTIMPLEMENTED();
  return 0;
}

gfx::Rect BrowserFrameGtk::GetBoundsForTabStrip(TabStrip* tabstrip) const {
  return browser_frame_view_->GetBoundsForTabStrip(tabstrip);
}

void BrowserFrameGtk::UpdateThrobber(bool running) {
  browser_frame_view_->UpdateThrobber(running);
}

void BrowserFrameGtk::ContinueDraggingDetachedTab() {
  NOTIMPLEMENTED();
}

ThemeProvider* BrowserFrameGtk::GetThemeProviderForFrame() const {
  // This is implemented for a different interface than GetThemeProvider is,
  // but they mean the same things.
  return GetThemeProvider();
}

bool BrowserFrameGtk::AlwaysUseNativeFrame() const {
  return false;
}

ThemeProvider* BrowserFrameGtk::GetThemeProvider() const {
  return profile_->GetThemeProvider();
}

ThemeProvider* BrowserFrameGtk::GetDefaultThemeProvider() const {
  return profile_->GetThemeProvider();
}

views::RootView* BrowserFrameGtk::CreateRootView() {
  root_view_ = new BrowserRootView(browser_view_, this);
  return root_view_;
}

void BrowserFrameGtk::IsActiveChanged() {
  GetRootView()->SchedulePaint();
  browser_view_->ActivationChanged(IsActive());
  views::WidgetGtk::IsActiveChanged();
}

bool BrowserFrameGtk::GetAccelerator(int cmd_id,
                                     views::Accelerator* accelerator) {
  return browser_view_->GetAccelerator(cmd_id, accelerator);
}

gboolean BrowserFrameGtk::OnWindowStateEvent(GtkWidget* widget,
                                             GdkEventWindowState* event) {
  gboolean result = views::WindowGtk::OnWindowStateEvent(widget, event);
  if ((!IsVisible() || IsMinimized()) && browser_view_->GetStatusBubble()) {
    // The window is effectively hidden. We have to hide the status bubble as
    // unlike windows gtk has no notion of child windows that are hidden along
    // with the parent.
    browser_view_->GetStatusBubble()->Hide();
  }
  return result;
}

gboolean BrowserFrameGtk::OnConfigureEvent(GtkWidget* widget,
                                           GdkEventConfigure* event) {
  browser_view_->WindowMoved();
  return views::WindowGtk::OnConfigureEvent(widget, event);
}
<commit_msg>Makes the nonclientframeview for popups on views/gtk draw nothing. This is needed as we want the window manager rendering the decorations.<commit_after>// Copyright (c) 2009 The Chromium 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 "chrome/browser/views/frame/browser_frame_gtk.h"

#include "base/logging.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/status_bubble.h"
#include "chrome/browser/views/frame/browser_root_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/frame/opaque_browser_frame_view.h"
#include "views/widget/root_view.h"
#include "views/window/hit_test.h"

namespace {

// BrowserNonClientFrameView implementation for popups. We let the window
// manager implementation render the decorations for popups, so this draws
// nothing.
class PopupNonClientFrameView : public BrowserNonClientFrameView {
 public:
  PopupNonClientFrameView() {
  }

  // NonClientFrameView:
  virtual gfx::Rect GetBoundsForClientView() const {
    return gfx::Rect(0, 0, width(), height());
  }
  virtual bool AlwaysUseCustomFrame() const { return false; }
  virtual bool AlwaysUseNativeFrame() const { return true; }
  virtual gfx::Rect GetWindowBoundsForClientBounds(
      const gfx::Rect& client_bounds) const {
    return client_bounds;
  }
  virtual gfx::Point GetSystemMenuPoint() const {
    // Never used on GTK.
    // TODO: make this method windows specific.
    return gfx::Point(0, 0);
  }
  virtual int NonClientHitTest(const gfx::Point& point) {
    return HTNOWHERE;
  }
  virtual void GetWindowMask(const gfx::Size& size,
                             gfx::Path* window_mask) {}
  virtual void EnableClose(bool enable) {}
  virtual void ResetWindowControls() {}

  // BrowserNonClientFrameView:
  virtual gfx::Rect GetBoundsForTabStrip(TabStrip* tabstrip) const {
    return gfx::Rect(0, 0, width(), tabstrip->GetPreferredHeight());
  }
  virtual void UpdateThrobber(bool running) {}

 private:
  DISALLOW_COPY_AND_ASSIGN(PopupNonClientFrameView);
};

}

// static (Factory method.)
BrowserFrame* BrowserFrame::Create(BrowserView* browser_view,
                                   Profile* profile) {
  BrowserFrameGtk* frame = new BrowserFrameGtk(browser_view, profile);
  frame->Init();
  return frame;
}

BrowserFrameGtk::BrowserFrameGtk(BrowserView* browser_view, Profile* profile)
    : WindowGtk(browser_view),
      browser_view_(browser_view),
      browser_frame_view_(NULL),
      root_view_(NULL),
      profile_(profile) {
  browser_view_->set_frame(this);
  if (browser_view->browser()->type() == Browser::TYPE_POPUP)
    browser_frame_view_ = new PopupNonClientFrameView();
  else
    browser_frame_view_ = new OpaqueBrowserFrameView(this, browser_view_);
  GetNonClientView()->SetFrameView(browser_frame_view_);
  // Don't focus anything on creation, selecting a tab will set the focus.
}

BrowserFrameGtk::~BrowserFrameGtk() {
}

void BrowserFrameGtk::Init() {
  WindowGtk::Init(NULL, gfx::Rect());
}

views::Window* BrowserFrameGtk::GetWindow() {
  return this;
}

void BrowserFrameGtk::TabStripCreated(TabStrip* tabstrip) {
}

int BrowserFrameGtk::GetMinimizeButtonOffset() const {
  NOTIMPLEMENTED();
  return 0;
}

gfx::Rect BrowserFrameGtk::GetBoundsForTabStrip(TabStrip* tabstrip) const {
  return browser_frame_view_->GetBoundsForTabStrip(tabstrip);
}

void BrowserFrameGtk::UpdateThrobber(bool running) {
  browser_frame_view_->UpdateThrobber(running);
}

void BrowserFrameGtk::ContinueDraggingDetachedTab() {
  NOTIMPLEMENTED();
}

ThemeProvider* BrowserFrameGtk::GetThemeProviderForFrame() const {
  // This is implemented for a different interface than GetThemeProvider is,
  // but they mean the same things.
  return GetThemeProvider();
}

bool BrowserFrameGtk::AlwaysUseNativeFrame() const {
  return false;
}

ThemeProvider* BrowserFrameGtk::GetThemeProvider() const {
  return profile_->GetThemeProvider();
}

ThemeProvider* BrowserFrameGtk::GetDefaultThemeProvider() const {
  return profile_->GetThemeProvider();
}

views::RootView* BrowserFrameGtk::CreateRootView() {
  root_view_ = new BrowserRootView(browser_view_, this);
  return root_view_;
}

void BrowserFrameGtk::IsActiveChanged() {
  GetRootView()->SchedulePaint();
  browser_view_->ActivationChanged(IsActive());
  views::WidgetGtk::IsActiveChanged();
}

bool BrowserFrameGtk::GetAccelerator(int cmd_id,
                                     views::Accelerator* accelerator) {
  return browser_view_->GetAccelerator(cmd_id, accelerator);
}

gboolean BrowserFrameGtk::OnWindowStateEvent(GtkWidget* widget,
                                             GdkEventWindowState* event) {
  gboolean result = views::WindowGtk::OnWindowStateEvent(widget, event);
  if ((!IsVisible() || IsMinimized()) && browser_view_->GetStatusBubble()) {
    // The window is effectively hidden. We have to hide the status bubble as
    // unlike windows gtk has no notion of child windows that are hidden along
    // with the parent.
    browser_view_->GetStatusBubble()->Hide();
  }
  return result;
}

gboolean BrowserFrameGtk::OnConfigureEvent(GtkWidget* widget,
                                           GdkEventConfigure* event) {
  browser_view_->WindowMoved();
  return views::WindowGtk::OnConfigureEvent(widget, event);
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium 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 "chrome/renderer/extensions/chrome_v8_context.h"

#include "base/logging.h"
#include "base/string_split.h"
#include "base/values.h"
#include "chrome/common/extensions/extension_set.h"
#include "chrome/renderer/extensions/chrome_v8_extension.h"
#include "content/public/renderer/render_view.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "v8/include/v8.h"

ChromeV8Context::ChromeV8Context(v8::Handle<v8::Context> v8_context,
                                 WebKit::WebFrame* web_frame,
                                 const std::string& extension_id)
    : v8_context_(v8::Persistent<v8::Context>::New(v8_context)),
      web_frame_(web_frame),
      extension_id_(extension_id) {
  VLOG(1) << "Created context for extension\n"
          << "  id:    " << extension_id << "\n"
          << "  frame: " << web_frame_;
}

ChromeV8Context::~ChromeV8Context() {
  VLOG(1) << "Destroyed context for extension\n"
          << "  id:    " << extension_id_;
  v8_context_.Dispose();
}

content::RenderView* ChromeV8Context::GetRenderView() const {
  if (web_frame_ && web_frame_->view())
    return content::RenderView::FromWebView(web_frame_->view());
  else
    return NULL;
}

bool ChromeV8Context::CallChromeHiddenMethod(
    const std::string& function_name,
    int argc,
    v8::Handle<v8::Value>* argv,
    v8::Handle<v8::Value>* result) const {
  v8::Context::Scope context_scope(v8_context_);

  // Look up the function name, which may be a sub-property like
  // "Port.dispatchOnMessage" in the hidden global variable.
  v8::Local<v8::Value> value = v8::Local<v8::Value>::New(
      ChromeV8Extension::GetChromeHidden(v8_context_));
  std::vector<std::string> components;
  base::SplitStringDontTrim(function_name, '.', &components);
  for (size_t i = 0; i < components.size(); ++i) {
    if (!value.IsEmpty()) {
      value = v8::Local<v8::Object>::Cast(value)->Get(
          v8::String::New(components[i].c_str()));
    }
  }

  // TODO(aa): CHECK that this succeeds. Can't do this now because not all
  // callers know if the method they are calling exists. Should be able to fix
  // this when all the bindings are converted to the new framework.
  if (value.IsEmpty() || !value->IsFunction()) {
    VLOG(1) << "Could not execute chrome hidden method: " << function_name;
    return false;
  }

  v8::Handle<v8::Value> result_temp =
      v8::Local<v8::Function>::Cast(value)->Call(v8::Object::New(), argc, argv);
  if (result)
    *result = result_temp;
  return true;
}

void ChromeV8Context::DispatchOnLoadEvent(bool is_extension_process,
                                          bool is_incognito_process) const {
  v8::HandleScope handle_scope;
  v8::Handle<v8::Value> argv[3];
  argv[0] = v8::String::New(extension_id_.c_str());
  argv[1] = v8::Boolean::New(is_extension_process);
  argv[2] = v8::Boolean::New(is_incognito_process);
  CallChromeHiddenMethod("dispatchOnLoad", arraysize(argv), argv, NULL);
}

void ChromeV8Context::DispatchOnUnloadEvent() const {
  v8::HandleScope handle_scope;
  CallChromeHiddenMethod("dispatchOnUnload", 0, NULL, NULL);
}
<commit_msg>Be more careful when calling methods on chromeHidden. If chromeHidden didn't have the method before, it would stop the current stack because of an unhandled try/catch.<commit_after>// Copyright (c) 2011 The Chromium 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 "chrome/renderer/extensions/chrome_v8_context.h"

#include "base/logging.h"
#include "base/string_split.h"
#include "base/values.h"
#include "chrome/common/extensions/extension_set.h"
#include "chrome/renderer/extensions/chrome_v8_extension.h"
#include "content/public/renderer/render_view.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "v8/include/v8.h"

ChromeV8Context::ChromeV8Context(v8::Handle<v8::Context> v8_context,
                                 WebKit::WebFrame* web_frame,
                                 const std::string& extension_id)
    : v8_context_(v8::Persistent<v8::Context>::New(v8_context)),
      web_frame_(web_frame),
      extension_id_(extension_id) {
  VLOG(1) << "Created context for extension\n"
          << "  id:    " << extension_id << "\n"
          << "  frame: " << web_frame_;
}

ChromeV8Context::~ChromeV8Context() {
  VLOG(1) << "Destroyed context for extension\n"
          << "  id:    " << extension_id_;
  v8_context_.Dispose();
}

content::RenderView* ChromeV8Context::GetRenderView() const {
  if (web_frame_ && web_frame_->view())
    return content::RenderView::FromWebView(web_frame_->view());
  else
    return NULL;
}

bool ChromeV8Context::CallChromeHiddenMethod(
    const std::string& function_name,
    int argc,
    v8::Handle<v8::Value>* argv,
    v8::Handle<v8::Value>* result) const {
  v8::Context::Scope context_scope(v8_context_);
  v8::TryCatch try_catch;

  // Look up the function name, which may be a sub-property like
  // "Port.dispatchOnMessage" in the hidden global variable.
  v8::Local<v8::Value> value = v8::Local<v8::Value>::New(
      ChromeV8Extension::GetChromeHidden(v8_context_));
  std::vector<std::string> components;
  base::SplitStringDontTrim(function_name, '.', &components);
  for (size_t i = 0; i < components.size(); ++i) {
    if (!value.IsEmpty() && value->IsObject()) {
      value = v8::Local<v8::Object>::Cast(value)->Get(
          v8::String::New(components[i].c_str()));
      if (try_catch.HasCaught()) {
        NOTREACHED() << *v8::String::AsciiValue(try_catch.Exception());
        return false;
      }
    }
  }

  if (value.IsEmpty() || !value->IsFunction()) {
    VLOG(1) << "Could not execute chrome hidden method: " << function_name;
    return false;
  }

  v8::Handle<v8::Value> result_temp =
      v8::Local<v8::Function>::Cast(value)->Call(v8::Object::New(), argc, argv);
  if (try_catch.HasCaught()) {
    NOTREACHED() << *v8::String::AsciiValue(try_catch.Exception());
    return false;
  }
  if (result)
    *result = result_temp;
  return true;
}

void ChromeV8Context::DispatchOnLoadEvent(bool is_extension_process,
                                          bool is_incognito_process) const {
  v8::HandleScope handle_scope;
  v8::Handle<v8::Value> argv[3];
  argv[0] = v8::String::New(extension_id_.c_str());
  argv[1] = v8::Boolean::New(is_extension_process);
  argv[2] = v8::Boolean::New(is_incognito_process);
  CallChromeHiddenMethod("dispatchOnLoad", arraysize(argv), argv, NULL);
}

void ChromeV8Context::DispatchOnUnloadEvent() const {
  v8::HandleScope handle_scope;
  CallChromeHiddenMethod("dispatchOnUnload", 0, NULL, NULL);
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtNetwork module of the Qt eXTension library
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of th Common Public License, version 1.0, as published by
** IBM.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL along with this file.
** See the LICENSE file and the cpl1.0.txt file included with the source
** distribution for more information. If you did not receive a copy of the
** license, contact the Qxt Foundation.
**
** <http://libqxt.sourceforge.net>  <foundation@libqxt.org>
**
****************************************************************************/

#include "qxtlinesocket_p.h"

#include <QIODevice>

/**
\class QxtLineSocket QxtLineSocket

\ingroup QxtCore

\brief Acts on a QIOdevice as baseclass for line-based protocols
*/

QxtLineSocket::QxtLineSocket (QIODevice * socket,QObject * parent):QObject(parent)
{
    QXT_INIT_PRIVATE(QxtLineSocket);
    qxt_d().socket=socket;
    connect(qxt_d().socket,SIGNAL(readyRead()),&qxt_d(),SLOT(readyRead()));
}

QxtLineSocket::QxtLineSocket (QObject * parent):QObject(parent)
{
    QXT_INIT_PRIVATE(QxtLineSocket);
    qxt_d().socket=0;
}

void QxtLineSocket::setSocket(QIODevice * a)
{
    if (qxt_d().socket)
        disconnect(qxt_d().socket);
    qxt_d().socket=a;
    connect(qxt_d().socket,SIGNAL(readyRead()),&qxt_d(),SLOT(readyRead()));
}

QIODevice * QxtLineSocket::socket() const
{
    return qxt_d().socket;
}

void QxtLineSocket::sendLine(QByteArray a)
{
    qxt_d().socket->write(a.replace('\n',"")+'\n');
}

void QxtLineSocket::newLine(QByteArray a)
{
    emit(newLineReceived(a));
}

void QxtLineSocketPrivate::readyRead()
{
    rbuff+=socket->readAll();

    int i=rbuff.indexOf('\n');
    if (i>-1)
    {
        (&qxt_p())->newLine(rbuff.left(i));
        rbuff=rbuff.mid(i+1);
    }
}

<commit_msg>fixed missing loop<commit_after>/****************************************************************************
**
** Copyright (C) Qxt Foundation. Some rights reserved.
**
** This file is part of the QxtNetwork module of the Qt eXTension library
**
** This library is free software; you can redistribute it and/or modify it
** under the terms of th Common Public License, version 1.0, as published by
** IBM.
**
** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY
** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY
** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
** FITNESS FOR A PARTICULAR PURPOSE.
**
** You should have received a copy of the CPL along with this file.
** See the LICENSE file and the cpl1.0.txt file included with the source
** distribution for more information. If you did not receive a copy of the
** license, contact the Qxt Foundation.
**
** <http://libqxt.sourceforge.net>  <foundation@libqxt.org>
**
****************************************************************************/

#include "qxtlinesocket_p.h"

#include <QIODevice>

/**
\class QxtLineSocket QxtLineSocket

\ingroup QxtCore

\brief Acts on a QIOdevice as baseclass for line-based protocols
*/

QxtLineSocket::QxtLineSocket (QIODevice * socket,QObject * parent):QObject(parent)
{
    QXT_INIT_PRIVATE(QxtLineSocket);
    qxt_d().socket=socket;
    connect(qxt_d().socket,SIGNAL(readyRead()),&qxt_d(),SLOT(readyRead()));
}

QxtLineSocket::QxtLineSocket (QObject * parent):QObject(parent)
{
    QXT_INIT_PRIVATE(QxtLineSocket);
    qxt_d().socket=0;
}

void QxtLineSocket::setSocket(QIODevice * a)
{
    if (qxt_d().socket)
        disconnect(qxt_d().socket);
    qxt_d().socket=a;
    connect(qxt_d().socket,SIGNAL(readyRead()),&qxt_d(),SLOT(readyRead()));
}

QIODevice * QxtLineSocket::socket() const
{
    return qxt_d().socket;
}

void QxtLineSocket::sendLine(QByteArray a)
{
    qxt_d().socket->write(a.replace('\n',"")+'\n');
}

void QxtLineSocket::newLine(QByteArray a)
{
    emit(newLineReceived(a));
}

void QxtLineSocketPrivate::readyRead()
{
    rbuff+=socket->readAll();

    int i=0;
    while((i=rbuff.indexOf('\n'))>-1)
    {
        (&qxt_p())->newLine(rbuff.left(i));
        rbuff=rbuff.mid(i+1);
    }
}

<|endoftext|>


<commit_before><commit_msg>Planning : update test and resolve interface change<commit_after><|endoftext|>


<commit_before>/*=========================================================================

  Program:   KWSys - Kitware System Library
  Module:    Glob.cxx

  Copyright (c) Kitware, Inc., Insight Consortium.  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Glob.hxx)

#include KWSYS_HEADER(Configure.hxx)

#include KWSYS_HEADER(RegularExpression.hxx)
#include KWSYS_HEADER(SystemTools.hxx)
#include KWSYS_HEADER(Directory.hxx)
#include KWSYS_HEADER(stl/string)
#include KWSYS_HEADER(stl/vector)

// Work-around CMake dependency scanning limitation.  This must
// duplicate the above list of headers.
#if 0
# include "Glob.hxx.in"
# include "Directory.hxx.in"
# include "Configure.hxx.in"
# include "RegularExpression.hxx.in"
# include "SystemTools.hxx.in"
# include "kwsys_stl.hxx.in"
# include "kwsys_stl_string.hxx.in"
#endif

#include <ctype.h>
#include <stdio.h>
#include <string.h>
namespace KWSYS_NAMESPACE
{
#if defined(_WIN32) || defined(__APPLE__) || defined(__CYGWIN__)
// On Windows and apple, no difference between lower and upper case
# define KWSYS_GLOB_CASE_INDEPENDENT
#endif

#if defined(_WIN32) || defined(__CYGWIN__)
// Handle network paths
# define KWSYS_GLOB_SUPPORT_NETWORK_PATHS
#endif

//----------------------------------------------------------------------------
class GlobInternals
{
public:
  kwsys_stl::vector<kwsys_stl::string> Files;
  kwsys_stl::vector<kwsys::RegularExpression> Expressions;
};

//----------------------------------------------------------------------------
Glob::Glob()
{
  this->Internals = new GlobInternals;
  this->Recurse = false;
  this->Relative = "";
}

//----------------------------------------------------------------------------
Glob::~Glob()
{
  delete this->Internals;
}

//----------------------------------------------------------------------------
kwsys_stl::vector<kwsys_stl::string>& Glob::GetFiles()
{
  return this->Internals->Files;
}

//----------------------------------------------------------------------------
kwsys_stl::string Glob::PatternToRegex(const kwsys_stl::string& pattern,
                                       bool require_whole_string)
{
  // Incrementally build the regular expression from the pattern.
  kwsys_stl::string regex = require_whole_string? "^" : "";
  kwsys_stl::string::const_iterator pattern_first = pattern.begin();
  kwsys_stl::string::const_iterator pattern_last = pattern.end();
  for(kwsys_stl::string::const_iterator i = pattern_first;
      i != pattern_last; ++i)
    {
    int c = *i;
    if(c == '*')
      {
      // A '*' (not between brackets) matches any string.
      // We modify this to not match slashes since the orignal glob
      // pattern documentation was meant for matching file name
      // components separated by slashes.
      regex += "[^/]*";
      }
    else if(c == '?')
      {
      // A '?' (not between brackets) matches any single character.
      // We modify this to not match slashes since the orignal glob
      // pattern documentation was meant for matching file name
      // components separated by slashes.
      regex += "[^/]";
      }
    else if(c == '[')
      {
      // Parse out the bracket expression.  It begins just after the
      // opening character.
      kwsys_stl::string::const_iterator bracket_first = i+1;
      kwsys_stl::string::const_iterator bracket_last = bracket_first;

      // The first character may be complementation '!' or '^'.
      if(bracket_last != pattern_last &&
         (*bracket_last == '!' || *bracket_last == '^'))
        {
        ++bracket_last;
        }

      // If the next character is a ']' it is included in the brackets
      // because the bracket string may not be empty.
      if(bracket_last != pattern_last && *bracket_last == ']')
        {
        ++bracket_last;
        }

      // Search for the closing ']'.
      while(bracket_last != pattern_last && *bracket_last != ']')
        {
        ++bracket_last;
        }

      // Check whether we have a complete bracket string.
      if(bracket_last == pattern_last)
        {
        // The bracket string did not end, so it was opened simply by
        // a '[' that is supposed to be matched literally.
        regex += "\\[";
        }
      else
        {
        // Convert the bracket string to its regex equivalent.
        kwsys_stl::string::const_iterator k = bracket_first;

        // Open the regex block.
        regex += "[";

        // A regex range complement uses '^' instead of '!'.
        if(k != bracket_last && *k == '!')
          {
          regex += "^";
          ++k;
          }

        // Convert the remaining characters.
        for(; k != bracket_last; ++k)
          {
          // Backslashes must be escaped.
          if(*k == '\\')
            {
            regex += "\\";
            }

          // Store this character.
          regex += *k;
          }

        // Close the regex block.
        regex += "]";

        // Jump to the end of the bracket string.
        i = bracket_last;
        }
      }
    else
      {
      // A single character matches itself.
      int ch = c;
      if(!(('a' <= ch && ch <= 'z') ||
           ('A' <= ch && ch <= 'Z') ||
           ('0' <= ch && ch <= '9')))
        {
        // Escape the non-alphanumeric character.
        regex += "\\";
        }
#if defined(KWSYS_GLOB_CASE_INDEPENDENT)
      else
        {
        // On case-insensitive systems file names are converted to lower
        // case before matching.
        ch = tolower(ch);
        }
#endif

      // Store the character.
      regex.append(1, static_cast<char>(ch));
      }
    }

  if(require_whole_string)
    {
    regex += "$";
    }
  return regex;
}

//----------------------------------------------------------------------------
void Glob::RecurseDirectory(kwsys_stl::string::size_type start,
  const kwsys_stl::string& dir, bool dir_only)
{
  kwsys::Directory d;
  if ( !d.Load(dir.c_str()) )
    {
    return;
    }
  unsigned long cc;
  kwsys_stl::string fullname;
  kwsys_stl::string realname;
  kwsys_stl::string fname;
  for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
    {
    fname = d.GetFile(cc);
    if ( strcmp(fname.c_str(), ".") == 0 ||
      strcmp(fname.c_str(), "..") == 0  )
      {
      continue;
      }

    if ( start == 0 )
      {
      realname = dir + fname;
      }
    else
      {
      realname = dir + "/" + fname;
      }

#if defined( KWSYS_GLOB_CASE_INDEPENDENT )
    // On Windows and apple, no difference between lower and upper case
    fname = kwsys::SystemTools::LowerCase(fname);
#endif

    if ( start == 0 )
      {
      fullname = dir + fname;
      }
    else
      {
      fullname = dir + "/" + fname;
      }

    if ( !dir_only || !kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
      {
      if ( this->Internals->Expressions[
        this->Internals->Expressions.size()-1].find(fname.c_str()) )
        {
        this->AddFile(this->Internals->Files, realname.c_str());
        }
      }
    if ( kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
      {
      this->RecurseDirectory(start+1, realname, dir_only);
      }
    }
}

//----------------------------------------------------------------------------
void Glob::ProcessDirectory(kwsys_stl::string::size_type start,
  const kwsys_stl::string& dir, bool dir_only)
{
  //kwsys_ios::cout << "ProcessDirectory: " << dir << kwsys_ios::endl;
  bool last = ( start == this->Internals->Expressions.size()-1 );
  if ( last && this->Recurse )
    {
    this->RecurseDirectory(start, dir, dir_only);
    return;
    }
  kwsys::Directory d;
  if ( !d.Load(dir.c_str()) )
    {
    return;
    }
  unsigned long cc;
  kwsys_stl::string fullname;
  kwsys_stl::string realname;
  kwsys_stl::string fname;
  for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
    {
    fname = d.GetFile(cc);
    if ( strcmp(fname.c_str(), ".") == 0 ||
      strcmp(fname.c_str(), "..") == 0  )
      {
      continue;
      }

    if ( start == 0 )
      {
      realname = dir + fname;
      }
    else
      {
      realname = dir + "/" + fname;
      }

#if defined(KWSYS_GLOB_CASE_INDEPENDENT)
    // On case-insensitive file systems convert to lower case for matching.
    fname = kwsys::SystemTools::LowerCase(fname);
#endif

    if ( start == 0 )
      {
      fullname = dir + fname;
      }
    else
      {
      fullname = dir + "/" + fname;
      }

    //kwsys_ios::cout << "Look at file: " << fname << kwsys_ios::endl;
    //kwsys_ios::cout << "Match: "
    // << this->Internals->TextExpressions[start].c_str() << kwsys_ios::endl;
    //kwsys_ios::cout << "Full name: " << fullname << kwsys_ios::endl;

    if ( (!dir_only || !last) &&
      !kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
      {
      continue;
      }

    if ( this->Internals->Expressions[start].find(fname.c_str()) )
      {
      if ( last )
        {
        this->AddFile(this->Internals->Files, realname.c_str());
        }
      else
        {
        this->ProcessDirectory(start+1, realname + "/", dir_only);
        }
      }
    }
}

//----------------------------------------------------------------------------
bool Glob::FindFiles(const kwsys_stl::string& inexpr)
{
  kwsys_stl::string cexpr;
  kwsys_stl::string::size_type cc;
  kwsys_stl::string expr = inexpr;

  this->Internals->Expressions.clear();
  this->Internals->Files.clear();

  if ( !kwsys::SystemTools::FileIsFullPath(expr.c_str()) )
    {
    expr = kwsys::SystemTools::GetCurrentWorkingDirectory();
    expr += "/" + inexpr;
    }
  kwsys_stl::string fexpr = expr;

  int skip = 0;
  int last_slash = 0;
  for ( cc = 0; cc < expr.size(); cc ++ )
    {
    if ( cc > 0 && expr[cc] == '/' && expr[cc-1] != '\\' )
      {
      last_slash = static_cast<int>(cc);
      }
    if ( cc > 0 &&
      (expr[cc] == '[' || expr[cc] == '?' || expr[cc] == '*') &&
      expr[cc-1] != '\\' )
      {
      break;
      }
    }
  if ( last_slash > 0 )
    {
    //kwsys_ios::cout << "I can skip: " << fexpr.substr(0, last_slash)
    //<< kwsys_ios::endl;
    skip = last_slash;
    }
  if ( skip == 0 )
    {
#if defined( KWSYS_GLOB_SUPPORT_NETWORK_PATHS )
    // Handle network paths
    if ( expr[0] == '/' && expr[1] == '/' )
      {
      int cnt = 0;
      for ( cc = 2; cc < expr.size(); cc ++ )
        {
        if ( expr[cc] == '/' )
          {
          cnt ++;
          if ( cnt == 2 )
            {
            break;
            }
          }
        }
      skip = int(cc + 1);
      }
    else
#endif
      // Handle drive letters on Windows
      if ( expr[1] == ':' && expr[0] != '/' )
        {
        skip = 2;
        }
    }

  if ( skip > 0 )
    {
    expr = expr.substr(skip);
    }

  cexpr = "";
  for ( cc = 0; cc < expr.size(); cc ++ )
    {
    int ch = expr[cc];
    if ( ch == '/' )
      {
      if ( cexpr.size() > 0 )
        {
        this->AddExpression(cexpr.c_str());
        }
      cexpr = "";
      }
    else
      {
      cexpr.append(1, static_cast<char>(ch));
      }
    }
  if ( cexpr.size() > 0 )
    {
    this->AddExpression(cexpr.c_str());
    }

  // Handle network paths
  if ( skip > 0 )
    {
    this->ProcessDirectory(0, fexpr.substr(0, skip) + "/",
      true);
    }
  else
    {
    this->ProcessDirectory(0, "/", true);
    }
  return true;
}

//----------------------------------------------------------------------------
void Glob::AddExpression(const char* expr)
{
  this->Internals->Expressions.push_back(
    kwsys::RegularExpression(
      this->PatternToRegex(expr).c_str()));
}

//----------------------------------------------------------------------------
void Glob::SetRelative(const char* dir)
{
  if ( !dir )
    {
    this->Relative = "";
    return;
    }
  this->Relative = dir;
}

//----------------------------------------------------------------------------
const char* Glob::GetRelative()
{
  if ( this->Relative.empty() )
    {
    return 0;
    }
  return this->Relative.c_str();
}

//----------------------------------------------------------------------------
void Glob::AddFile(kwsys_stl::vector<kwsys_stl::string>& files, const char* file)
{
  if ( !this->Relative.empty() )
    {
    files.push_back(kwsys::SystemTools::RelativePath(this->Relative.c_str(), file));
    }
  else
    {
    files.push_back(file);
    }
}

} // namespace KWSYS_NAMESPACE

<commit_msg><commit_after>/*=========================================================================

  Program:   KWSys - Kitware System Library
  Module:    Glob.cxx

  Copyright (c) Kitware, Inc., Insight Consortium.  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Glob.hxx)

#include KWSYS_HEADER(Configure.hxx)

#include KWSYS_HEADER(RegularExpression.hxx)
#include KWSYS_HEADER(SystemTools.hxx)
#include KWSYS_HEADER(Directory.hxx)
#include KWSYS_HEADER(stl/string)
#include KWSYS_HEADER(stl/vector)

// Work-around CMake dependency scanning limitation.  This must
// duplicate the above list of headers.
#if 0
# include "Glob.hxx.in"
# include "Directory.hxx.in"
# include "Configure.hxx.in"
# include "RegularExpression.hxx.in"
# include "SystemTools.hxx.in"
# include "kwsys_stl.hxx.in"
# include "kwsys_stl_string.hxx.in"
#endif

#include <ctype.h>
#include <stdio.h>
#include <string.h>
namespace KWSYS_NAMESPACE
{
#if defined(_WIN32) || defined(__APPLE__) || defined(__CYGWIN__)
// On Windows and apple, no difference between lower and upper case
# define KWSYS_GLOB_CASE_INDEPENDENT
#endif

#if defined(_WIN32) || defined(__CYGWIN__)
// Handle network paths
# define KWSYS_GLOB_SUPPORT_NETWORK_PATHS
#endif

//----------------------------------------------------------------------------
class GlobInternals
{
public:
  kwsys_stl::vector<kwsys_stl::string> Files;
  kwsys_stl::vector<kwsys::RegularExpression> Expressions;
};

//----------------------------------------------------------------------------
Glob::Glob()
{
  this->Internals = new GlobInternals;
  this->Recurse = false;
  this->Relative = "";
}

//----------------------------------------------------------------------------
Glob::~Glob()
{
  delete this->Internals;
}

//----------------------------------------------------------------------------
kwsys_stl::vector<kwsys_stl::string>& Glob::GetFiles()
{
  return this->Internals->Files;
}

//----------------------------------------------------------------------------
kwsys_stl::string Glob::PatternToRegex(const kwsys_stl::string& pattern,
                                       bool require_whole_string)
{
  // Incrementally build the regular expression from the pattern.
  kwsys_stl::string regex = require_whole_string? "^" : "";
  kwsys_stl::string::const_iterator pattern_first = pattern.begin();
  kwsys_stl::string::const_iterator pattern_last = pattern.end();
  for(kwsys_stl::string::const_iterator i = pattern_first;
      i != pattern_last; ++i)
    {
    int c = *i;
    if(c == '*')
      {
      // A '*' (not between brackets) matches any string.
      // We modify this to not match slashes since the orignal glob
      // pattern documentation was meant for matching file name
      // components separated by slashes.
      regex += "[^/]*";
      }
    else if(c == '?')
      {
      // A '?' (not between brackets) matches any single character.
      // We modify this to not match slashes since the orignal glob
      // pattern documentation was meant for matching file name
      // components separated by slashes.
      regex += "[^/]";
      }
    else if(c == '[')
      {
      // Parse out the bracket expression.  It begins just after the
      // opening character.
      kwsys_stl::string::const_iterator bracket_first = i+1;
      kwsys_stl::string::const_iterator bracket_last = bracket_first;

      // The first character may be complementation '!' or '^'.
      if(bracket_last != pattern_last &&
         (*bracket_last == '!' || *bracket_last == '^'))
        {
        ++bracket_last;
        }

      // If the next character is a ']' it is included in the brackets
      // because the bracket string may not be empty.
      if(bracket_last != pattern_last && *bracket_last == ']')
        {
        ++bracket_last;
        }

      // Search for the closing ']'.
      while(bracket_last != pattern_last && *bracket_last != ']')
        {
        ++bracket_last;
        }

      // Check whether we have a complete bracket string.
      if(bracket_last == pattern_last)
        {
        // The bracket string did not end, so it was opened simply by
        // a '[' that is supposed to be matched literally.
        regex += "\\[";
        }
      else
        {
        // Convert the bracket string to its regex equivalent.
        kwsys_stl::string::const_iterator k = bracket_first;

        // Open the regex block.
        regex += "[";

        // A regex range complement uses '^' instead of '!'.
        if(k != bracket_last && *k == '!')
          {
          regex += "^";
          ++k;
          }

        // Convert the remaining characters.
        for(; k != bracket_last; ++k)
          {
          // Backslashes must be escaped.
          if(*k == '\\')
            {
            regex += "\\";
            }

          // Store this character.
          regex += *k;
          }

        // Close the regex block.
        regex += "]";

        // Jump to the end of the bracket string.
        i = bracket_last;
        }
      }
    else
      {
      // A single character matches itself.
      int ch = c;
      if(!(('a' <= ch && ch <= 'z') ||
           ('A' <= ch && ch <= 'Z') ||
           ('0' <= ch && ch <= '9')))
        {
        // Escape the non-alphanumeric character.
        regex += "\\";
        }
#if defined(KWSYS_GLOB_CASE_INDEPENDENT)
      else
        {
        // On case-insensitive systems file names are converted to lower
        // case before matching.
        ch = tolower(ch);
        }
#endif

      // Store the character.
      regex.append(1, static_cast<char>(ch));
      }
    }

  if(require_whole_string)
    {
    regex += "$";
    }
  return regex;
}

//----------------------------------------------------------------------------
void Glob::RecurseDirectory(kwsys_stl::string::size_type start,
  const kwsys_stl::string& dir, bool dir_only)
{
  kwsys::Directory d;
  if ( !d.Load(dir.c_str()) )
    {
    return;
    }
  unsigned long cc;
  kwsys_stl::string fullname;
  kwsys_stl::string realname;
  kwsys_stl::string fname;
  for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
    {
    fname = d.GetFile(cc);
    if ( strcmp(fname.c_str(), ".") == 0 ||
      strcmp(fname.c_str(), "..") == 0  )
      {
      continue;
      }

    if ( start == 0 )
      {
      realname = dir + fname;
      }
    else
      {
      realname = dir + "/" + fname;
      }

#if defined( KWSYS_GLOB_CASE_INDEPENDENT )
    // On Windows and apple, no difference between lower and upper case
    fname = kwsys::SystemTools::LowerCase(fname);
#endif

    if ( start == 0 )
      {
      fullname = dir + fname;
      }
    else
      {
      fullname = dir + "/" + fname;
      }

    if ( !dir_only || !kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
      {
      if ( (this->Internals->Expressions.size() > 0) &&
           this->Internals->Expressions[
             this->Internals->Expressions.size()-1].find(fname.c_str()) )
        {
        this->AddFile(this->Internals->Files, realname.c_str());
        }
      }
    if ( kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
      {
      this->RecurseDirectory(start+1, realname, dir_only);
      }
    }
}

//----------------------------------------------------------------------------
void Glob::ProcessDirectory(kwsys_stl::string::size_type start,
  const kwsys_stl::string& dir, bool dir_only)
{
  //kwsys_ios::cout << "ProcessDirectory: " << dir << kwsys_ios::endl;
  bool last = ( start == this->Internals->Expressions.size()-1 );
  if ( last && this->Recurse )
    {
    this->RecurseDirectory(start, dir, dir_only);
    return;
    }

  if ( start >= this->Internals->Expressions.size() )
    {
    return;
    }

  kwsys::Directory d;
  if ( !d.Load(dir.c_str()) )
    {
    return;
    }
  unsigned long cc;
  kwsys_stl::string fullname;
  kwsys_stl::string realname;
  kwsys_stl::string fname;
  for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
    {
    fname = d.GetFile(cc);
    if ( strcmp(fname.c_str(), ".") == 0 ||
      strcmp(fname.c_str(), "..") == 0  )
      {
      continue;
      }

    if ( start == 0 )
      {
      realname = dir + fname;
      }
    else
      {
      realname = dir + "/" + fname;
      }

#if defined(KWSYS_GLOB_CASE_INDEPENDENT)
    // On case-insensitive file systems convert to lower case for matching.
    fname = kwsys::SystemTools::LowerCase(fname);
#endif

    if ( start == 0 )
      {
      fullname = dir + fname;
      }
    else
      {
      fullname = dir + "/" + fname;
      }

    //kwsys_ios::cout << "Look at file: " << fname << kwsys_ios::endl;
    //kwsys_ios::cout << "Match: "
    // << this->Internals->TextExpressions[start].c_str() << kwsys_ios::endl;
    //kwsys_ios::cout << "Full name: " << fullname << kwsys_ios::endl;

    if ( (!dir_only || !last) &&
      !kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
      {
      continue;
      }

    if ( this->Internals->Expressions[start].find(fname.c_str()) )
      {
      if ( last )
        {
        this->AddFile(this->Internals->Files, realname.c_str());
        }
      else
        {
        this->ProcessDirectory(start+1, realname + "/", dir_only);
        }
      }
    }
}

//----------------------------------------------------------------------------
bool Glob::FindFiles(const kwsys_stl::string& inexpr)
{
  kwsys_stl::string cexpr;
  kwsys_stl::string::size_type cc;
  kwsys_stl::string expr = inexpr;

  this->Internals->Expressions.clear();
  this->Internals->Files.clear();

  if ( !kwsys::SystemTools::FileIsFullPath(expr.c_str()) )
    {
    expr = kwsys::SystemTools::GetCurrentWorkingDirectory();
    expr += "/" + inexpr;
    }
  kwsys_stl::string fexpr = expr;

  int skip = 0;
  int last_slash = 0;
  for ( cc = 0; cc < expr.size(); cc ++ )
    {
    if ( cc > 0 && expr[cc] == '/' && expr[cc-1] != '\\' )
      {
      last_slash = static_cast<int>(cc);
      }
    if ( cc > 0 &&
      (expr[cc] == '[' || expr[cc] == '?' || expr[cc] == '*') &&
      expr[cc-1] != '\\' )
      {
      break;
      }
    }
  if ( last_slash > 0 )
    {
    //kwsys_ios::cout << "I can skip: " << fexpr.substr(0, last_slash)
    //<< kwsys_ios::endl;
    skip = last_slash;
    }
  if ( skip == 0 )
    {
#if defined( KWSYS_GLOB_SUPPORT_NETWORK_PATHS )
    // Handle network paths
    if ( expr[0] == '/' && expr[1] == '/' )
      {
      int cnt = 0;
      for ( cc = 2; cc < expr.size(); cc ++ )
        {
        if ( expr[cc] == '/' )
          {
          cnt ++;
          if ( cnt == 2 )
            {
            break;
            }
          }
        }
      skip = int(cc + 1);
      }
    else
#endif
      // Handle drive letters on Windows
      if ( expr[1] == ':' && expr[0] != '/' )
        {
        skip = 2;
        }
    }

  if ( skip > 0 )
    {
    expr = expr.substr(skip);
    }

  cexpr = "";
  for ( cc = 0; cc < expr.size(); cc ++ )
    {
    int ch = expr[cc];
    if ( ch == '/' )
      {
      if ( cexpr.size() > 0 )
        {
        this->AddExpression(cexpr.c_str());
        }
      cexpr = "";
      }
    else
      {
      cexpr.append(1, static_cast<char>(ch));
      }
    }
  if ( cexpr.size() > 0 )
    {
    this->AddExpression(cexpr.c_str());
    }

  // Handle network paths
  if ( skip > 0 )
    {
    this->ProcessDirectory(0, fexpr.substr(0, skip) + "/",
      true);
    }
  else
    {
    this->ProcessDirectory(0, "/", true);
    }
  return true;
}

//----------------------------------------------------------------------------
void Glob::AddExpression(const char* expr)
{
  this->Internals->Expressions.push_back(
    kwsys::RegularExpression(
      this->PatternToRegex(expr).c_str()));
}

//----------------------------------------------------------------------------
void Glob::SetRelative(const char* dir)
{
  if ( !dir )
    {
    this->Relative = "";
    return;
    }
  this->Relative = dir;
}

//----------------------------------------------------------------------------
const char* Glob::GetRelative()
{
  if ( this->Relative.empty() )
    {
    return 0;
    }
  return this->Relative.c_str();
}

//----------------------------------------------------------------------------
void Glob::AddFile(kwsys_stl::vector<kwsys_stl::string>& files, const char* file)
{
  if ( !this->Relative.empty() )
    {
    files.push_back(kwsys::SystemTools::RelativePath(this->Relative.c_str(), file));
    }
  else
    {
    files.push_back(file);
    }
}

} // namespace KWSYS_NAMESPACE

<|endoftext|>


<commit_before><commit_msg>remove dependency on [Sampler|Uniform]InterfaceBlock.h<commit_after><|endoftext|>


<commit_before><commit_msg>Add error message to matinfo.<commit_after><|endoftext|>