<commit_before>/*
 * Copyright deipi.com LLC and contributors. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "multivalue.h"

#include "length.h"

#include <assert.h>

void
StringList::unserialise(const std::string & serialised)
{
	const char * ptr = serialised.data();
	const char * end = serialised.data() + serialised.size();
	unserialise(&ptr, end);
}

void
StringList::unserialise(const char ** ptr, const char * end)
{
	clear();
	size_t length = decode_length(ptr, end, true);
	if (length == -1 || length != end - *ptr) {
		push_back(std::string(*ptr, end - *ptr));
	} else {
		size_t currlen;
		while (*ptr != end) {
			currlen = decode_length(ptr, end, true);
			if (currlen == -1) {
				// FIXME: throwing a NetworkError if the length is too long - should be a more appropriate error.
				throw Xapian::NetworkError("Decoding error of serialised MultiValueCountMatchSpy");
			}
			push_back(std::string(*ptr, currlen));
			*ptr += currlen;
		}
	}
}

std::string
StringList::serialise() const
{
	std::string serialised, values;
	StringList::const_iterator i(begin());
	if (size() > 1) {
		for (; i != end(); i++) {
			values.append(encode_length((*i).size()));
			values.append(*i);
		}
		serialised.append(MULTIVALUE_MAGIC);
		serialised.append(encode_length(values.size()));
	} else if (i != end()) {
		values.assign(*i);
	}
	serialised.append(values);
	return serialised;
}

void
MultiValueCountMatchSpy::operator()(const Xapian::Document &doc, double) {
	assert(internal.get());
	++(internal->total);
	StringList list;
	list.unserialise(doc.get_value(internal->slot));
	StringList::const_iterator i(list.begin());
	for (; i != list.end(); i++) {
		std::string val(*i);
		if (!val.empty()) ++(internal->values[val]);
	}
}

Xapian::MatchSpy *
MultiValueCountMatchSpy::clone() const {
	assert(internal.get());
	return new MultiValueCountMatchSpy(internal->slot);
}

std::string
MultiValueCountMatchSpy::name() const {
	return "Xapian::MultiValueCountMatchSpy";
}

std::string
MultiValueCountMatchSpy::serialise() const {
	assert(internal.get());
	std::string result;
	result += encode_length(internal->slot);
	return result;
}

Xapian::MatchSpy *
MultiValueCountMatchSpy::unserialise(const std::string & s,
									 const Xapian::Registry &) const{
	const char * p = s.data();
	const char * end = p + s.size();

	Xapian::valueno new_slot = decode_length(&p, end, false);
	if (new_slot == -1) {
		throw Xapian::NetworkError("Decoding error of serialised MultiValueCountMatchSpy");
	}
	if (p != end) {
		throw Xapian::NetworkError("Junk at end of serialised MultiValueCountMatchSpy");
	}

	return new MultiValueCountMatchSpy(new_slot);
}

std::string
MultiValueCountMatchSpy::get_description() const {
	char buffer[20];
	std::string d = "MultiValueCountMatchSpy(";
	if (internal.get()) {
		snprintf(buffer, sizeof(buffer), "%u", internal->total);
		d += buffer;
		d += " docs seen, looking in ";
		snprintf(buffer, sizeof(buffer), "%lu", internal->values.size());
		d += buffer;
		d += " slots)";
	} else {
		d += ")";
	}
	return d;
}<commit_msg>Don't append MULTIVALUE_MAGIC<commit_after>/*
 * Copyright deipi.com LLC and contributors. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "multivalue.h"

#include "length.h"

#include <assert.h>

void
StringList::unserialise(const std::string & serialised)
{
	const char * ptr = serialised.data();
	const char * end = serialised.data() + serialised.size();
	unserialise(&ptr, end);
}

void
StringList::unserialise(const char ** ptr, const char * end)
{
	clear();
	size_t length = decode_length(ptr, end, true);
	if (length == -1 || length != end - *ptr) {
		push_back(std::string(*ptr, end - *ptr));
	} else {
		size_t currlen;
		while (*ptr != end) {
			currlen = decode_length(ptr, end, true);
			if (currlen == -1) {
				// FIXME: throwing a NetworkError if the length is too long - should be a more appropriate error.
				throw Xapian::NetworkError("Decoding error of serialised MultiValueCountMatchSpy");
			}
			push_back(std::string(*ptr, currlen));
			*ptr += currlen;
		}
	}
}

std::string
StringList::serialise() const
{
	std::string serialised, values;
	StringList::const_iterator i(begin());
	if (size() > 1) {
		for (; i != end(); i++) {
			values.append(encode_length((*i).size()));
			values.append(*i);
		}
		serialised.append(encode_length(values.size()));
	} else if (i != end()) {
		values.assign(*i);
	}
	serialised.append(values);
	return serialised;
}

void
MultiValueCountMatchSpy::operator()(const Xapian::Document &doc, double) {
	assert(internal.get());
	++(internal->total);
	StringList list;
	list.unserialise(doc.get_value(internal->slot));
	StringList::const_iterator i(list.begin());
	for (; i != list.end(); i++) {
		std::string val(*i);
		if (!val.empty()) ++(internal->values[val]);
	}
}

Xapian::MatchSpy *
MultiValueCountMatchSpy::clone() const {
	assert(internal.get());
	return new MultiValueCountMatchSpy(internal->slot);
}

std::string
MultiValueCountMatchSpy::name() const {
	return "Xapian::MultiValueCountMatchSpy";
}

std::string
MultiValueCountMatchSpy::serialise() const {
	assert(internal.get());
	std::string result;
	result += encode_length(internal->slot);
	return result;
}

Xapian::MatchSpy *
MultiValueCountMatchSpy::unserialise(const std::string & s,
									 const Xapian::Registry &) const{
	const char * p = s.data();
	const char * end = p + s.size();

	Xapian::valueno new_slot = decode_length(&p, end, false);
	if (new_slot == -1) {
		throw Xapian::NetworkError("Decoding error of serialised MultiValueCountMatchSpy");
	}
	if (p != end) {
		throw Xapian::NetworkError("Junk at end of serialised MultiValueCountMatchSpy");
	}

	return new MultiValueCountMatchSpy(new_slot);
}

std::string
MultiValueCountMatchSpy::get_description() const {
	char buffer[20];
	std::string d = "MultiValueCountMatchSpy(";
	if (internal.get()) {
		snprintf(buffer, sizeof(buffer), "%u", internal->total);
		d += buffer;
		d += " docs seen, looking in ";
		snprintf(buffer, sizeof(buffer), "%lu", internal->values.size());
		d += buffer;
		d += " slots)";
	} else {
		d += ")";
	}
	return d;
}<|endoftext|>


<commit_before>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"

using namespace std;

void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = 1000;

#define PI 4*atan(1)

int main (int argc, char *argv[]) {
	string type = argv[1];
	transform(type.begin(), type.end(), type.begin(), :: tolower);
	// lets assume that the way to run this is
	// pwm.exe [rising/falling/sine/constant]
	if (argc != 2) {
		cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
		return -1;
	}

	while (time_to_complete <= 0) {
		cout << "Input How Long To Run (in seconds)" << endl;
		cin >> time_to_complete;
	}

	GPIOClass* out1 = new GPIOClass("4");
	GPIOClass* in2 = new GPIOClass("17");

	out1->export_gpio();
	in2->export_gpio();

	out1->setdir_gpio("out");
	in2->setdir_gpio("in");

	cout << "Pins are setup." << endl;
	// avoiding flickering will be at 100hz
	// aka turn on and off 100 times a sec
	// a cycle of 0 is off
	// a cycle of 100 is on

	if (type == "rising") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		double t = time_to_complete;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			t -= 1;
			//Pulse(out1, sin((2PI/2) * abs(1/t)));
			//Wait(sin((PI/2) * abs(1/t)));
			Pulse(out1, 1/resolution);
			Wait(sin((PI) * abs(1/t)));
		}
	}
	if (type == "falling") {

	}
	if (type == "sine") {

	}
	if (type == "constant") {
		out1->setval_gpio("1"); // turn the pin on
		Wait(time_to_complete); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		out1->setval_gpio("0"); // turn the pin off
	}
	if (type == "blink") { // aka. TESTR
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, 1/resolution);
			Wait(4/resolution);
		}
	}
	cout << "Done." << endl;
}

//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
	bool running = true;
	while (running) {
		pin->setval_gpio("1"); // turn the pin on
		Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		pin->setval_gpio("0"); // turn the pin off
		running = false; // this is unnessesary but could be useful if modified a bit.
	}
}

void Wait ( double seconds )
{
	clock_t endwait;
	endwait = clock () + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}
<commit_msg>Update pwm.cpp<commit_after>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"

using namespace std;

void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = 1000;

#define PI 4*atan(1)

int main (int argc, char *argv[]) {
	string type = argv[1];
	transform(type.begin(), type.end(), type.begin(), :: tolower);
	// lets assume that the way to run this is
	// pwm.exe [rising/falling/sine/constant]
	if (argc != 2) {
		cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
		return -1;
	}

	while (time_to_complete <= 0) {
		cout << "Input How Long To Run (in seconds)" << endl;
		cin >> time_to_complete;
	}

	GPIOClass* out1 = new GPIOClass("4");
	GPIOClass* in2 = new GPIOClass("17");

	out1->export_gpio();
	in2->export_gpio();

	out1->setdir_gpio("out");
	in2->setdir_gpio("in");

	cout << "Pins are setup." << endl;
	// avoiding flickering will be at 100hz
	// aka turn on and off 100 times a sec
	// a cycle of 0 is off
	// a cycle of 100 is on

	if (type == "rising") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		double t = time_to_complete;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			t -= 1;
			//Pulse(out1, sin((2PI/2) * abs(1/t)));
			//Wait(sin((PI/2) * abs(1/t)));
			Pulse(out1, 1/resolution);
			Wait(sin((PI/2)/t));
		}
	}
	if (type == "falling") {

	}
	if (type == "sine") {

	}
	if (type == "constant") {
		out1->setval_gpio("1"); // turn the pin on
		Wait(time_to_complete); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		out1->setval_gpio("0"); // turn the pin off
	}
	if (type == "blink") { // aka. TESTR
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, 1/resolution);
			Wait(4/resolution);
		}
	}
	cout << "Done." << endl;
}

//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
	bool running = true;
	while (running) {
		pin->setval_gpio("1"); // turn the pin on
		Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		pin->setval_gpio("0"); // turn the pin off
		running = false; // this is unnessesary but could be useful if modified a bit.
	}
}

void Wait ( double seconds )
{
	clock_t endwait;
	endwait = clock () + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    TestPruneTreeFilter.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  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 notice for more information.

=========================================================================*/

#include "vtkPruneTreeFilter.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkTree.h"

//----------------------------------------------------------------------------
int TestPruneTreeFilter(int argc, char* argv[])
{
  vtkNew<vtkMutableDirectedGraph> graph;
  vtkIdType root = graph->AddVertex();
  vtkIdType internalOne = graph->AddChild(root);
  vtkIdType internalTwo = graph->AddChild(internalOne);
  vtkIdType a = graph->AddChild(internalTwo);
  graph->AddChild(internalTwo);
  graph->AddChild(internalOne);
  graph->AddChild(a);
  graph->AddChild(a);

  vtkNew<vtkTree> tree;
  tree->ShallowCopy(graph.GetPointer());

  vtkNew<vtkPruneTreeFilter> filter;
  filter->SetInputData(tree.GetPointer());
  filter->SetParentVertex(internalTwo);
  vtkTree *prunedTree = filter->GetOutput();
  filter->Update();

  if (prunedTree->GetNumberOfVertices() == 3)
    {
    return EXIT_SUCCESS;
    }

  return EXIT_FAILURE;
}
<commit_msg>Fix "unreferenced formal parameter" warnings<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestPruneTreeFilter.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  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 notice for more information.

=========================================================================*/

#include "vtkPruneTreeFilter.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkTree.h"

//----------------------------------------------------------------------------
int TestPruneTreeFilter(int, char*[])
{
  vtkNew<vtkMutableDirectedGraph> graph;
  vtkIdType root = graph->AddVertex();
  vtkIdType internalOne = graph->AddChild(root);
  vtkIdType internalTwo = graph->AddChild(internalOne);
  vtkIdType a = graph->AddChild(internalTwo);
  graph->AddChild(internalTwo);
  graph->AddChild(internalOne);
  graph->AddChild(a);
  graph->AddChild(a);

  vtkNew<vtkTree> tree;
  tree->ShallowCopy(graph.GetPointer());

  vtkNew<vtkPruneTreeFilter> filter;
  filter->SetInputData(tree.GetPointer());
  filter->SetParentVertex(internalTwo);
  vtkTree *prunedTree = filter->GetOutput();
  filter->Update();

  if (prunedTree->GetNumberOfVertices() == 3)
    {
    return EXIT_SUCCESS;
    }

  return EXIT_FAILURE;
}
<|endoftext|>


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

#pragma hdrstop

#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SVX_SCRIPTTYPEITEM_HXX
#include <svx/scripttypeitem.hxx>
#endif

#ifndef FORMAT_HXX
#include "format.hxx"
#endif

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

// Latin default-fonts
static const USHORT aLatinDefFnts[FNT_END] =
{
    DEFAULTFONT_SERIF,  // FNT_VARIABLE
    DEFAULTFONT_SERIF,  // FNT_FUNCTION
    DEFAULTFONT_SERIF,  // FNT_NUMBER
    DEFAULTFONT_SERIF,  // FNT_TEXT
    DEFAULTFONT_SERIF,  // FNT_SERIF
    DEFAULTFONT_SANS,   // FNT_SANS
    DEFAULTFONT_FIXED   // FNT_FIXED
    //StarSymbol,    // FNT_MATH
};

// CJK default-fonts
//! we use non-asian fonts for variables, functions and numbers since they
//! look better and even in asia only latin letters will be used for those.
//! At least that's what I was told...
static const USHORT aCJKDefFnts[FNT_END] =
{
    DEFAULTFONT_SERIF,          // FNT_VARIABLE
    DEFAULTFONT_SERIF,          // FNT_FUNCTION
    DEFAULTFONT_SERIF,          // FNT_NUMBER
    DEFAULTFONT_CJK_TEXT,       // FNT_TEXT
    DEFAULTFONT_CJK_TEXT,       // FNT_SERIF
    DEFAULTFONT_CJK_DISPLAY,    // FNT_SANS
    DEFAULTFONT_CJK_TEXT        // FNT_FIXED
    //StarSymbol,    // FNT_MATH
};

// CTL default-fonts
static const USHORT aCTLDefFnts[FNT_END] =
{
    DEFAULTFONT_CTL_TEXT,    // FNT_VARIABLE
    DEFAULTFONT_CTL_TEXT,    // FNT_FUNCTION
    DEFAULTFONT_CTL_TEXT,    // FNT_NUMBER
    DEFAULTFONT_CTL_TEXT,    // FNT_TEXT
    DEFAULTFONT_CTL_TEXT,    // FNT_SERIF
    DEFAULTFONT_CTL_TEXT,    // FNT_SANS
    DEFAULTFONT_CTL_TEXT     // FNT_FIXED
    //StarSymbol,    // FNT_MATH
};

String GetDefaultFontName( LanguageType nLang, USHORT nIdent )
{
    DBG_ASSERT( FNT_BEGIN <= nIdent  &&  nIdent <= FNT_END,
            "index out opd range" );

    if (FNT_MATH == nIdent)
        return String::CreateFromAscii( FNTNAME_MATH );
    else
    {
        const USHORT *pTable;
        switch ( SvtLanguageOptions::GetScriptTypeOfLanguage( nLang ) )
        {
            case SCRIPTTYPE_LATIN :     pTable = aLatinDefFnts; break;
            case SCRIPTTYPE_ASIAN :     pTable = aCJKDefFnts; break;
            case SCRIPTTYPE_COMPLEX :   pTable = aCTLDefFnts; break;
            default :
                pTable = aLatinDefFnts;
                DBG_ERROR( "unknown script-type" );
        }

        return Application::GetDefaultDevice()->GetDefaultFont(
                        pTable[ nIdent ], nLang,
                        DEFAULTFONT_FLAGS_ONLYONE ).GetName();
    }
}

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

SmFormat::SmFormat()
:   aBaseSize(0, SmPtsTo100th_mm(12))
{
    nVersion    = SM_FMT_VERSION_NOW;

    eHorAlign   = AlignCenter;
    bIsTextmode = bScaleNormalBrackets = FALSE;

    vSize[SIZ_TEXT]     = 100;
    vSize[SIZ_INDEX]    = 60;
    vSize[SIZ_FUNCTION] =
    vSize[SIZ_OPERATOR] = 100;
    vSize[SIZ_LIMITS]   = 60;

    vDist[DIS_HORIZONTAL]           = 10;
    vDist[DIS_VERTICAL]             = 5;
    vDist[DIS_ROOT]                 = 0;
    vDist[DIS_SUPERSCRIPT]          =
    vDist[DIS_SUBSCRIPT]            = 20;
    vDist[DIS_NUMERATOR]            =
    vDist[DIS_DENOMINATOR]          = 0;
    vDist[DIS_FRACTION]             = 10;
    vDist[DIS_STROKEWIDTH]          = 5;
    vDist[DIS_UPPERLIMIT]           =
    vDist[DIS_LOWERLIMIT]           = 0;
    vDist[DIS_BRACKETSIZE]          =
    vDist[DIS_BRACKETSPACE]         = 5;
    vDist[DIS_MATRIXROW]            = 3;
    vDist[DIS_MATRIXCOL]            = 30;
    vDist[DIS_ORNAMENTSIZE]         =
    vDist[DIS_ORNAMENTSPACE]        = 0;
    vDist[DIS_OPERATORSIZE]         = 50;
    vDist[DIS_OPERATORSPACE]        = 20;
    vDist[DIS_LEFTSPACE]            =
    vDist[DIS_RIGHTSPACE]           = 100;
    vDist[DIS_TOPSPACE]             =
    vDist[DIS_BOTTOMSPACE]          =
    vDist[DIS_NORMALBRACKETSIZE]    = 0;

    vFont[FNT_VARIABLE] =
    vFont[FNT_FUNCTION] =
    vFont[FNT_NUMBER]   =
    vFont[FNT_TEXT]     =
    vFont[FNT_SERIF]    = SmFace(C2S(FNTNAME_TIMES), aBaseSize);
    vFont[FNT_SANS]     = SmFace(C2S(FNTNAME_HELV),  aBaseSize);
    vFont[FNT_FIXED]    = SmFace(C2S(FNTNAME_COUR),  aBaseSize);
    vFont[FNT_MATH]     = SmFace(C2S(FNTNAME_MATH),  aBaseSize);

    vFont[FNT_MATH].SetCharSet( RTL_TEXTENCODING_UNICODE );

    vFont[FNT_VARIABLE].SetItalic(ITALIC_NORMAL);
    vFont[FNT_FUNCTION].SetItalic(ITALIC_NONE);
    vFont[FNT_NUMBER]  .SetItalic(ITALIC_NONE);
    vFont[FNT_TEXT]    .SetItalic(ITALIC_NONE);
    vFont[FNT_SERIF]   .SetItalic(ITALIC_NONE);
    vFont[FNT_SANS]    .SetItalic(ITALIC_NONE);
    vFont[FNT_FIXED]   .SetItalic(ITALIC_NONE);

    for ( USHORT i = FNT_BEGIN;  i <= FNT_END;  i++ )
    {
        SmFace &rFace = vFont[i];
        rFace.SetTransparent( TRUE );
        rFace.SetAlign( ALIGN_BASELINE );
        rFace.SetColor( COL_AUTO );
        bDefaultFont[i] = FALSE;
    }
}

void SmFormat::SetFont(USHORT nIdent, const SmFace &rFont, BOOL bDefault )
{
    vFont[nIdent] = rFont;
    vFont[nIdent].SetTransparent( TRUE );
    vFont[nIdent].SetAlign( ALIGN_BASELINE );

    bDefaultFont[nIdent] = bDefault;
}

SmFormat & SmFormat::operator = (const SmFormat &rFormat)
{
    SetBaseSize(rFormat.GetBaseSize());
    SetVersion (rFormat.GetVersion());
    SetHorAlign(rFormat.GetHorAlign());
    SetTextmode(rFormat.IsTextmode());
    SetScaleNormalBrackets(rFormat.IsScaleNormalBrackets());

    USHORT  i;
    for (i = FNT_BEGIN;  i <= FNT_END;  i++)
    {
        SetFont(i, rFormat.GetFont(i));
        SetDefaultFont(i, rFormat.IsDefaultFont(i));
    }
    for (i = SIZ_BEGIN;  i <= SIZ_END;  i++)
        SetRelSize(i, rFormat.GetRelSize(i));
    for (i = DIS_BEGIN;  i <= DIS_END;  i++)
        SetDistance(i, rFormat.GetDistance(i));

    return *this;
}

BOOL SmFormat::operator == (const SmFormat &rFormat) const
{
    BOOL bRes = aBaseSize == rFormat.aBaseSize  &&
                eHorAlign == rFormat.eHorAlign  &&
                bIsTextmode == rFormat.bIsTextmode  &&
                bScaleNormalBrackets  == rFormat.bScaleNormalBrackets;

    USHORT i;
    for (i = 0;  i <= SIZ_END && bRes;  ++i)
    {
        if (vSize[i] != rFormat.vSize[i])
            bRes = FALSE;
    }
    for (i = 0;  i <= DIS_END && bRes;  ++i)
    {
        if (vDist[i] != rFormat.vDist[i])
            bRes = FALSE;
    }
    for (i = 0;  i <= FNT_END && bRes;  ++i)
    {
        if (vFont[i] != rFormat.vFont[i]  ||
            bDefaultFont[i] != rFormat.bDefaultFont[i])
            bRes = FALSE;
    }

    return bRes;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.10.56); FILE MERGED 2005/09/05 17:37:31 rt 1.10.56.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: format.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 15:07:31 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _SVX_SCRIPTTYPEITEM_HXX
#include <svx/scripttypeitem.hxx>
#endif

#ifndef FORMAT_HXX
#include "format.hxx"
#endif

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

// Latin default-fonts
static const USHORT aLatinDefFnts[FNT_END] =
{
    DEFAULTFONT_SERIF,  // FNT_VARIABLE
    DEFAULTFONT_SERIF,  // FNT_FUNCTION
    DEFAULTFONT_SERIF,  // FNT_NUMBER
    DEFAULTFONT_SERIF,  // FNT_TEXT
    DEFAULTFONT_SERIF,  // FNT_SERIF
    DEFAULTFONT_SANS,   // FNT_SANS
    DEFAULTFONT_FIXED   // FNT_FIXED
    //StarSymbol,    // FNT_MATH
};

// CJK default-fonts
//! we use non-asian fonts for variables, functions and numbers since they
//! look better and even in asia only latin letters will be used for those.
//! At least that's what I was told...
static const USHORT aCJKDefFnts[FNT_END] =
{
    DEFAULTFONT_SERIF,          // FNT_VARIABLE
    DEFAULTFONT_SERIF,          // FNT_FUNCTION
    DEFAULTFONT_SERIF,          // FNT_NUMBER
    DEFAULTFONT_CJK_TEXT,       // FNT_TEXT
    DEFAULTFONT_CJK_TEXT,       // FNT_SERIF
    DEFAULTFONT_CJK_DISPLAY,    // FNT_SANS
    DEFAULTFONT_CJK_TEXT        // FNT_FIXED
    //StarSymbol,    // FNT_MATH
};

// CTL default-fonts
static const USHORT aCTLDefFnts[FNT_END] =
{
    DEFAULTFONT_CTL_TEXT,    // FNT_VARIABLE
    DEFAULTFONT_CTL_TEXT,    // FNT_FUNCTION
    DEFAULTFONT_CTL_TEXT,    // FNT_NUMBER
    DEFAULTFONT_CTL_TEXT,    // FNT_TEXT
    DEFAULTFONT_CTL_TEXT,    // FNT_SERIF
    DEFAULTFONT_CTL_TEXT,    // FNT_SANS
    DEFAULTFONT_CTL_TEXT     // FNT_FIXED
    //StarSymbol,    // FNT_MATH
};

String GetDefaultFontName( LanguageType nLang, USHORT nIdent )
{
    DBG_ASSERT( FNT_BEGIN <= nIdent  &&  nIdent <= FNT_END,
            "index out opd range" );

    if (FNT_MATH == nIdent)
        return String::CreateFromAscii( FNTNAME_MATH );
    else
    {
        const USHORT *pTable;
        switch ( SvtLanguageOptions::GetScriptTypeOfLanguage( nLang ) )
        {
            case SCRIPTTYPE_LATIN :     pTable = aLatinDefFnts; break;
            case SCRIPTTYPE_ASIAN :     pTable = aCJKDefFnts; break;
            case SCRIPTTYPE_COMPLEX :   pTable = aCTLDefFnts; break;
            default :
                pTable = aLatinDefFnts;
                DBG_ERROR( "unknown script-type" );
        }

        return Application::GetDefaultDevice()->GetDefaultFont(
                        pTable[ nIdent ], nLang,
                        DEFAULTFONT_FLAGS_ONLYONE ).GetName();
    }
}

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

SmFormat::SmFormat()
:   aBaseSize(0, SmPtsTo100th_mm(12))
{
    nVersion    = SM_FMT_VERSION_NOW;

    eHorAlign   = AlignCenter;
    bIsTextmode = bScaleNormalBrackets = FALSE;

    vSize[SIZ_TEXT]     = 100;
    vSize[SIZ_INDEX]    = 60;
    vSize[SIZ_FUNCTION] =
    vSize[SIZ_OPERATOR] = 100;
    vSize[SIZ_LIMITS]   = 60;

    vDist[DIS_HORIZONTAL]           = 10;
    vDist[DIS_VERTICAL]             = 5;
    vDist[DIS_ROOT]                 = 0;
    vDist[DIS_SUPERSCRIPT]          =
    vDist[DIS_SUBSCRIPT]            = 20;
    vDist[DIS_NUMERATOR]            =
    vDist[DIS_DENOMINATOR]          = 0;
    vDist[DIS_FRACTION]             = 10;
    vDist[DIS_STROKEWIDTH]          = 5;
    vDist[DIS_UPPERLIMIT]           =
    vDist[DIS_LOWERLIMIT]           = 0;
    vDist[DIS_BRACKETSIZE]          =
    vDist[DIS_BRACKETSPACE]         = 5;
    vDist[DIS_MATRIXROW]            = 3;
    vDist[DIS_MATRIXCOL]            = 30;
    vDist[DIS_ORNAMENTSIZE]         =
    vDist[DIS_ORNAMENTSPACE]        = 0;
    vDist[DIS_OPERATORSIZE]         = 50;
    vDist[DIS_OPERATORSPACE]        = 20;
    vDist[DIS_LEFTSPACE]            =
    vDist[DIS_RIGHTSPACE]           = 100;
    vDist[DIS_TOPSPACE]             =
    vDist[DIS_BOTTOMSPACE]          =
    vDist[DIS_NORMALBRACKETSIZE]    = 0;

    vFont[FNT_VARIABLE] =
    vFont[FNT_FUNCTION] =
    vFont[FNT_NUMBER]   =
    vFont[FNT_TEXT]     =
    vFont[FNT_SERIF]    = SmFace(C2S(FNTNAME_TIMES), aBaseSize);
    vFont[FNT_SANS]     = SmFace(C2S(FNTNAME_HELV),  aBaseSize);
    vFont[FNT_FIXED]    = SmFace(C2S(FNTNAME_COUR),  aBaseSize);
    vFont[FNT_MATH]     = SmFace(C2S(FNTNAME_MATH),  aBaseSize);

    vFont[FNT_MATH].SetCharSet( RTL_TEXTENCODING_UNICODE );

    vFont[FNT_VARIABLE].SetItalic(ITALIC_NORMAL);
    vFont[FNT_FUNCTION].SetItalic(ITALIC_NONE);
    vFont[FNT_NUMBER]  .SetItalic(ITALIC_NONE);
    vFont[FNT_TEXT]    .SetItalic(ITALIC_NONE);
    vFont[FNT_SERIF]   .SetItalic(ITALIC_NONE);
    vFont[FNT_SANS]    .SetItalic(ITALIC_NONE);
    vFont[FNT_FIXED]   .SetItalic(ITALIC_NONE);

    for ( USHORT i = FNT_BEGIN;  i <= FNT_END;  i++ )
    {
        SmFace &rFace = vFont[i];
        rFace.SetTransparent( TRUE );
        rFace.SetAlign( ALIGN_BASELINE );
        rFace.SetColor( COL_AUTO );
        bDefaultFont[i] = FALSE;
    }
}

void SmFormat::SetFont(USHORT nIdent, const SmFace &rFont, BOOL bDefault )
{
    vFont[nIdent] = rFont;
    vFont[nIdent].SetTransparent( TRUE );
    vFont[nIdent].SetAlign( ALIGN_BASELINE );

    bDefaultFont[nIdent] = bDefault;
}

SmFormat & SmFormat::operator = (const SmFormat &rFormat)
{
    SetBaseSize(rFormat.GetBaseSize());
    SetVersion (rFormat.GetVersion());
    SetHorAlign(rFormat.GetHorAlign());
    SetTextmode(rFormat.IsTextmode());
    SetScaleNormalBrackets(rFormat.IsScaleNormalBrackets());

    USHORT  i;
    for (i = FNT_BEGIN;  i <= FNT_END;  i++)
    {
        SetFont(i, rFormat.GetFont(i));
        SetDefaultFont(i, rFormat.IsDefaultFont(i));
    }
    for (i = SIZ_BEGIN;  i <= SIZ_END;  i++)
        SetRelSize(i, rFormat.GetRelSize(i));
    for (i = DIS_BEGIN;  i <= DIS_END;  i++)
        SetDistance(i, rFormat.GetDistance(i));

    return *this;
}

BOOL SmFormat::operator == (const SmFormat &rFormat) const
{
    BOOL bRes = aBaseSize == rFormat.aBaseSize  &&
                eHorAlign == rFormat.eHorAlign  &&
                bIsTextmode == rFormat.bIsTextmode  &&
                bScaleNormalBrackets  == rFormat.bScaleNormalBrackets;

    USHORT i;
    for (i = 0;  i <= SIZ_END && bRes;  ++i)
    {
        if (vSize[i] != rFormat.vSize[i])
            bRes = FALSE;
    }
    for (i = 0;  i <= DIS_END && bRes;  ++i)
    {
        if (vDist[i] != rFormat.vDist[i])
            bRes = FALSE;
    }
    for (i = 0;  i <= FNT_END && bRes;  ++i)
    {
        if (vFont[i] != rFormat.vFont[i]  ||
            bDefaultFont[i] != rFormat.bDefaultFont[i])
            bRes = FALSE;
    }

    return bRes;
}

<|endoftext|>


<commit_before>#include "util/exception.hh"
#include "moses/FF/Factory.h"
#include "moses/StaticData.h"

#include "moses/TranslationModel/PhraseDictionaryTreeAdaptor.h"
#include "moses/TranslationModel/PhraseDictionaryMemory.h"
#include "moses/TranslationModel/PhraseDictionaryMultiModel.h"
#include "moses/TranslationModel/PhraseDictionaryMultiModelCounts.h"
#include "moses/TranslationModel/PhraseDictionaryScope3.h"
#include "moses/TranslationModel/PhraseDictionaryTransliteration.h"
#include "moses/TranslationModel/PhraseDictionaryDynamicCacheBased.h"

#include "moses/TranslationModel/RuleTable/PhraseDictionaryOnDisk.h"
#include "moses/TranslationModel/RuleTable/PhraseDictionaryFuzzyMatch.h"
#include "moses/TranslationModel/RuleTable/PhraseDictionaryALSuffixArray.h"

#include "moses/FF/LexicalReordering/LexicalReordering.h"

#include "moses/FF/BleuScoreFeature.h"
#include "moses/FF/TargetWordInsertionFeature.h"
#include "moses/FF/SourceWordDeletionFeature.h"
#include "moses/FF/GlobalLexicalModel.h"
#include "moses/FF/GlobalLexicalModelUnlimited.h"
#include "moses/FF/Model1Feature.h"
#include "moses/FF/UnknownWordPenaltyProducer.h"
#include "moses/FF/WordTranslationFeature.h"
#include "moses/FF/TargetBigramFeature.h"
#include "moses/FF/TargetNgramFeature.h"
#include "moses/FF/PhraseBoundaryFeature.h"
#include "moses/FF/PhrasePairFeature.h"
#include "moses/FF/RulePairUnlexicalizedSource.h"
#include "moses/FF/PhraseLengthFeature.h"
#include "moses/FF/DistortionScoreProducer.h"
#include "moses/FF/SparseHieroReorderingFeature.h"
#include "moses/FF/WordPenaltyProducer.h"
#include "moses/FF/InputFeature.h"
#include "moses/FF/PhrasePenalty.h"
#include "moses/FF/OSM-Feature/OpSequenceModel.h"
#include "moses/FF/ControlRecombination.h"
#include "moses/FF/ConstrainedDecoding.h"
#include "moses/FF/SoftSourceSyntacticConstraintsFeature.h"
#include "moses/FF/CoveredReferenceFeature.h"
#include "moses/FF/TreeStructureFeature.h"
#include "moses/FF/SoftMatchingFeature.h"
#include "moses/FF/DynamicCacheBasedLanguageModel.h"
#include "moses/FF/SourceGHKMTreeInputMatchFeature.h"
#include "moses/FF/HyperParameterAsWeight.h"
#include "moses/FF/SetSourcePhrase.h"
#include "moses/FF/PhraseOrientationFeature.h"
#include "moses/FF/UnalignedWordCountFeature.h"
#include "CountNonTerms.h"
#include "ReferenceComparison.h"
#include "RuleScope.h"
#include "MaxSpanFreeNonTermSource.h"
#include "NieceTerminal.h"
#include "SpanLength.h"
#include "SyntaxRHS.h"

#include "moses/FF/SkeletonStatelessFF.h"
#include "moses/FF/SkeletonStatefulFF.h"
#include "moses/LM/SkeletonLM.h"
#include "moses/FF/SkeletonTranslationOptionListFeature.h"
#include "moses/LM/BilingualLM.h"
#include "moses/TranslationModel/SkeletonPT.h"
#include "moses/Syntax/InputWeightFF.h"
#include "moses/Syntax/RuleTableFF.h"

#ifdef HAVE_VW
#include "moses/FF/VW/VW.h"
#include "moses/FF/VW/VWFeatureSourceBagOfWords.h"
#include "moses/FF/VW/VWFeatureSourceBigrams.h"
#include "moses/FF/VW/VWFeatureSourceIndicator.h"
#include "moses/FF/VW/VWFeatureSourcePhraseInternal.h"
#include "moses/FF/VW/VWFeatureSourceWindow.h"
#include "moses/FF/VW/VWFeatureTargetBigrams.h"
#include "moses/FF/VW/VWFeatureTargetIndicator.h"
#include "moses/FF/VW/VWFeatureSourceExternalFeatures.h"
#include "moses/FF/VW/VWFeatureTargetPhraseInternal.h"
#include "moses/FF/VW/VWFeatureTargetPhraseScores.h"
#endif

#ifdef HAVE_CMPH
#include "moses/TranslationModel/CompactPT/PhraseDictionaryCompact.h"
#endif
#ifdef PT_UG
#include "moses/TranslationModel/UG/mmsapt.h"
#endif
#ifdef HAVE_PROBINGPT
#include "moses/TranslationModel/ProbingPT/ProbingPT.h"
#endif

#include "moses/LM/Ken.h"
#ifdef LM_IRST
#include "moses/LM/IRST.h"
#endif

#ifdef LM_SRI
#include "moses/LM/SRI.h"
#endif

#ifdef LM_MAXENT_SRI
#include "moses/LM/MaxEntSRI.h"
#endif

#ifdef LM_RAND
#include "moses/LM/Rand.h"
#endif

#ifdef HAVE_SYNLM
#include "moses/SyntacticLanguageModel.h"
#endif

#ifdef LM_NEURAL
#include "moses/LM/NeuralLMWrapper.h"
#include "moses/LM/RDLM.h"
#include "moses/LM/bilingual-lm/BiLM_NPLM.h"
#endif

#ifdef LM_DALM
#include "moses/LM/DALMWrapper.h"
#endif

#ifdef LM_OXLM
#include "moses/LM/oxlm/OxLM.h"
#include "moses/LM/oxlm/SourceOxLM.h"
#endif

#include "util/exception.hh"

#include <vector>

namespace Moses
{

class FeatureFactory
{
public:
  virtual ~FeatureFactory() {}

  virtual void Create(const std::string &line) = 0;

protected:
  template <class F> static void DefaultSetup(F *feature);

  FeatureFactory() {}
};

template <class F>
void
FeatureFactory
::DefaultSetup(F *feature)
{
  StaticData &static_data = StaticData::InstanceNonConst();
  const std::string &featureName = feature->GetScoreProducerDescription();
  std::vector<float> weights = static_data.GetParameter()->GetWeights(featureName);

  if (feature->GetNumScoreComponents()) {
    if (weights.size() == 0) {
      weights = feature->DefaultWeights();
      if (weights.size() == 0) {
        TRACE_ERR("WARNING: No weights specified in config file for FF "
                  << featureName << ". This FF does not supply default values.\n"
                  << "WARNING: Auto-initializing all weights for this FF to 1.0");
        weights.assign(feature->GetNumScoreComponents(),1.0);
      } else {
        VERBOSE(2,"WARNING: No weights specified in config file for FF "
                << featureName << ". Using default values supplied by FF.");
      }
    }
    UTIL_THROW_IF2(weights.size() != feature->GetNumScoreComponents(),
                   "FATAL ERROR: Mismatch in number of features and number "
                   << "of weights for Feature Function " << featureName
                   << " (features: " << feature->GetNumScoreComponents()
                   << " vs. weights: " << weights.size() << ")");
    static_data.SetWeights(feature, weights);
  } else if (feature->IsTuneable())
    static_data.SetWeights(feature, weights);
}

namespace
{

template <class F>
class DefaultFeatureFactory : public FeatureFactory
{
public:
  void Create(const std::string &line) {
    DefaultSetup(new F(line));
  }
};

class KenFactory : public FeatureFactory
{
public:
  void Create(const std::string &line) {
    DefaultSetup(ConstructKenLM(line));
  }
};

} // namespace

FeatureRegistry::FeatureRegistry()
{
// Feature with same name as class
#define MOSES_FNAME(name) Add(#name, new DefaultFeatureFactory< name >());
// Feature with different name than class.
#define MOSES_FNAME2(name, type) Add(name, new DefaultFeatureFactory< type >());

  MOSES_FNAME2("PhraseDictionaryBinary", PhraseDictionaryTreeAdaptor);
  MOSES_FNAME(PhraseDictionaryOnDisk);
  MOSES_FNAME(PhraseDictionaryMemory);
  MOSES_FNAME(PhraseDictionaryScope3);
  MOSES_FNAME(PhraseDictionaryMultiModel);
  MOSES_FNAME(PhraseDictionaryMultiModelCounts);
  MOSES_FNAME(PhraseDictionaryALSuffixArray);
  //  MOSES_FNAME(PhraseDictionaryDynSuffixArray);
  MOSES_FNAME(PhraseDictionaryTransliteration);
  MOSES_FNAME(PhraseDictionaryDynamicCacheBased);
  MOSES_FNAME(PhraseDictionaryFuzzyMatch);
  MOSES_FNAME2("RuleTable", Syntax::RuleTableFF);
  MOSES_FNAME2("SyntaxInputWeight", Syntax::InputWeightFF);

  MOSES_FNAME(GlobalLexicalModel);
  //MOSES_FNAME(GlobalLexicalModelUnlimited); This was commented out in the original
  MOSES_FNAME(Model1Feature);
  MOSES_FNAME(SourceWordDeletionFeature);
  MOSES_FNAME(TargetWordInsertionFeature);
  MOSES_FNAME(PhraseBoundaryFeature);
  MOSES_FNAME(PhraseLengthFeature);
  MOSES_FNAME(WordTranslationFeature);
  MOSES_FNAME(TargetBigramFeature);
  MOSES_FNAME(TargetNgramFeature);
  MOSES_FNAME(PhrasePairFeature);
  MOSES_FNAME(RulePairUnlexicalizedSource);
  MOSES_FNAME(LexicalReordering);
  MOSES_FNAME2("Generation", GenerationDictionary);
  MOSES_FNAME(BleuScoreFeature);
  MOSES_FNAME2("Distortion", DistortionScoreProducer);
  MOSES_FNAME2("WordPenalty", WordPenaltyProducer);
  MOSES_FNAME(InputFeature);
  MOSES_FNAME(OpSequenceModel);
  MOSES_FNAME(PhrasePenalty);
  MOSES_FNAME2("UnknownWordPenalty", UnknownWordPenaltyProducer);
  MOSES_FNAME(ControlRecombination);
  MOSES_FNAME(ConstrainedDecoding);
  MOSES_FNAME(CoveredReferenceFeature);
  MOSES_FNAME(SourceGHKMTreeInputMatchFeature);
  MOSES_FNAME(SoftSourceSyntacticConstraintsFeature);
  MOSES_FNAME(TreeStructureFeature);
  MOSES_FNAME(SoftMatchingFeature);
  MOSES_FNAME(DynamicCacheBasedLanguageModel);
  MOSES_FNAME(HyperParameterAsWeight);
  MOSES_FNAME(SetSourcePhrase);
  MOSES_FNAME(CountNonTerms);
  MOSES_FNAME(ReferenceComparison);
  MOSES_FNAME(RuleScope);
  MOSES_FNAME(MaxSpanFreeNonTermSource);
  MOSES_FNAME(NieceTerminal);
  MOSES_FNAME(SparseHieroReorderingFeature);
  MOSES_FNAME(SpanLength);
  MOSES_FNAME(SyntaxRHS);
  MOSES_FNAME(PhraseOrientationFeature);
  MOSES_FNAME(UnalignedWordCountFeature);

  MOSES_FNAME(SkeletonStatelessFF);
  MOSES_FNAME(SkeletonStatefulFF);
  MOSES_FNAME(SkeletonLM);
  MOSES_FNAME(SkeletonTranslationOptionListFeature);
  MOSES_FNAME(SkeletonPT);

#ifdef HAVE_VW
  MOSES_FNAME(VW);
  MOSES_FNAME(VWFeatureSourceBagOfWords);
  MOSES_FNAME(VWFeatureSourceBigrams);
  MOSES_FNAME(VWFeatureSourceIndicator);
  MOSES_FNAME(VWFeatureSourcePhraseInternal);
  MOSES_FNAME(VWFeatureSourceWindow);
  MOSES_FNAME(VWFeatureTargetBigrams);
  MOSES_FNAME(VWFeatureTargetPhraseInternal);
  MOSES_FNAME(VWFeatureTargetIndicator);
  MOSES_FNAME(VWFeatureSourceExternalFeatures);
  MOSES_FNAME(VWFeatureTargetPhraseScores);
#endif

#ifdef HAVE_CMPH
  MOSES_FNAME(PhraseDictionaryCompact);
#endif
#ifdef PT_UG
  MOSES_FNAME(Mmsapt);
  MOSES_FNAME2("PhraseDictionaryBitextSampling",Mmsapt); // that's an alias for Mmsapt!
#endif
#ifdef HAVE_PROBINGPT
  MOSES_FNAME(ProbingPT);
#endif

#ifdef HAVE_SYNLM
  MOSES_FNAME(SyntacticLanguageModel);
#endif
#ifdef LM_IRST
  MOSES_FNAME2("IRSTLM", LanguageModelIRST);
#endif
#ifdef LM_SRI
  MOSES_FNAME2("SRILM", LanguageModelSRI);
#endif
#ifdef LM_MAXENT_SRI
  MOSES_FNAME2("MaxEntLM", LanguageModelMaxEntSRI);
#endif
#ifdef LM_RAND
  MOSES_FNAME2("RANDLM", LanguageModelRandLM);
#endif
#ifdef LM_NEURAL
  MOSES_FNAME2("NeuralLM", NeuralLMWrapper);
  MOSES_FNAME(RDLM);
  MOSES_FNAME2("BilingualNPLM", BilingualLM_NPLM);
#endif
#ifdef LM_DALM
  MOSES_FNAME2("DALM", LanguageModelDALM);
#endif
#ifdef LM_OXLM
  MOSES_FNAME2("OxLM", OxLM<oxlm::LM>);
  MOSES_FNAME2("OxFactoredLM", OxLM<oxlm::FactoredLM>);
  MOSES_FNAME2("OxFactoredMaxentLM", OxLM<oxlm::FactoredMaxentLM>);
  MOSES_FNAME2("OxSourceFactoredLM", SourceOxLM);
  MOSES_FNAME2("OxTreeLM", OxLM<oxlm::FactoredTreeLM>);
#endif

  Add("KENLM", new KenFactory());
}

FeatureRegistry::~FeatureRegistry()
{
}

void FeatureRegistry::Add(const std::string &name, FeatureFactory *factory)
{
  std::pair<std::string, boost::shared_ptr<FeatureFactory> > to_ins(name, boost::shared_ptr<FeatureFactory>(factory));
  UTIL_THROW_IF2(!registry_.insert(to_ins).second, "Duplicate feature name " << name);
}

namespace
{
class UnknownFeatureException : public util::Exception {};
}

void FeatureRegistry::Construct(const std::string &name, const std::string &line)
{
  Map::iterator i = registry_.find(name);
  UTIL_THROW_IF(i == registry_.end(), UnknownFeatureException, "Feature name " << name << " is not registered.");
  i->second->Create(line);
}

void FeatureRegistry::PrintFF() const
{
  std::vector<std::string> ffs;
  std::cerr << "Available feature functions:" << std::endl;
  Map::const_iterator iter;
  for (iter = registry_.begin(); iter != registry_.end(); ++iter) {
    const std::string &ffName = iter->first;
    ffs.push_back(ffName);
  }

  std::vector<std::string>::const_iterator iterVec;
  std::sort(ffs.begin(), ffs.end());
  for (iterVec = ffs.begin(); iterVec != ffs.end(); ++iterVec) {
    const std::string &ffName = *iterVec;
    std::cerr << ffName << " ";
  }

  std::cerr << std::endl;
}

} // namespace Moses
<commit_msg>registered coarsebilm in factory<commit_after>#include "util/exception.hh"
#include "moses/FF/Factory.h"
#include "moses/StaticData.h"

#include "moses/TranslationModel/PhraseDictionaryTreeAdaptor.h"
#include "moses/TranslationModel/PhraseDictionaryMemory.h"
#include "moses/TranslationModel/PhraseDictionaryMultiModel.h"
#include "moses/TranslationModel/PhraseDictionaryMultiModelCounts.h"
#include "moses/TranslationModel/PhraseDictionaryScope3.h"
#include "moses/TranslationModel/PhraseDictionaryTransliteration.h"
#include "moses/TranslationModel/PhraseDictionaryDynamicCacheBased.h"

#include "moses/TranslationModel/RuleTable/PhraseDictionaryOnDisk.h"
#include "moses/TranslationModel/RuleTable/PhraseDictionaryFuzzyMatch.h"
#include "moses/TranslationModel/RuleTable/PhraseDictionaryALSuffixArray.h"

#include "moses/FF/LexicalReordering/LexicalReordering.h"

#include "moses/FF/BleuScoreFeature.h"
#include "moses/FF/CoarseBiLM.h"
#include "moses/FF/TargetWordInsertionFeature.h"
#include "moses/FF/SourceWordDeletionFeature.h"
#include "moses/FF/GlobalLexicalModel.h"
#include "moses/FF/GlobalLexicalModelUnlimited.h"
#include "moses/FF/Model1Feature.h"
#include "moses/FF/UnknownWordPenaltyProducer.h"
#include "moses/FF/WordTranslationFeature.h"
#include "moses/FF/TargetBigramFeature.h"
#include "moses/FF/TargetNgramFeature.h"
#include "moses/FF/PhraseBoundaryFeature.h"
#include "moses/FF/PhrasePairFeature.h"
#include "moses/FF/RulePairUnlexicalizedSource.h"
#include "moses/FF/PhraseLengthFeature.h"
#include "moses/FF/DistortionScoreProducer.h"
#include "moses/FF/SparseHieroReorderingFeature.h"
#include "moses/FF/WordPenaltyProducer.h"
#include "moses/FF/InputFeature.h"
#include "moses/FF/PhrasePenalty.h"
#include "moses/FF/OSM-Feature/OpSequenceModel.h"
#include "moses/FF/ControlRecombination.h"
#include "moses/FF/ConstrainedDecoding.h"
#include "moses/FF/SoftSourceSyntacticConstraintsFeature.h"
#include "moses/FF/CoveredReferenceFeature.h"
#include "moses/FF/TreeStructureFeature.h"
#include "moses/FF/SoftMatchingFeature.h"
#include "moses/FF/DynamicCacheBasedLanguageModel.h"
#include "moses/FF/SourceGHKMTreeInputMatchFeature.h"
#include "moses/FF/HyperParameterAsWeight.h"
#include "moses/FF/SetSourcePhrase.h"
#include "moses/FF/PhraseOrientationFeature.h"
#include "moses/FF/UnalignedWordCountFeature.h"
#include "CountNonTerms.h"
#include "ReferenceComparison.h"
#include "RuleScope.h"
#include "MaxSpanFreeNonTermSource.h"
#include "NieceTerminal.h"
#include "SpanLength.h"
#include "SyntaxRHS.h"

#include "moses/FF/SkeletonStatelessFF.h"
#include "moses/FF/SkeletonStatefulFF.h"
#include "moses/LM/SkeletonLM.h"
#include "moses/FF/SkeletonTranslationOptionListFeature.h"
#include "moses/LM/BilingualLM.h"
#include "moses/TranslationModel/SkeletonPT.h"
#include "moses/Syntax/InputWeightFF.h"
#include "moses/Syntax/RuleTableFF.h"

#ifdef HAVE_VW
#include "moses/FF/VW/VW.h"
#include "moses/FF/VW/VWFeatureSourceBagOfWords.h"
#include "moses/FF/VW/VWFeatureSourceBigrams.h"
#include "moses/FF/VW/VWFeatureSourceIndicator.h"
#include "moses/FF/VW/VWFeatureSourcePhraseInternal.h"
#include "moses/FF/VW/VWFeatureSourceWindow.h"
#include "moses/FF/VW/VWFeatureTargetBigrams.h"
#include "moses/FF/VW/VWFeatureTargetIndicator.h"
#include "moses/FF/VW/VWFeatureSourceExternalFeatures.h"
#include "moses/FF/VW/VWFeatureTargetPhraseInternal.h"
#include "moses/FF/VW/VWFeatureTargetPhraseScores.h"
#endif

#ifdef HAVE_CMPH
#include "moses/TranslationModel/CompactPT/PhraseDictionaryCompact.h"
#endif
#ifdef PT_UG
#include "moses/TranslationModel/UG/mmsapt.h"
#endif
#ifdef HAVE_PROBINGPT
#include "moses/TranslationModel/ProbingPT/ProbingPT.h"
#endif

#include "moses/LM/Ken.h"
#ifdef LM_IRST
#include "moses/LM/IRST.h"
#endif

#ifdef LM_SRI
#include "moses/LM/SRI.h"
#endif

#ifdef LM_MAXENT_SRI
#include "moses/LM/MaxEntSRI.h"
#endif

#ifdef LM_RAND
#include "moses/LM/Rand.h"
#endif

#ifdef HAVE_SYNLM
#include "moses/SyntacticLanguageModel.h"
#endif

#ifdef LM_NEURAL
#include "moses/LM/NeuralLMWrapper.h"
#include "moses/LM/RDLM.h"
#include "moses/LM/bilingual-lm/BiLM_NPLM.h"
#endif

#ifdef LM_DALM
#include "moses/LM/DALMWrapper.h"
#endif

#ifdef LM_OXLM
#include "moses/LM/oxlm/OxLM.h"
#include "moses/LM/oxlm/SourceOxLM.h"
#endif

#include "util/exception.hh"

#include <vector>

namespace Moses
{

class FeatureFactory
{
public:
  virtual ~FeatureFactory() {}

  virtual void Create(const std::string &line) = 0;

protected:
  template <class F> static void DefaultSetup(F *feature);

  FeatureFactory() {}
};

template <class F>
void
FeatureFactory
::DefaultSetup(F *feature)
{
  StaticData &static_data = StaticData::InstanceNonConst();
  const std::string &featureName = feature->GetScoreProducerDescription();
  std::vector<float> weights = static_data.GetParameter()->GetWeights(featureName);

  if (feature->GetNumScoreComponents()) {
    if (weights.size() == 0) {
      weights = feature->DefaultWeights();
      if (weights.size() == 0) {
        TRACE_ERR("WARNING: No weights specified in config file for FF "
                  << featureName << ". This FF does not supply default values.\n"
                  << "WARNING: Auto-initializing all weights for this FF to 1.0");
        weights.assign(feature->GetNumScoreComponents(),1.0);
      } else {
        VERBOSE(2,"WARNING: No weights specified in config file for FF "
                << featureName << ". Using default values supplied by FF.");
      }
    }
    UTIL_THROW_IF2(weights.size() != feature->GetNumScoreComponents(),
                   "FATAL ERROR: Mismatch in number of features and number "
                   << "of weights for Feature Function " << featureName
                   << " (features: " << feature->GetNumScoreComponents()
                   << " vs. weights: " << weights.size() << ")");
    static_data.SetWeights(feature, weights);
  } else if (feature->IsTuneable())
    static_data.SetWeights(feature, weights);
}

namespace
{

template <class F>
class DefaultFeatureFactory : public FeatureFactory
{
public:
  void Create(const std::string &line) {
    DefaultSetup(new F(line));
  }
};

class KenFactory : public FeatureFactory
{
public:
  void Create(const std::string &line) {
    DefaultSetup(ConstructKenLM(line));
  }
};

} // namespace

FeatureRegistry::FeatureRegistry()
{
// Feature with same name as class
#define MOSES_FNAME(name) Add(#name, new DefaultFeatureFactory< name >());
// Feature with different name than class.
#define MOSES_FNAME2(name, type) Add(name, new DefaultFeatureFactory< type >());

  MOSES_FNAME2("PhraseDictionaryBinary", PhraseDictionaryTreeAdaptor);
  MOSES_FNAME(PhraseDictionaryOnDisk);
  MOSES_FNAME(PhraseDictionaryMemory);
  MOSES_FNAME(PhraseDictionaryScope3);
  MOSES_FNAME(PhraseDictionaryMultiModel);
  MOSES_FNAME(PhraseDictionaryMultiModelCounts);
  MOSES_FNAME(PhraseDictionaryALSuffixArray);
  //  MOSES_FNAME(PhraseDictionaryDynSuffixArray);
  MOSES_FNAME(PhraseDictionaryTransliteration);
  MOSES_FNAME(PhraseDictionaryDynamicCacheBased);
  MOSES_FNAME(PhraseDictionaryFuzzyMatch);
  MOSES_FNAME2("RuleTable", Syntax::RuleTableFF);
  MOSES_FNAME2("SyntaxInputWeight", Syntax::InputWeightFF);

  MOSES_FNAME(GlobalLexicalModel);
  //MOSES_FNAME(GlobalLexicalModelUnlimited); This was commented out in the original
  MOSES_FNAME(Model1Feature);
  MOSES_FNAME(SourceWordDeletionFeature);
  MOSES_FNAME(TargetWordInsertionFeature);
  MOSES_FNAME(PhraseBoundaryFeature);
  MOSES_FNAME(PhraseLengthFeature);
  MOSES_FNAME(WordTranslationFeature);
  MOSES_FNAME(TargetBigramFeature);
  MOSES_FNAME(TargetNgramFeature);
  MOSES_FNAME(PhrasePairFeature);
  MOSES_FNAME(RulePairUnlexicalizedSource);
  MOSES_FNAME(LexicalReordering);
  MOSES_FNAME2("Generation", GenerationDictionary);
  MOSES_FNAME(BleuScoreFeature);
  MOSES_FNAME2("Distortion", DistortionScoreProducer);
  MOSES_FNAME2("WordPenalty", WordPenaltyProducer);
  MOSES_FNAME(InputFeature);
  MOSES_FNAME(OpSequenceModel);
  MOSES_FNAME(PhrasePenalty);
  MOSES_FNAME2("UnknownWordPenalty", UnknownWordPenaltyProducer);
  MOSES_FNAME(ControlRecombination);
  MOSES_FNAME(ConstrainedDecoding);
  MOSES_FNAME(CoveredReferenceFeature);
  MOSES_FNAME(SourceGHKMTreeInputMatchFeature);
  MOSES_FNAME(SoftSourceSyntacticConstraintsFeature);
  MOSES_FNAME(TreeStructureFeature);
  MOSES_FNAME(SoftMatchingFeature);
  MOSES_FNAME(DynamicCacheBasedLanguageModel);
  MOSES_FNAME(HyperParameterAsWeight);
  MOSES_FNAME(SetSourcePhrase);
  MOSES_FNAME(CountNonTerms);
  MOSES_FNAME(ReferenceComparison);
  MOSES_FNAME(RuleScope);
  MOSES_FNAME(MaxSpanFreeNonTermSource);
  MOSES_FNAME(NieceTerminal);
  MOSES_FNAME(SparseHieroReorderingFeature);
  MOSES_FNAME(SpanLength);
  MOSES_FNAME(SyntaxRHS);
  MOSES_FNAME(PhraseOrientationFeature);
  MOSES_FNAME(UnalignedWordCountFeature);
  MOSES_FNAME(CoarseBiLM);

  MOSES_FNAME(SkeletonStatelessFF);
  MOSES_FNAME(SkeletonStatefulFF);
  MOSES_FNAME(SkeletonLM);
  MOSES_FNAME(SkeletonTranslationOptionListFeature);
  MOSES_FNAME(SkeletonPT);

#ifdef HAVE_VW
  MOSES_FNAME(VW);
  MOSES_FNAME(VWFeatureSourceBagOfWords);
  MOSES_FNAME(VWFeatureSourceBigrams);
  MOSES_FNAME(VWFeatureSourceIndicator);
  MOSES_FNAME(VWFeatureSourcePhraseInternal);
  MOSES_FNAME(VWFeatureSourceWindow);
  MOSES_FNAME(VWFeatureTargetBigrams);
  MOSES_FNAME(VWFeatureTargetPhraseInternal);
  MOSES_FNAME(VWFeatureTargetIndicator);
  MOSES_FNAME(VWFeatureSourceExternalFeatures);
  MOSES_FNAME(VWFeatureTargetPhraseScores);
#endif

#ifdef HAVE_CMPH
  MOSES_FNAME(PhraseDictionaryCompact);
#endif
#ifdef PT_UG
  MOSES_FNAME(Mmsapt);
  MOSES_FNAME2("PhraseDictionaryBitextSampling",Mmsapt); // that's an alias for Mmsapt!
#endif
#ifdef HAVE_PROBINGPT
  MOSES_FNAME(ProbingPT);
#endif

#ifdef HAVE_SYNLM
  MOSES_FNAME(SyntacticLanguageModel);
#endif
#ifdef LM_IRST
  MOSES_FNAME2("IRSTLM", LanguageModelIRST);
#endif
#ifdef LM_SRI
  MOSES_FNAME2("SRILM", LanguageModelSRI);
#endif
#ifdef LM_MAXENT_SRI
  MOSES_FNAME2("MaxEntLM", LanguageModelMaxEntSRI);
#endif
#ifdef LM_RAND
  MOSES_FNAME2("RANDLM", LanguageModelRandLM);
#endif
#ifdef LM_NEURAL
  MOSES_FNAME2("NeuralLM", NeuralLMWrapper);
  MOSES_FNAME(RDLM);
  MOSES_FNAME2("BilingualNPLM", BilingualLM_NPLM);
#endif
#ifdef LM_DALM
  MOSES_FNAME2("DALM", LanguageModelDALM);
#endif
#ifdef LM_OXLM
  MOSES_FNAME2("OxLM", OxLM<oxlm::LM>);
  MOSES_FNAME2("OxFactoredLM", OxLM<oxlm::FactoredLM>);
  MOSES_FNAME2("OxFactoredMaxentLM", OxLM<oxlm::FactoredMaxentLM>);
  MOSES_FNAME2("OxSourceFactoredLM", SourceOxLM);
  MOSES_FNAME2("OxTreeLM", OxLM<oxlm::FactoredTreeLM>);
#endif

  Add("KENLM", new KenFactory());
}

FeatureRegistry::~FeatureRegistry()
{
}

void FeatureRegistry::Add(const std::string &name, FeatureFactory *factory)
{
  std::pair<std::string, boost::shared_ptr<FeatureFactory> > to_ins(name, boost::shared_ptr<FeatureFactory>(factory));
  UTIL_THROW_IF2(!registry_.insert(to_ins).second, "Duplicate feature name " << name);
}

namespace
{
class UnknownFeatureException : public util::Exception {};
}

void FeatureRegistry::Construct(const std::string &name, const std::string &line)
{
  Map::iterator i = registry_.find(name);
  UTIL_THROW_IF(i == registry_.end(), UnknownFeatureException, "Feature name " << name << " is not registered.");
  i->second->Create(line);
}

void FeatureRegistry::PrintFF() const
{
  std::vector<std::string> ffs;
  std::cerr << "Available feature functions:" << std::endl;
  Map::const_iterator iter;
  for (iter = registry_.begin(); iter != registry_.end(); ++iter) {
    const std::string &ffName = iter->first;
    ffs.push_back(ffName);
  }

  std::vector<std::string>::const_iterator iterVec;
  std::sort(ffs.begin(), ffs.end());
  for (iterVec = ffs.begin(); iterVec != ffs.end(); ++iterVec) {
    const std::string &ffName = *iterVec;
    std::cerr << ffName << " ";
  }

  std::cerr << std::endl;
}

} // namespace Moses
<|endoftext|>


<commit_before>/*
Copyright (c) 2016 Ingo Wald

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

// ospray pixel
#include "ospray/fb/PixelOp.h"
#include "ospray/fb/FrameBuffer.h"
#include "ospray/mpi/MPICommon.h"
// displaywald client
#include "../client/Client.h"

namespace ospray {
  namespace dw {

    void foo()
    {
    }

    struct DisplayWaldPixelOp : public ospray::PixelOp
    {
      struct Instance : public ospray::PixelOp::Instance
      {
        Instance(FrameBuffer *fb,
                 PixelOp::Instance *prev,
                 dw::Client *client)
          : client(client)
        {
          fb->pixelOp = this;
        }

        // /*! gets called every time the frame buffer got 'commit'ted */
        // virtual void  commitNotify() {}
        // /*! gets called once at the end of the frame */
        virtual void endFrame()
        { client->endFrame(); }

        virtual int clampColorComponent(float c)
        {
            int r = 255*c;
            if (r < 0) r = 0;
            if (r > 255) r = 255;
        }

        virtual float simpleGammaCorrection(float c, float gamma)
        {
            return exp(c, 1.0f/gamma);
        }

        virtual unsigned int packColor(float r, float g, float b, float a)
        {
            return (a<<32) | (b<<24) | (g<<16) | (r<<8);
        }

        /*! called right after the tile got accumulated; i.e., the
          tile's RGBA values already contain the accu-buffer blended
          values (assuming an accubuffer exists), and this function
          defines how these pixels are being processed before written
          into the color buffer */
        virtual void postAccum(Tile &tile)
        {
          PlainTile plainTile(vec2i(TILE_SIZE));
          plainTile.pitch = TILE_SIZE;
          for (int i=0;i<TILE_SIZE*TILE_SIZE;i++) {
            //int r = std::min(255,int(255.f*tile.r[i]));
            //int g = std::min(255,int(255.f*tile.g[i]));
            //int b = std::min(255,int(255.f*tile.b[i]));

            float gamma = 1.8;
            int r = clampColorComponent(simpleGammaCorrection(tile.r[i], gamma);
            int g = clampColorComponent(simpleGammaCorrection(tile.g[i], gamma);
            int b = clampColorComponent(simpleGammaCorrection(tile.b[i], gamma);

            int rgba = (b<<24)|(g<<16)|(r<<8);
            plainTile.pixel[i] = rgba;
          }
          plainTile.region = tile.region;
          bool stereo = client->getWallConfig()->doStereo();
          if (!stereo) {
            plainTile.eye = 0;
            client->writeTile(plainTile);
          } else {
            int trueScreenWidth = client->getWallConfig()->totalPixels().x;
            if (plainTile.region.upper.x <= trueScreenWidth) {
              // all on left eye
              plainTile.eye = 0;
              client->writeTile(plainTile);
            } else if (plainTile.region.lower.x >= trueScreenWidth) {
              // all on right eye - just shift coordinates
              plainTile.region.lower.x -= trueScreenWidth;
              plainTile.region.upper.x -= trueScreenWidth;
              plainTile.eye = 1;
              client->writeTile(plainTile);
            } else {
              // overlaps both sides - split it up
              const int original_lower_x = plainTile.region.lower.x;
              const int original_upper_x = plainTile.region.upper.x;
              // first, 'clip' the tile and write 'clipped' one to the left side
              plainTile.region.lower.x = original_lower_x - trueScreenWidth;
              plainTile.region.upper.x = trueScreenWidth;
              plainTile.eye = 0;
              client->writeTile(plainTile);

              // now, move right true to the left, clip on lower side, and shift pixels
              plainTile.region.lower.x = 0;
              plainTile.region.upper.x = original_upper_x - trueScreenWidth;
              // since pixels didn't start at 'trueWidth' but at 'lower.x', we have to shift
              int numPixelsInRegion = plainTile.region.size().y*plainTile.pitch;
              int shift = trueScreenWidth - original_lower_x;
              plainTile.eye = 1;
              for (int i=0;i<numPixelsInRegion;i++)
                plainTile.pixel[i] = plainTile.pixel[i+shift];
              client->writeTile(plainTile);
            }

          }
        }

        //! \brief common function to help printf-debugging
        /*! Every derived class should overrride this! */
        virtual std::string toString() const;

        dw::Client *client;
      };

      //! \brief common function to help printf-debugging
      /*! Every derived class should overrride this! */
      virtual std::string toString() const;

      /*! \brief commit the object's outstanding changes (such as changed
       *         parameters etc) */
      virtual void commit()
      {
        std::string streamName = getParamString("streamName","");
        std::cout << "#osp:dw: trying to establish connection to display wall service at MPI port " << streamName << std::endl;
        client = new dw::Client(mpi::worker.comm,streamName);
      }

      //! \brief create an instance of this pixel op
      virtual ospray::PixelOp::Instance *createInstance(FrameBuffer *fb,
                                                        PixelOp::Instance *prev)
      {
        return new Instance(fb,prev,client);
      }

      dw::Client *client;
    };

    //! \brief common function to help printf-debugging
    std::string DisplayWaldPixelOp::toString() const
    { return "ospray::dw::DisplayWaldPixelOp (displayWald module)"; }

    //! \brief common function to help printf-debugging
    std::string DisplayWaldPixelOp::Instance::toString() const
    { return "ospray::dw::DisplayWaldPixelOp::Instance (displayWald module)"; }

    extern "C" void ospray_init_module_displayWald()
    {
      printf("loading the 'displayWald' module...\n");
    }

    OSP_REGISTER_PIXEL_OP(DisplayWaldPixelOp,display_wald);

  } // ::ospray::dw
} // ::ospray
<commit_msg>update missing )<commit_after>/*
Copyright (c) 2016 Ingo Wald

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

// ospray pixel
#include "ospray/fb/PixelOp.h"
#include "ospray/fb/FrameBuffer.h"
#include "ospray/mpi/MPICommon.h"
// displaywald client
#include "../client/Client.h"

namespace ospray {
  namespace dw {

    void foo()
    {
    }

    struct DisplayWaldPixelOp : public ospray::PixelOp
    {
      struct Instance : public ospray::PixelOp::Instance
      {
        Instance(FrameBuffer *fb,
                 PixelOp::Instance *prev,
                 dw::Client *client)
          : client(client)
        {
          fb->pixelOp = this;
        }

        // /*! gets called every time the frame buffer got 'commit'ted */
        // virtual void  commitNotify() {}
        // /*! gets called once at the end of the frame */
        virtual void endFrame()
        { client->endFrame(); }

        virtual int clampColorComponent(float c)
        {
            int r = 255*c;
            if (r < 0) r = 0;
            if (r > 255) r = 255;
        }

        virtual float simpleGammaCorrection(float c, float gamma)
        {
            return exp(c, 1.0f/gamma);
        }

        virtual unsigned int packColor(float r, float g, float b, float a)
        {
            return (a<<32) | (b<<24) | (g<<16) | (r<<8);
        }

        /*! called right after the tile got accumulated; i.e., the
          tile's RGBA values already contain the accu-buffer blended
          values (assuming an accubuffer exists), and this function
          defines how these pixels are being processed before written
          into the color buffer */
        virtual void postAccum(Tile &tile)
        {
          PlainTile plainTile(vec2i(TILE_SIZE));
          plainTile.pitch = TILE_SIZE;
          for (int i=0;i<TILE_SIZE*TILE_SIZE;i++) {
            //int r = std::min(255,int(255.f*tile.r[i]));
            //int g = std::min(255,int(255.f*tile.g[i]));
            //int b = std::min(255,int(255.f*tile.b[i]));

            float gamma = 1.8;
            int r = clampColorComponent(simpleGammaCorrection(tile.r[i], gamma));
            int g = clampColorComponent(simpleGammaCorrection(tile.g[i], gamma));
            int b = clampColorComponent(simpleGammaCorrection(tile.b[i], gamma));

            int rgba = (b<<24)|(g<<16)|(r<<8);
            plainTile.pixel[i] = rgba;
          }
          plainTile.region = tile.region;
          bool stereo = client->getWallConfig()->doStereo();
          if (!stereo) {
            plainTile.eye = 0;
            client->writeTile(plainTile);
          } else {
            int trueScreenWidth = client->getWallConfig()->totalPixels().x;
            if (plainTile.region.upper.x <= trueScreenWidth) {
              // all on left eye
              plainTile.eye = 0;
              client->writeTile(plainTile);
            } else if (plainTile.region.lower.x >= trueScreenWidth) {
              // all on right eye - just shift coordinates
              plainTile.region.lower.x -= trueScreenWidth;
              plainTile.region.upper.x -= trueScreenWidth;
              plainTile.eye = 1;
              client->writeTile(plainTile);
            } else {
              // overlaps both sides - split it up
              const int original_lower_x = plainTile.region.lower.x;
              const int original_upper_x = plainTile.region.upper.x;
              // first, 'clip' the tile and write 'clipped' one to the left side
              plainTile.region.lower.x = original_lower_x - trueScreenWidth;
              plainTile.region.upper.x = trueScreenWidth;
              plainTile.eye = 0;
              client->writeTile(plainTile);

              // now, move right true to the left, clip on lower side, and shift pixels
              plainTile.region.lower.x = 0;
              plainTile.region.upper.x = original_upper_x - trueScreenWidth;
              // since pixels didn't start at 'trueWidth' but at 'lower.x', we have to shift
              int numPixelsInRegion = plainTile.region.size().y*plainTile.pitch;
              int shift = trueScreenWidth - original_lower_x;
              plainTile.eye = 1;
              for (int i=0;i<numPixelsInRegion;i++)
                plainTile.pixel[i] = plainTile.pixel[i+shift];
              client->writeTile(plainTile);
            }

          }
        }

        //! \brief common function to help printf-debugging
        /*! Every derived class should overrride this! */
        virtual std::string toString() const;

        dw::Client *client;
      };

      //! \brief common function to help printf-debugging
      /*! Every derived class should overrride this! */
      virtual std::string toString() const;

      /*! \brief commit the object's outstanding changes (such as changed
       *         parameters etc) */
      virtual void commit()
      {
        std::string streamName = getParamString("streamName","");
        std::cout << "#osp:dw: trying to establish connection to display wall service at MPI port " << streamName << std::endl;
        client = new dw::Client(mpi::worker.comm,streamName);
      }

      //! \brief create an instance of this pixel op
      virtual ospray::PixelOp::Instance *createInstance(FrameBuffer *fb,
                                                        PixelOp::Instance *prev)
      {
        return new Instance(fb,prev,client);
      }

      dw::Client *client;
    };

    //! \brief common function to help printf-debugging
    std::string DisplayWaldPixelOp::toString() const
    { return "ospray::dw::DisplayWaldPixelOp (displayWald module)"; }

    //! \brief common function to help printf-debugging
    std::string DisplayWaldPixelOp::Instance::toString() const
    { return "ospray::dw::DisplayWaldPixelOp::Instance (displayWald module)"; }

    extern "C" void ospray_init_module_displayWald()
    {
      printf("loading the 'displayWald' module...\n");
    }

    OSP_REGISTER_PIXEL_OP(DisplayWaldPixelOp,display_wald);

  } // ::ospray::dw
} // ::ospray
<|endoftext|>


<commit_before>#include "AudioMonitorServer.hpp"

/*Constructor of AudioMonitorServer, create the server socket and initialize the data
 * structure*/

AudioMonitorServer::AudioMonitorServer(int prt,int dbg):
  debug(1),port(prt){

    /* socket factory*/
    if((servSockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == -1)
    {
      perror("socket");
      exit(EXIT_FAILURE);
    }

    /* init local addr structure and other params */
    my_addr.sin_family      = AF_INET;
    my_addr.sin_port        = htons(port);
    my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addrlen                 = sizeof(struct sockaddr_in);

    /* bind addr structure with socket */
    if(bind(servSockfd,(struct sockaddr*)&my_addr,addrlen) == -1)
    {
      perror("bind");
      close(servSockfd);
      exit(EXIT_FAILURE);
    }

    /*Set servSockfd to be non-blocking*/
    fcntl(servSockfd,F_SETFL,O_NONBLOCK);

    /* set the socket in passive mode (only used for accept())
     * and set the list size for pending connection*/
    listen(servSockfd,SOMAXCONN);

    max_select=servSockfd;

    list_client=new std::vector<EASEAClientData>;
  }

/**
 * /brief    Destructor of AudioMonitorServer
 **/
AudioMonitorServer::~AudioMonitorServer(){
  /*close every opened socket*/
  unsigned int i;

  for(i=0;i<list_client->size();i++){
    close(list_client->at(i).getSocket());
  }

}

void AudioMonitorServer::signalHandler(){
  /*Signal handler in case of ^C, to close the sockets*/
  //terminaison.sa_handler=sigIntEvent;
  sigfillset(&terminaison.sa_mask);
  terminaison.sa_flags=0;

  sigaction(SIGINT,&terminaison,NULL);
}

void AudioMonitorServer::sigIntEvent(int sig){
  unsigned int i;

  close(servSockfd);

  for(i=0;i<list_client->size();i++){
    //send(list_client[i].getSocket(),"000/END",8,0);
    close(list_client->at(i).getSocket());
  }

  exit(0);
}

void AudioMonitorServer::buildSocketList(){
  unsigned int i;

  FD_ZERO(&rdclient);
  FD_SET(servSockfd,&rdclient);

  for(i=0;i<list_client->size();i++){
    FD_SET(list_client->at(i).getSocket(),&rdclient);
  }

}

void AudioMonitorServer::newClient(){
  int tmp_sockfd;
  EASEAClientData* new_client;

  tmp_sockfd = accept(servSockfd,(struct sockaddr*)&my_addr,&addrlen);

  /*selected need to know the highest numerical socket value*/
  if(tmp_sockfd>max_select){
    max_select=tmp_sockfd;
  }

  if (debug) {
    std::cout<<"nouveaux client"<<std::endl;
  }

  /*Adding the newly connected client to the list of client*/
  new_client = new EASEAClientData(tmp_sockfd);
  new_client->setIP(inet_ntoa(my_addr.sin_addr));
  new_client->setPort(ntohs(my_addr.sin_port));
  list_client->push_back(*new_client);

}

void AudioMonitorServer::recvSomething(){
  if(FD_ISSET(servSockfd,&rdclient))
    newClient();
  else
    recvFromClient();

}

/* Case new data from known client*/
/* Check whose fd changed and received from them*/
void AudioMonitorServer::recvFromClient(){
  char buf[1024];
  float* dec=(float*)buf;
  unsigned int i;
  EASEAClientData* changedClient;
  memset(buf,'\0',1024); //reset buffer

  for(i=0;i<list_client->size();i++){
    if(list_client->at(i).getSocket()!=0){
      if(FD_ISSET(list_client->at(i).getSocket(),&rdclient)){

        changedClient=&list_client->at(i);

        if(recv(changedClient->getSocket(),buf,1024,0)==0){
          //client_disconnected=true;
        }//Envoi de packet vide => deconnecte/fini;
        else {
          if (!changedClient->toIgnore()) {
            changedClient->addData(dec[0],dec[1],dec[2],dec[3]);

            if (debug){
              std::cout<<"I have received something from "<<
              changedClient->getIP()<<":"<<changedClient->getPort()
              <<std::endl;
              std::cout<<dec[0]<<" "<<dec[1]<<" "<<dec[2]<<" "<<dec[3]<<std::endl;
            }

            compo->notify(changedClient);
          }
          else{
            list_client->at(i).setIgnoreFlag(false);
          }
        }

      }
    }
  }

}

/**
 * /brief    Start the server, which will never stop listening
 **/
void AudioMonitorServer::start(){

  debug=1;

  while(1){

    buildSocketList();

    if((select(max_select+1,&rdclient,NULL,NULL,NULL))>=1){
     recvSomething();
    }
  }
}

/**
* /brief    Add a Compositor
**/
void AudioMonitorServer::setCompositor(Compositor* compo){
  this->compo=compo;
}
<commit_msg>Now keep track of individuals migration<commit_after>#include "AudioMonitorServer.hpp"

/*Constructor of AudioMonitorServer, create the server socket and initialize the data
 * structure*/

AudioMonitorServer::AudioMonitorServer(int prt,int dbg):
  debug(1),port(prt){

    /* socket factory*/
    if((servSockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == -1)
    {
      perror("socket");
      exit(EXIT_FAILURE);
    }

    /* init local addr structure and other params */
    my_addr.sin_family      = AF_INET;
    my_addr.sin_port        = htons(port);
    my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addrlen                 = sizeof(struct sockaddr_in);

    /* bind addr structure with socket */
    if(bind(servSockfd,(struct sockaddr*)&my_addr,addrlen) == -1)
    {
      perror("bind");
      close(servSockfd);
      exit(EXIT_FAILURE);
    }

    /*Set servSockfd to be non-blocking*/
    fcntl(servSockfd,F_SETFL,O_NONBLOCK);

    /* set the socket in passive mode (only used for accept())
     * and set the list size for pending connection*/
    listen(servSockfd,SOMAXCONN);

    max_select=servSockfd;

    list_client=new std::vector<EASEAClientData>;
  }

/**
 * /brief    Destructor of AudioMonitorServer
 **/
AudioMonitorServer::~AudioMonitorServer(){
  /*close every opened socket*/
  unsigned int i;

  for(i=0;i<list_client->size();i++){
    close(list_client->at(i).getSocket());
  }

}

void AudioMonitorServer::signalHandler(){
  /*Signal handler in case of ^C, to close the sockets*/
  //terminaison.sa_handler=sigIntEvent;
  sigfillset(&terminaison.sa_mask);
  terminaison.sa_flags=0;

  sigaction(SIGINT,&terminaison,NULL);
}

void AudioMonitorServer::sigIntEvent(int sig){
  unsigned int i;

  close(servSockfd);

  for(i=0;i<list_client->size();i++){
    //send(list_client[i].getSocket(),"000/END",8,0);
    close(list_client->at(i).getSocket());
  }

  exit(0);
}

void AudioMonitorServer::buildSocketList(){
  unsigned int i;

  FD_ZERO(&rdclient);
  FD_SET(servSockfd,&rdclient);

  for(i=0;i<list_client->size();i++){
    FD_SET(list_client->at(i).getSocket(),&rdclient);
  }

}

void AudioMonitorServer::newClient(){
  int tmp_sockfd;
  EASEAClientData* new_client;

  tmp_sockfd = accept(servSockfd,(struct sockaddr*)&my_addr,&addrlen);

  /*selected need to know the highest numerical socket value*/
  if(tmp_sockfd>max_select){
    max_select=tmp_sockfd;
  }

  if (debug) {
    std::cout<<"nouveaux client"<<std::endl;
  }

  /*Adding the newly connected client to the list of client*/
  new_client = new EASEAClientData(tmp_sockfd);
  new_client->setIP(inet_ntoa(my_addr.sin_addr));
  new_client->setPort(ntohs(my_addr.sin_port));
  list_client->push_back(*new_client);

}

void AudioMonitorServer::recvSomething(){
  if(FD_ISSET(servSockfd,&rdclient))
    newClient();
  else
    recvFromClient();

}

/*FAIRE DES STRUCTS POUR L'ENVOI/RECEPTION*/
/* Case new data from known client*/
/* Check whose fd changed and received from them*/
void AudioMonitorServer::recvFromClient(){
  char buf[1024];
  float* dec=(float*)buf;

  unsigned int i;
  EASEAClientData* changedClient;
  memset(buf,'\0',1024); //reset buffer

  for(i=0;i<list_client->size();i++){
    if(list_client->at(i).getSocket()!=0){
      if(FD_ISSET(list_client->at(i).getSocket(),&rdclient)){

        changedClient=&list_client->at(i);
        /*TRES CRADE: FAIRE UN *HEADER* QUI CONTIENT UN CODE IDENTIFICATEUR PLUTOT*/
        if(recv(changedClient->getSocket(),buf,1024,0)==sizeof(bool)){

          if ((bool*)buf[0]) {
            compo->aReception();
          }
          if (!(bool*)buf[0]) {
            compo->aSending();
          }

        }
        else {
          if (!changedClient->toIgnore()) {
            changedClient->addData(dec[0],dec[1],dec[2],dec[3]);

            if (debug){
              std::cout<<"I have received something from "<<
              changedClient->getIP()<<":"<<changedClient->getPort()
              <<std::endl;
              std::cout<<dec[0]<<" "<<dec[1]<<" "<<dec[2]<<" "<<dec[3]<<std::endl;
            }

            compo->notify(changedClient);
          }
          else{
            list_client->at(i).setIgnoreFlag(false);
          }
        }

      }
    }
  }

}

/**
 * /brief    Start the server, which will never stop listening
 **/
void AudioMonitorServer::start(){

  debug=1;

  while(1){

    buildSocketList();

    if((select(max_select+1,&rdclient,NULL,NULL,NULL))>=1){
     recvSomething();
    }
  }
}

/**
* /brief    Add a Compositor
**/
void AudioMonitorServer::setCompositor(Compositor* compo){
  this->compo=compo;
}
<|endoftext|>