<commit_before>/*
 *	tt.xfade~
 *	External object for Max/MSP
 *
 *	Example project for TTBlue
 *	Copyright © 2005 by Timothy Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "ext.h"					// Max Header
#include "z_dsp.h"					// MSP Header
#include "ext_strings.h"			// String Functions
#include "commonsyms.h"				// Common symbols used by the Max 4.5 API
#include "ext_obex.h"				// Max Object Extensions (attributes) Header

#include "TTBlueAPI.h"				// TTBlue Interfaces...

#define MAX_NUM_CHANNELS 32

// Data Structure for this object
typedef struct _fade{
	t_pxobject 			x_obj;
	long				attr_shape;
	long				attr_mode;
	float				attr_position;
	TTUInt16			numChannels;
	TTAudioObject*		xfade;			// crossfade object from the TTBlue library
	TTAudioSignal*		audioIn1;
	TTAudioSignal*		audioIn2;
	TTAudioSignal*		audioInControl;
	TTAudioSignal*		audioOut;
} t_fade;

// Prototypes for methods
void *fade_new(t_symbol *s, long argc, t_atom *argv);				// New Object Creation Method
t_int *fade_perform1(t_int *w);										// An MSP Perform (signal) Method
t_int *fade_perform2(t_int *w);										// An MSP Perform (signal) Method
void fade_dsp(t_fade *x, t_signal **sp, short *count);				// DSP Method
void fade_assist(t_fade *x, void *b, long m, long a, char *s);		// Assistance Method
void fade_float(t_fade *x, double value );							// Float Method
void fade_free(t_fade *x);
t_max_err attr_set_position(t_fade *x, void *attr, long argc, t_atom *argv);
t_max_err attr_set_shape(t_fade *x, void *attr, long argc, t_atom *argv);
t_max_err attr_set_mode(t_fade *x, void *attr, long argc, t_atom *argv);
t_int *fade_perform_stereo_1(t_int *w);
t_int *fade_perform_stereo_2(t_int *w);

// Globals
static t_class	*s_fade_class;

/************************************************************************************/
// Main() Function

int main(void)				// main recieves a copy of the Max function macros table
{
	long attrflags = 0;
	t_class *c;
	t_object *attr;

	TTBlueInit();
	common_symbols_init();

	// Define our class
	c = class_new("tt.xfade~",(method)fade_new, (method)fade_free, sizeof(t_fade), (method)0L, A_GIMME, 0);

	// Make methods accessible for our class:
	class_addmethod(c, (method)fade_float,				"float", A_FLOAT, 0L);
	class_addmethod(c, (method)fade_dsp, 				"dsp", A_CANT, 0L);
    class_addmethod(c, (method)object_obex_dumpout, 	"dumpout", A_CANT,0);
    class_addmethod(c, (method)fade_assist, 			"assist", A_CANT, 0L);

	// Add attributes to our class:
	attr = attr_offset_new("shape", _sym_long, attrflags,
						   (method)0L,(method)attr_set_shape, calcoffset(t_fade, attr_shape));
	class_addattr(c, attr);

	attr = attr_offset_new("mode", _sym_long, attrflags,
						   (method)0L,(method)attr_set_mode, calcoffset(t_fade, attr_mode));
	class_addattr(c, attr);

	attr = attr_offset_new("position", _sym_float32, attrflags,
						   (method)0L,(method)attr_set_position, calcoffset(t_fade, attr_position));
	class_addattr(c, attr);

	// Setup our class to work with MSP
	class_dspinit(c);

	// Finalize our class
	class_register(CLASS_BOX, c);
	s_fade_class = c;
	return 0;
}

/************************************************************************************/
// Object Life

// Create
void *fade_new(t_symbol *s, long argc, t_atom *argv)
{
	long attrstart = attr_args_offset(argc, argv);		// support normal arguments
	short i;

	t_fade *x = (t_fade *)object_alloc(s_fade_class);
	if(x){
		object_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x, NULL));	// dumpout

		x->numChannels = 1;
		if(attrstart && argv){
			int argument = atom_getlong(argv);
			x->numChannels = TTClip(argument, 1, MAX_NUM_CHANNELS);
		}

		dsp_setup((t_pxobject *)x, (x->numChannels * 2) + 1);	// Create Object and N Inlets (last argument)
		x->x_obj.z_misc = Z_NO_INPLACE;  					// ESSENTIAL!
		for(i=0; i< (x->numChannels); i++)
			outlet_new((t_pxobject *)x, "signal");			// Create a signal Outlet

		//x->xfade = new TTCrossfade(x->numChannels);			// Constructors
		TTObjectInstantiate(TT("crossfade"),	&x->xfade,			x->numChannels);
		TTObjectInstantiate(kTTSym_audiosignal,	&x->audioIn1,		x->numChannels);
		TTObjectInstantiate(kTTSym_audiosignal,	&x->audioIn2,		x->numChannels);
		TTObjectInstantiate(kTTSym_audiosignal,	&x->audioInControl,	x->numChannels);
		TTObjectInstantiate(kTTSym_audiosignal,	&x->audioOut,		x->numChannels);

		x->xfade->setAttributeValue(TT("mode"), TT("lookup"));
		x->xfade->setAttributeValue(TT("shape"), TT("equalPower"));
		x->xfade->setAttributeValue(TT("position"), 0.5);

		attr_args_process(x, argc, argv);					// handle attribute args
	}
	return (x);												// Return the pointer
}

// Destroy
void fade_free(t_fade *x)
{
	dsp_free((t_pxobject *)x);		// Always call dsp_free first in this routine

	TTObjectRelease(&x->xfade);
	TTObjectRelease(&x->audioIn1);
	TTObjectRelease(&x->audioIn2);
	TTObjectRelease(&x->audioInControl);
	TTObjectRelease(&x->audioOut);
}

/************************************************************************************/
// Methods bound to input/inlets

// Method for Assistance Messages
void fade_assist(t_fade *x, void *b, long msg, long arg, char *dst)
{
	if(msg==1){ 	// Inlets
		if(arg < x->numChannels)
			strcpy(dst, "(signal) Input A");
		else if(arg < x->numChannels*2)
			strcpy(dst, "(signal) Input B");
		else
			strcpy(dst, "(float/signal) Crossfade Position");
	}
	else if(msg==2){ // Outlets
		if(arg < x->numChannels)
			strcpy(dst, "(signal) Crossfaded between A and B");
		else
			strcpy(dst, "dumpout");
	}
}

// Float Method
void fade_float(t_fade *x, double value)
{
	x->attr_position = value;
	x->xfade->setAttributeValue(TT("position"), value);
}

// ATTRIBUTE: position
t_max_err attr_set_position(t_fade *x, void *attr, long argc, t_atom *argv)
{
	fade_float(x, atom_getfloat(argv));
	return MAX_ERR_NONE;
}

// ATTRIBUTE: shape
t_max_err attr_set_shape(t_fade *x, void *attr, long argc, t_atom *argv)
{
	x->attr_shape = atom_getlong(argv);
	if(x->attr_shape == 0)
		x->xfade->setAttributeValue(TT("shape"), TT("equalPower"));
	else
		x->xfade->setAttributeValue(TT("shape"), TT("linear"));

	return MAX_ERR_NONE;
}

// ATTRIBUTE: mode
t_max_err attr_set_mode(t_fade *x, void *attr, long argc, t_atom *argv)
{
	x->attr_mode = atom_getlong(argv);
	if(x->attr_mode == 0)
		x->xfade->setAttributeValue(TT("mode"), TT("lookup"));
	else
		x->xfade->setAttributeValue(TT("mode"), TT("calculate"));

	return MAX_ERR_NONE;
}

// control rate fading
t_int *fade_perform1(t_int *w)
{
   	t_fade		*x = (t_fade *)(w[1]);
	short		i, j;
	TTUInt8		numChannels = x->audioIn1->getNumChannels();
	TTUInt16	vs = x->audioIn1->getVectorSize();

	for(i=0; i<numChannels; i++){
		j = (i*3) + 1;
		x->audioIn1->setVector(i, vs, (t_float *)(w[j+1]));
		x->audioIn2->setVector(i, vs, (t_float *)(w[j+2]));
	}

	x->xfade->process(*x->audioIn1, *x->audioIn2, *x->audioOut);

	for(i=0; i<numChannels; i++){
		j = (i*3) + 1;
		x->audioOut->getVector(i, vs, (t_float *)(w[j+3]));
	}

	return w + ((numChannels*3)+2);
}

// signal rate fading
t_int *fade_perform2(t_int *w)
{
   	t_fade		*x = (t_fade *)(w[1]);
	short		i, j;
	TTUInt8		numChannels = x->audioIn1->getNumChannels();
	TTUInt16	vs = x->audioIn1->getVectorSize();

	for(i=0; i<numChannels; i++){
		j = (i*3) + 1;
		x->audioIn1->setVector(i, vs, (t_float *)(w[j+1]));
		x->audioIn2->setVector(i, vs, (t_float *)(w[j+2]));
	}
	object_attr_setfloat(x, _sym_position, *((t_float *)(w[(numChannels*3)+2])));

	x->xfade->process(*x->audioIn1, *x->audioIn2, *x->audioOut);

	for(i=0; i<numChannels; i++){
		j = (i*3) + 1;
		x->audioOut->getVector(i, vs, (t_float *)(w[j+3]));
	}

	return w + ((numChannels*3)+3);

}

// DSP Method
void fade_dsp(t_fade *x, t_signal **sp, short *count)
{
	short		i, j, k, l=0;
	void		**audioVectors = NULL;
	TTUInt8		numChannels = 0;
	TTUInt16	vs = 0;

	if(count[x->numChannels * 2])			// SIGNAL RATE CROSSFADE CONNECTED
		audioVectors = (void**)sysmem_newptr(sizeof(void*) * ((x->numChannels * 3) + 2));
	else									// CONTROL RATE CROSSFADE
		audioVectors = (void**)sysmem_newptr(sizeof(void*) * ((x->numChannels * 3) + 1));
	audioVectors[l] = x;
	l++;

	// audioVectors[] passed to balance_perform() as {x, audioInL[0], audioInR[0], audioOut[0], audioInL[1], audioInR[1], audioOut[1],...}
	for(i=0; i < x->numChannels; i++){
		j = x->numChannels + i;
		k = x->numChannels*2 + i + 1;	// + 1 to account for the position input
		if(count[i] && count[j] && count[k]){
			numChannels++;
			if(sp[i]->s_n > vs)
				vs = sp[i]->s_n;

			audioVectors[l] = sp[i]->s_vec;
			l++;
			audioVectors[l] = sp[j]->s_vec;
			l++;
			audioVectors[l] = sp[k]->s_vec;
			l++;
		}
	}

	if(count[x->numChannels * 2]){		// SIGNAL RATE CROSSFADE CONNECTED
		audioVectors[l] = sp[x->numChannels*2]->s_vec;
		l++;
	}

	x->audioIn1->setnumChannels(numChannels);
	x->audioIn2->setnumChannels(numChannels);
	x->audioOut->setnumChannels(numChannels);
	x->audioIn1->setvectorSize(vs);
	x->audioIn2->setvectorSize(vs);
	x->audioOut->setvectorSize(vs);
	//audioIn will be set in the perform method
	x->audioOut->alloc();

	x->xfade->setAttributeValue(TT("sr"), sp[0]->s_sr);

	if(count[x->numChannels * 2])		// SIGNAL RATE CROSSFADE CONNECTED
		dsp_addv(fade_perform2, l, audioVectors);
	else
		dsp_addv(fade_perform1, l, audioVectors);

	sysmem_freeptr(audioVectors);
}

<commit_msg>The tt.xfade~ example for MSP now uses new Max 5 API for defining attributes, and includes enumerated names in the Max inspector.<commit_after>/*
 *	tt.xfade~
 *	External object for Max/MSP
 *
 *	Example project for TTBlue
 *	Copyright © 2005 by Timothy Place
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "ext.h"					// Max Header
#include "z_dsp.h"					// MSP Header
#include "ext_strings.h"			// String Functions
#include "commonsyms.h"				// Common symbols used by the Max 4.5 API
#include "ext_obex.h"				// Max Object Extensions (attributes) Header

#include "TTBlueAPI.h"				// TTBlue Interfaces...

#define MAX_NUM_CHANNELS 32

// Data Structure for this object
typedef struct _fade{
	t_pxobject 			x_obj;
	long				attr_shape;
	long				attr_mode;
	float				attr_position;
	TTUInt16			numChannels;
	TTAudioObject*		xfade;			// crossfade object from the TTBlue library
	TTAudioSignal*		audioIn1;
	TTAudioSignal*		audioIn2;
	TTAudioSignal*		audioInControl;
	TTAudioSignal*		audioOut;
} t_fade;

// Prototypes for methods
void *fade_new(t_symbol *s, long argc, t_atom *argv);				// New Object Creation Method
t_int *fade_perform1(t_int *w);										// An MSP Perform (signal) Method
t_int *fade_perform2(t_int *w);										// An MSP Perform (signal) Method
void fade_dsp(t_fade *x, t_signal **sp, short *count);				// DSP Method
void fade_assist(t_fade *x, void *b, long m, long a, char *s);		// Assistance Method
void fade_float(t_fade *x, double value );							// Float Method
void fade_free(t_fade *x);
t_max_err attr_set_position(t_fade *x, void *attr, long argc, t_atom *argv);
t_max_err attr_set_shape(t_fade *x, void *attr, long argc, t_atom *argv);
t_max_err attr_set_mode(t_fade *x, void *attr, long argc, t_atom *argv);
t_int *fade_perform_stereo_1(t_int *w);
t_int *fade_perform_stereo_2(t_int *w);

// Globals
static t_class	*s_fade_class;

/************************************************************************************/
// Main() Function

int main(void)				// main recieves a copy of the Max function macros table
{
	long attrflags = 0;
	t_class *c;
	t_object *attr;

	TTBlueInit();
	common_symbols_init();

	// Define our class
	c = class_new("tt.xfade~", (method)fade_new, (method)fade_free, sizeof(t_fade), (method)0L, A_GIMME, 0);

	// Make methods accessible for our class:
	class_addmethod(c, (method)fade_float,				"float", A_FLOAT, 0L);
	class_addmethod(c, (method)fade_dsp, 				"dsp", A_CANT, 0L);
    class_addmethod(c, (method)object_obex_dumpout, 	"dumpout", A_CANT,0);
    class_addmethod(c, (method)fade_assist, 			"assist", A_CANT, 0L);

	// Add attributes to our class:
	CLASS_ATTR_LONG(c,		"shape",		0,	t_fade, attr_shape);
	CLASS_ATTR_ACCESSORS(c,	"shape",		NULL, attr_set_shape);
	CLASS_ATTR_ENUMINDEX(c,	"shape",		0, "EqualPower Linear");

	CLASS_ATTR_LONG(c,		"mode",			0,	t_fade, attr_mode);
	CLASS_ATTR_ACCESSORS(c,	"mode",			NULL, attr_set_mode);
	CLASS_ATTR_ENUMINDEX(c,	"mode",			0, "LookupTable Calculate");

	CLASS_ATTR_FLOAT(c,		"position",		0,	t_fade, attr_position);
	CLASS_ATTR_ACCESSORS(c,	"position",		NULL, attr_set_position);

	// Setup our class to work with MSP
	class_dspinit(c);

	// Finalize our class
	class_register(CLASS_BOX, c);
	s_fade_class = c;
	return 0;
}

/************************************************************************************/
// Object Life

// Create
void *fade_new(t_symbol *s, long argc, t_atom *argv)
{
	long attrstart = attr_args_offset(argc, argv);		// support normal arguments
	short i;

	t_fade *x = (t_fade *)object_alloc(s_fade_class);
	if(x){
		object_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x, NULL));	// dumpout

		x->numChannels = 1;
		if(attrstart && argv){
			int argument = atom_getlong(argv);
			x->numChannels = TTClip(argument, 1, MAX_NUM_CHANNELS);
		}

		dsp_setup((t_pxobject *)x, (x->numChannels * 2) + 1);	// Create Object and N Inlets (last argument)
		x->x_obj.z_misc = Z_NO_INPLACE;  					// ESSENTIAL!
		for(i=0; i< (x->numChannels); i++)
			outlet_new((t_pxobject *)x, "signal");			// Create a signal Outlet

		//x->xfade = new TTCrossfade(x->numChannels);			// Constructors
		TTObjectInstantiate(TT("crossfade"),	&x->xfade,			x->numChannels);
		TTObjectInstantiate(kTTSym_audiosignal,	&x->audioIn1,		x->numChannels);
		TTObjectInstantiate(kTTSym_audiosignal,	&x->audioIn2,		x->numChannels);
		TTObjectInstantiate(kTTSym_audiosignal,	&x->audioInControl,	x->numChannels);
		TTObjectInstantiate(kTTSym_audiosignal,	&x->audioOut,		x->numChannels);

		x->xfade->setAttributeValue(TT("mode"), TT("lookup"));
		x->xfade->setAttributeValue(TT("shape"), TT("equalPower"));
		x->xfade->setAttributeValue(TT("position"), 0.5);

		attr_args_process(x, argc, argv);					// handle attribute args
	}
	return (x);												// Return the pointer
}

// Destroy
void fade_free(t_fade *x)
{
	dsp_free((t_pxobject *)x);		// Always call dsp_free first in this routine

	TTObjectRelease(&x->xfade);
	TTObjectRelease(&x->audioIn1);
	TTObjectRelease(&x->audioIn2);
	TTObjectRelease(&x->audioInControl);
	TTObjectRelease(&x->audioOut);
}

/************************************************************************************/
// Methods bound to input/inlets

// Method for Assistance Messages
void fade_assist(t_fade *x, void *b, long msg, long arg, char *dst)
{
	if(msg==1){ 	// Inlets
		if(arg < x->numChannels)
			strcpy(dst, "(signal) Input A");
		else if(arg < x->numChannels*2)
			strcpy(dst, "(signal) Input B");
		else
			strcpy(dst, "(float/signal) Crossfade Position");
	}
	else if(msg==2){ // Outlets
		if(arg < x->numChannels)
			strcpy(dst, "(signal) Crossfaded between A and B");
		else
			strcpy(dst, "dumpout");
	}
}

// Float Method
void fade_float(t_fade *x, double value)
{
	x->attr_position = value;
	x->xfade->setAttributeValue(TT("position"), value);
}

// ATTRIBUTE: position
t_max_err attr_set_position(t_fade *x, void *attr, long argc, t_atom *argv)
{
	fade_float(x, atom_getfloat(argv));
	return MAX_ERR_NONE;
}

// ATTRIBUTE: shape
t_max_err attr_set_shape(t_fade *x, void *attr, long argc, t_atom *argv)
{
	x->attr_shape = atom_getlong(argv);
	if(x->attr_shape == 0)
		x->xfade->setAttributeValue(TT("shape"), TT("equalPower"));
	else
		x->xfade->setAttributeValue(TT("shape"), TT("linear"));

	return MAX_ERR_NONE;
}

// ATTRIBUTE: mode
t_max_err attr_set_mode(t_fade *x, void *attr, long argc, t_atom *argv)
{
	x->attr_mode = atom_getlong(argv);
	if(x->attr_mode == 0)
		x->xfade->setAttributeValue(TT("mode"), TT("lookup"));
	else
		x->xfade->setAttributeValue(TT("mode"), TT("calculate"));

	return MAX_ERR_NONE;
}

// control rate fading
t_int *fade_perform1(t_int *w)
{
   	t_fade		*x = (t_fade *)(w[1]);
	short		i, j;
	TTUInt8		numChannels = x->audioIn1->getNumChannels();
	TTUInt16	vs = x->audioIn1->getVectorSize();

	for(i=0; i<numChannels; i++){
		j = (i*3) + 1;
		x->audioIn1->setVector(i, vs, (t_float *)(w[j+1]));
		x->audioIn2->setVector(i, vs, (t_float *)(w[j+2]));
	}

	x->xfade->process(*x->audioIn1, *x->audioIn2, *x->audioOut);

	for(i=0; i<numChannels; i++){
		j = (i*3) + 1;
		x->audioOut->getVector(i, vs, (t_float *)(w[j+3]));
	}

	return w + ((numChannels*3)+2);
}

// signal rate fading
t_int *fade_perform2(t_int *w)
{
   	t_fade		*x = (t_fade *)(w[1]);
	short		i, j;
	TTUInt8		numChannels = x->audioIn1->getNumChannels();
	TTUInt16	vs = x->audioIn1->getVectorSize();

	for(i=0; i<numChannels; i++){
		j = (i*3) + 1;
		x->audioIn1->setVector(i, vs, (t_float *)(w[j+1]));
		x->audioIn2->setVector(i, vs, (t_float *)(w[j+2]));
	}
	object_attr_setfloat(x, _sym_position, *((t_float *)(w[(numChannels*3)+2])));

	x->xfade->process(*x->audioIn1, *x->audioIn2, *x->audioOut);

	for(i=0; i<numChannels; i++){
		j = (i*3) + 1;
		x->audioOut->getVector(i, vs, (t_float *)(w[j+3]));
	}

	return w + ((numChannels*3)+3);

}

// DSP Method
void fade_dsp(t_fade *x, t_signal **sp, short *count)
{
	short		i, j, k, l=0;
	void		**audioVectors = NULL;
	TTUInt8		numChannels = 0;
	TTUInt16	vs = 0;

	if(count[x->numChannels * 2])			// SIGNAL RATE CROSSFADE CONNECTED
		audioVectors = (void**)sysmem_newptr(sizeof(void*) * ((x->numChannels * 3) + 2));
	else									// CONTROL RATE CROSSFADE
		audioVectors = (void**)sysmem_newptr(sizeof(void*) * ((x->numChannels * 3) + 1));
	audioVectors[l] = x;
	l++;

	// audioVectors[] passed to balance_perform() as {x, audioInL[0], audioInR[0], audioOut[0], audioInL[1], audioInR[1], audioOut[1],...}
	for(i=0; i < x->numChannels; i++){
		j = x->numChannels + i;
		k = x->numChannels*2 + i + 1;	// + 1 to account for the position input
		if(count[i] && count[j] && count[k]){
			numChannels++;
			if(sp[i]->s_n > vs)
				vs = sp[i]->s_n;

			audioVectors[l] = sp[i]->s_vec;
			l++;
			audioVectors[l] = sp[j]->s_vec;
			l++;
			audioVectors[l] = sp[k]->s_vec;
			l++;
		}
	}

	if(count[x->numChannels * 2]){		// SIGNAL RATE CROSSFADE CONNECTED
		audioVectors[l] = sp[x->numChannels*2]->s_vec;
		l++;
	}

	x->audioIn1->setnumChannels(numChannels);
	x->audioIn2->setnumChannels(numChannels);
	x->audioOut->setnumChannels(numChannels);
	x->audioIn1->setvectorSize(vs);
	x->audioIn2->setvectorSize(vs);
	x->audioOut->setvectorSize(vs);
	//audioIn will be set in the perform method
	x->audioOut->alloc();

	x->xfade->setAttributeValue(TT("sr"), sp[0]->s_sr);

	if(count[x->numChannels * 2])		// SIGNAL RATE CROSSFADE CONNECTED
		dsp_addv(fade_perform2, l, audioVectors);
	else
		dsp_addv(fade_perform1, l, audioVectors);

	sysmem_freeptr(audioVectors);
}

<|endoftext|>


<commit_before>/*
 * RGraphicsPlotManipulator.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

// TODO: closure for manipulate substitute expression

// TODO: validate that all controls have variables in the expression

// TODO: if manipulator popup values and controls match exactly then
// do nothing....this will take care of the flashing problem

#include "RGraphicsPlotManipulator.hpp"

#include <core/Error.hpp>
#include <core/FilePath.hpp>

#include <r/RExec.hpp>
#include <r/RJson.hpp>

using namespace core;

namespace r {
namespace session {
namespace graphics {

PlotManipulator::PlotManipulator()
   : sexp_()
{
}

PlotManipulator::PlotManipulator(SEXP sexp)
   : sexp_(sexp)
{
}

PlotManipulator::~PlotManipulator()
{
   try
   {
   }
   catch(...)
   {
   }
}

Error PlotManipulator::save(const FilePath& filePath) const
{
   // call manipulator save
   r::exec::RFunction manipSave(".rs.manipulator.save");
   manipSave.addParam(sexp_.get());
   manipSave.addParam(filePath.absolutePath());
   return manipSave.call();
}

Error PlotManipulator::load(const FilePath& filePath)
{
   // call manipulator load
   r::exec::RFunction manipLoad(".rs.manipulator.load");
   manipLoad.addParam(filePath.absolutePath());
   SEXP manipSEXP;
   Error error = manipLoad.call(&manipSEXP);
   if (error)
      return error;

   // set it
   sexp_.set(manipSEXP);
   return Success();
}

void PlotManipulator::asJson(core::json::Value* pValue) const
{
   Error error = r::json::jsonValueFromObject(sexp_.get(), pValue);
   if (error)
      LOG_ERROR(error);
}

SEXP PlotManipulator::sexp() const
{
   return sexp_.get();
}

} // namespace graphics
} // namespace session
} // namesapce r

<commit_msg>eliminate TODO comments<commit_after>/*
 * RGraphicsPlotManipulator.cpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "RGraphicsPlotManipulator.hpp"

#include <core/Error.hpp>
#include <core/FilePath.hpp>

#include <r/RExec.hpp>
#include <r/RJson.hpp>

using namespace core;

namespace r {
namespace session {
namespace graphics {

PlotManipulator::PlotManipulator()
   : sexp_()
{
}

PlotManipulator::PlotManipulator(SEXP sexp)
   : sexp_(sexp)
{
}

PlotManipulator::~PlotManipulator()
{
   try
   {
   }
   catch(...)
   {
   }
}

Error PlotManipulator::save(const FilePath& filePath) const
{
   // call manipulator save
   r::exec::RFunction manipSave(".rs.manipulator.save");
   manipSave.addParam(sexp_.get());
   manipSave.addParam(filePath.absolutePath());
   return manipSave.call();
}

Error PlotManipulator::load(const FilePath& filePath)
{
   // call manipulator load
   r::exec::RFunction manipLoad(".rs.manipulator.load");
   manipLoad.addParam(filePath.absolutePath());
   SEXP manipSEXP;
   Error error = manipLoad.call(&manipSEXP);
   if (error)
      return error;

   // set it
   sexp_.set(manipSEXP);
   return Success();
}

void PlotManipulator::asJson(core::json::Value* pValue) const
{
   Error error = r::json::jsonValueFromObject(sexp_.get(), pValue);
   if (error)
      LOG_ERROR(error);
}

SEXP PlotManipulator::sexp() const
{
   return sexp_.get();
}

} // namespace graphics
} // namespace session
} // namesapce r

<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt 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 "otbCoordinateToName.h"
#include "otbMacro.h"

#ifdef OTB_USE_CURL
#include "tinyxml.h"
#include <curl/curl.h>
#endif

namespace otb
{

/**
 * Constructor
 */

CoordinateToName::CoordinateToName():
    m_Lon(-1000.0), m_Lat(-1000.0), m_Multithread(false), m_IsValid(false)
{
  m_PlaceName = "";
  m_CountryName = "";
  m_TempFileName = "out-SignayriUt1.xml";

  m_Threader = itk::MultiThreader::New();

  m_UpdateDistance = 0.01;//about 1km at equator

}

/**
 * PrintSelf
 */
void
CoordinateToName
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << " m_Lon "  << m_Lon << std::endl;
  os << indent << " m_Lat "  << m_Lat << std::endl;
  os << indent << " m_PlaceName "  << m_PlaceName << std::endl;
}

bool CoordinateToName::Evaluate()
{
  if (m_Multithread)
  {
    m_Threader->SpawnThread(ThreadFunction, this);
  }
  else
  {
    DoEvaluate();
  }
}

ITK_THREAD_RETURN_TYPE
CoordinateToName::ThreadFunction( void *arg )
{
  struct itk::MultiThreader::ThreadInfoStruct * pInfo = (itk::MultiThreader::ThreadInfoStruct *)(arg);
  CoordinateToName::Pointer lThis = (CoordinateToName*)(pInfo->UserData);
  lThis->DoEvaluate();
}

void CoordinateToName::DoEvaluate()
{
  std::ostringstream urlStream;
  urlStream << "http://ws.geonames.org/findNearbyPlaceName?lat=";
  urlStream << m_Lat;
  urlStream << "&lng=";
  urlStream << m_Lon;
  otbMsgDevMacro("CoordinateToName: retrieve url " << urlStream.str());
  RetrieveXML(urlStream);
  std::string placeName = "";
  std::string countryName = "";
  ParseXMLGeonames(placeName, countryName);
  m_PlaceName = placeName;
  m_CountryName = countryName;
  m_IsValid = true;
}

void CoordinateToName::RetrieveXML(std::ostringstream& urlStream) const
{
#ifdef OTB_USE_CURL
  CURL *curl;
  CURLcode res;

  FILE* output_file = fopen(m_TempFileName.c_str(),"w");
  curl = curl_easy_init();

  char url[256];
  strcpy(url,urlStream.str().data());

//   std::cout << url << std::endl;
  if (curl)
  {
    std::vector<char> chunk;
    curl_easy_setopt(curl, CURLOPT_URL, url);

    curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_file);
    res = curl_easy_perform(curl);

    fclose(output_file);
    /* always cleanup */
    curl_easy_cleanup(curl);
  }
#endif
}

void CoordinateToName::ParseXMLGeonames(std::string& placeName, std::string& countryName) const
{
#ifdef OTB_USE_CURL
  TiXmlDocument doc( m_TempFileName.c_str() );
  doc.LoadFile();
  TiXmlHandle docHandle( &doc );

  TiXmlElement* childName = docHandle.FirstChild( "geonames" ).FirstChild( "geoname" ).
      FirstChild( "name" ).Element();
  if ( childName )
  {
    placeName=childName->GetText();
  }
  TiXmlElement* childCountryName = docHandle.FirstChild( "geonames" ).FirstChild( "geoname" ).
      FirstChild( "countryName" ).Element();
  if ( childCountryName )
  {
    countryName=childCountryName->GetText();
  }

  remove(m_TempFileName.c_str());
#endif
}

} // namespace otb
<commit_msg>WRG: add return to methods<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt 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 "otbCoordinateToName.h"
#include "otbMacro.h"

#ifdef OTB_USE_CURL
#include "tinyxml.h"
#include <curl/curl.h>
#endif

namespace otb
{

/**
 * Constructor
 */

CoordinateToName::CoordinateToName():
    m_Lon(-1000.0), m_Lat(-1000.0), m_Multithread(false), m_IsValid(false)
{
  m_PlaceName = "";
  m_CountryName = "";
  m_TempFileName = "out-SignayriUt1.xml";

  m_Threader = itk::MultiThreader::New();

  m_UpdateDistance = 0.01;//about 1km at equator

}

/**
 * PrintSelf
 */
void
CoordinateToName
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << " m_Lon "  << m_Lon << std::endl;
  os << indent << " m_Lat "  << m_Lat << std::endl;
  os << indent << " m_PlaceName "  << m_PlaceName << std::endl;
}

bool CoordinateToName::Evaluate()
{
  if (m_Multithread)
  {
    m_Threader->SpawnThread(ThreadFunction, this);
  }
  else
  {
    DoEvaluate();
  }
  return true;
}

ITK_THREAD_RETURN_TYPE
CoordinateToName::ThreadFunction( void *arg )
{
  struct itk::MultiThreader::ThreadInfoStruct * pInfo = (itk::MultiThreader::ThreadInfoStruct *)(arg);
  CoordinateToName::Pointer lThis = (CoordinateToName*)(pInfo->UserData);
  lThis->DoEvaluate();
  return 0;
}

void CoordinateToName::DoEvaluate()
{
  std::ostringstream urlStream;
  urlStream << "http://ws.geonames.org/findNearbyPlaceName?lat=";
  urlStream << m_Lat;
  urlStream << "&lng=";
  urlStream << m_Lon;
  otbMsgDevMacro("CoordinateToName: retrieve url " << urlStream.str());
  RetrieveXML(urlStream);
  std::string placeName = "";
  std::string countryName = "";
  ParseXMLGeonames(placeName, countryName);
  m_PlaceName = placeName;
  m_CountryName = countryName;
  m_IsValid = true;
}

void CoordinateToName::RetrieveXML(std::ostringstream& urlStream) const
{
#ifdef OTB_USE_CURL
  CURL *curl;
  CURLcode res;

  FILE* output_file = fopen(m_TempFileName.c_str(),"w");
  curl = curl_easy_init();

  char url[256];
  strcpy(url,urlStream.str().data());

//   std::cout << url << std::endl;
  if (curl)
  {
    std::vector<char> chunk;
    curl_easy_setopt(curl, CURLOPT_URL, url);

    curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_file);
    res = curl_easy_perform(curl);

    fclose(output_file);
    /* always cleanup */
    curl_easy_cleanup(curl);
  }
#endif
}

void CoordinateToName::ParseXMLGeonames(std::string& placeName, std::string& countryName) const
{
#ifdef OTB_USE_CURL
  TiXmlDocument doc( m_TempFileName.c_str() );
  doc.LoadFile();
  TiXmlHandle docHandle( &doc );

  TiXmlElement* childName = docHandle.FirstChild( "geonames" ).FirstChild( "geoname" ).
      FirstChild( "name" ).Element();
  if ( childName )
  {
    placeName=childName->GetText();
  }
  TiXmlElement* childCountryName = docHandle.FirstChild( "geonames" ).FirstChild( "geoname" ).
      FirstChild( "countryName" ).Element();
  if ( childCountryName )
  {
    countryName=childCountryName->GetText();
  }

  remove(m_TempFileName.c_str());
#endif
}

} // namespace otb
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "qlinear_global_average_pool.h"
#include "core/util/math_cpuonly.h"
#include "core/providers/common.h"
#include "core/platform/threadpool.h"
#include "core/util/math.h"
#include "core/mlas/inc/mlas.h"
#include <functional>

using onnxruntime::concurrency::ThreadPool;

namespace onnxruntime {
namespace contrib {

Status ComputeQLinearGlobalAvgPool(
    const uint8_t* x,
    float x_scale,
    uint8_t x_zero_point,
    uint8_t* y,
    float y_scale,
    uint8_t y_zero_point,
    int64_t N,
    int64_t C,
    int64_t image_size,
    bool channels_last,
    concurrency::ThreadPool* tp) {
  static constexpr int64_t kMiniChannelGroup = 64;

  if (!channels_last || C == 1) {
    auto worker = [=](std::ptrdiff_t first, std::ptrdiff_t last) {
      const uint8_t* input = (const uint8_t*)(x + (first * image_size));
      uint8_t* output = (uint8_t*)(y + first);
      std::vector<int32_t> acc_buffer(MlasQLinearSafePaddingElementCount(sizeof(int32_t), last - first));
      MlasQLinearGlobalAveragePoolNchw(input, x_scale, x_zero_point, output, y_scale, y_zero_point, last - first, image_size, acc_buffer.data());
    };
    concurrency::ThreadPool::TryParallelFor(
        tp, static_cast<std::ptrdiff_t>(N * C), {1.0 * image_size, 1.0, 8.0 * image_size}, worker);
  } else {
    if (N == 1) {
      int64_t channel_padded = (C + kMiniChannelGroup - 1) & (~(kMiniChannelGroup - 1));
      int64_t channel_groups = channel_padded / kMiniChannelGroup;
      auto worker = [=](std::ptrdiff_t first, std::ptrdiff_t last) {
        std::vector<int32_t> acc_buffer(MlasQLinearSafePaddingElementCount(sizeof(int32_t), C));
        std::vector<uint8_t> zero_buffer(MlasQLinearSafePaddingElementCount(sizeof(uint8_t), C), 0);
        const uint8_t* input = x + first * kMiniChannelGroup;
        uint8_t* output = y + first * kMiniChannelGroup;
        int64_t channel_count = (last == channel_groups) ? (C - first * kMiniChannelGroup) : ((last - first) * kMiniChannelGroup);
        MlasQLinearGlobalAveragePoolNhwc(
            input, x_scale, x_zero_point, output, y_scale, y_zero_point,
            N, image_size, C, channel_count, acc_buffer.data(), zero_buffer.data());
      };
      concurrency::ThreadPool::TryParallelFor(
          tp, static_cast<std::ptrdiff_t>(channel_groups),
          {1.0 * N * image_size * kMiniChannelGroup, 1.0 * N * kMiniChannelGroup, 8.0 * N * image_size * kMiniChannelGroup},
          worker);
    } else {
      auto worker = [=](std::ptrdiff_t first, std::ptrdiff_t last) {
        const uint8_t* input = x + first * C * image_size;
        uint8_t* output = y + first * C;
        std::vector<int32_t> acc_buffer(MlasQLinearSafePaddingElementCount(sizeof(int32_t), C));
        std::vector<uint8_t> zero_buffer(MlasQLinearSafePaddingElementCount(sizeof(uint8_t), C), 0);
        MlasQLinearGlobalAveragePoolNhwc(
            input, x_scale, x_zero_point, output, y_scale, y_zero_point,
            last - first, image_size, C, C, acc_buffer.data(), zero_buffer.data());
      };
      concurrency::ThreadPool::TryParallelFor(
          tp, static_cast<std::ptrdiff_t>(N),
          {1.0 * image_size * C, 1.0 * C, 8.0 *image_size * C},
          worker);
    }
  }
  return Status::OK();
}

Status QLinearGlobalAveragePool::Compute(OpKernelContext* context) const {
  const auto tensor_x_scale = context->Input<Tensor>(1);
  const auto tensor_x_zero_point = context->Input<Tensor>(2);
  const auto tensor_y_scale = context->Input<Tensor>(3);
  const auto tensor_y_zero_point = context->Input<Tensor>(4);

  ORT_ENFORCE(IsScalarOr1ElementVector(tensor_x_scale),
              "Input x_scale must be a scalar or 1D tensor of size 1");
  ORT_ENFORCE(IsScalarOr1ElementVector(tensor_x_zero_point),
              "input x_zero_point must be a scalar or 1D tensor of size 1 if given");
  ORT_ENFORCE(IsScalarOr1ElementVector(tensor_y_scale),
              "input y_scale must be a scalar or 1D tensor of size 1");
  ORT_ENFORCE(IsScalarOr1ElementVector(tensor_y_zero_point),
              "input y_zero_point must be a scalar or 1D tensor of size 1 if given");

  concurrency::ThreadPool* tp = context->GetOperatorThreadPool();
  const auto& X = *context->Input<Tensor>(0);
  const auto& x_shape = X.Shape().GetDims();

  ORT_RETURN_IF_NOT(x_shape.size() >= 3, "Input dimension cannot be less than 3.");
  const size_t spatial_dim_start = channels_last_ ? 1 : 2;
  const size_t spatial_dim_end = spatial_dim_start + (x_shape.size() - 2);

  int64_t N = x_shape[0];
  int64_t C = (channels_last_ ? x_shape.back() : x_shape[1]);
  int64_t image_size = std::accumulate(x_shape.cbegin() + spatial_dim_start, x_shape.cbegin() + spatial_dim_end,
                                       1LL, std::multiplies<int64_t>());

  std::vector<int64_t> output_dims(x_shape);
  std::transform(x_shape.cbegin() + spatial_dim_start, x_shape.cbegin() + spatial_dim_end,
                 output_dims.begin() + spatial_dim_start, [](const int64_t&) { return int64_t{1}; });
  Tensor& Y = *context->Output(0, output_dims);

  const float x_scale = *(tensor_x_scale->Data<float>());
  const float y_scale = *(tensor_y_scale->Data<float>());
  auto dtype = X.GetElementType();
  switch (dtype) {
    case ONNX_NAMESPACE::TensorProto_DataType_UINT8:
      return ComputeQLinearGlobalAvgPool(X.Data<uint8_t>(), x_scale, *(tensor_x_zero_point->Data<uint8_t>()),
                                Y.MutableData<uint8_t>(), y_scale, *(tensor_y_zero_point->Data<uint8_t>()),
                                N, C, image_size, channels_last_, tp);
    default:
      ORT_THROW("Unsupported 'dtype' value: ", dtype);
  }
}

ONNX_OPERATOR_KERNEL_EX(QLinearGlobalAveragePool, kMSDomain, 1, kCpuExecutionProvider, KernelDefBuilder(), QLinearGlobalAveragePool);

}  // namespace contrib

}  // namespace onnxruntime
<commit_msg>disable inner parallel for global avg pool as normally they are small (#9487)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "qlinear_global_average_pool.h"
#include "core/util/math_cpuonly.h"
#include "core/providers/common.h"
#include "core/platform/threadpool.h"
#include "core/util/math.h"
#include "core/mlas/inc/mlas.h"
#include <functional>

using onnxruntime::concurrency::ThreadPool;

namespace onnxruntime {
namespace contrib {

Status ComputeQLinearGlobalAvgPool(
    const uint8_t* x,
    float x_scale,
    uint8_t x_zero_point,
    uint8_t* y,
    float y_scale,
    uint8_t y_zero_point,
    int64_t N,
    int64_t C,
    int64_t image_size,
    bool channels_last,
    concurrency::ThreadPool* tp) {
  if (!channels_last || C == 1) {
    auto worker = [=](std::ptrdiff_t first, std::ptrdiff_t last) {
      const uint8_t* input = (const uint8_t*)(x + (first * image_size));
      uint8_t* output = (uint8_t*)(y + first);
      std::vector<int32_t> acc_buffer(MlasQLinearSafePaddingElementCount(sizeof(int32_t), last - first));
      MlasQLinearGlobalAveragePoolNchw(input, x_scale, x_zero_point, output, y_scale, y_zero_point, last - first, image_size, acc_buffer.data());
    };
    concurrency::ThreadPool::TryParallelFor(
        tp, static_cast<std::ptrdiff_t>(N * C), {1.0 * image_size, 1.0, 8.0 * image_size}, worker);
  } else {
    auto worker = [=](std::ptrdiff_t first, std::ptrdiff_t last) {
      const uint8_t* input = x + first * C * image_size;
      uint8_t* output = y + first * C;
      std::vector<int32_t> acc_buffer(MlasQLinearSafePaddingElementCount(sizeof(int32_t), C));
      std::vector<uint8_t> zero_buffer(MlasQLinearSafePaddingElementCount(sizeof(uint8_t), C), 0);
      MlasQLinearGlobalAveragePoolNhwc(
          input, x_scale, x_zero_point, output, y_scale, y_zero_point,
          last - first, image_size, C, C, acc_buffer.data(), zero_buffer.data());
    };
    concurrency::ThreadPool::TryParallelFor(
        tp, static_cast<std::ptrdiff_t>(N),
        {1.0 * image_size * C, 1.0 * C, 8.0 *image_size * C},
        worker);
  }
  return Status::OK();
}

Status QLinearGlobalAveragePool::Compute(OpKernelContext* context) const {
  const auto tensor_x_scale = context->Input<Tensor>(1);
  const auto tensor_x_zero_point = context->Input<Tensor>(2);
  const auto tensor_y_scale = context->Input<Tensor>(3);
  const auto tensor_y_zero_point = context->Input<Tensor>(4);

  ORT_ENFORCE(IsScalarOr1ElementVector(tensor_x_scale),
              "Input x_scale must be a scalar or 1D tensor of size 1");
  ORT_ENFORCE(IsScalarOr1ElementVector(tensor_x_zero_point),
              "input x_zero_point must be a scalar or 1D tensor of size 1 if given");
  ORT_ENFORCE(IsScalarOr1ElementVector(tensor_y_scale),
              "input y_scale must be a scalar or 1D tensor of size 1");
  ORT_ENFORCE(IsScalarOr1ElementVector(tensor_y_zero_point),
              "input y_zero_point must be a scalar or 1D tensor of size 1 if given");

  concurrency::ThreadPool* tp = context->GetOperatorThreadPool();
  const auto& X = *context->Input<Tensor>(0);
  const auto& x_shape = X.Shape().GetDims();

  ORT_RETURN_IF_NOT(x_shape.size() >= 3, "Input dimension cannot be less than 3.");
  const size_t spatial_dim_start = channels_last_ ? 1 : 2;
  const size_t spatial_dim_end = spatial_dim_start + (x_shape.size() - 2);

  int64_t N = x_shape[0];
  int64_t C = (channels_last_ ? x_shape.back() : x_shape[1]);
  int64_t image_size = std::accumulate(x_shape.cbegin() + spatial_dim_start, x_shape.cbegin() + spatial_dim_end,
                                       1LL, std::multiplies<int64_t>());

  std::vector<int64_t> output_dims(x_shape);
  std::transform(x_shape.cbegin() + spatial_dim_start, x_shape.cbegin() + spatial_dim_end,
                 output_dims.begin() + spatial_dim_start, [](const int64_t&) { return int64_t{1}; });
  Tensor& Y = *context->Output(0, output_dims);

  const float x_scale = *(tensor_x_scale->Data<float>());
  const float y_scale = *(tensor_y_scale->Data<float>());
  auto dtype = X.GetElementType();
  switch (dtype) {
    case ONNX_NAMESPACE::TensorProto_DataType_UINT8:
      return ComputeQLinearGlobalAvgPool(X.Data<uint8_t>(), x_scale, *(tensor_x_zero_point->Data<uint8_t>()),
                                Y.MutableData<uint8_t>(), y_scale, *(tensor_y_zero_point->Data<uint8_t>()),
                                N, C, image_size, channels_last_, tp);
    default:
      ORT_THROW("Unsupported 'dtype' value: ", dtype);
  }
}

ONNX_OPERATOR_KERNEL_EX(QLinearGlobalAveragePool, kMSDomain, 1, kCpuExecutionProvider, KernelDefBuilder(), QLinearGlobalAveragePool);

}  // namespace contrib

}  // namespace onnxruntime
<|endoftext|>


<commit_before>/*
 * BackwardChainerPMCB.cc
 *
 * Copyright (C) 2014 Misgana Bayetta
 * Copyright (C) 2015 OpenCog Foundation
 *
 * Author: Misgana Bayetta <misgana.bayetta@gmail.com>  October 2014
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "BackwardChainerPMCB.h"

using namespace opencog;

BackwardChainerPMCB::BackwardChainerPMCB(AtomSpace * as)
    : InitiateSearchCB(as), DefaultPatternMatchCB(as), as_(as)
 // : Implicator(as), DefaultPatternMatchCB(as), AttentionalFocusCB(as), PLNImplicator(as), as_(as)
{
}

BackwardChainerPMCB::~BackwardChainerPMCB()
{
}

bool BackwardChainerPMCB::grounding(const std::map<Handle, Handle> &var_soln,
                               const std::map<Handle, Handle> &pred_soln)
{
	std::map<Handle, Handle> true_var_soln;

	// get rid of non-var mapping
	for (auto& p : var_soln)
	{
		if (p.first->getType() == VARIABLE_NODE)
			true_var_soln[p.first] = p.second;
	}

	// XXX TODO if a variable match to itself, reject?

	// store the variable solution
	var_solns_.push_back(true_var_soln);
	pred_solns_.push_back(pred_soln);

	return false;
}

std::vector<std::map<Handle, Handle>> BackwardChainerPMCB::get_var_list()
{
	return var_solns_;
}
std::vector<std::map<Handle, Handle>> BackwardChainerPMCB::get_pred_list()
{
	return pred_solns_;
}
<commit_msg>Correct variable checking in PMCB<commit_after>/*
 * BackwardChainerPMCB.cc
 *
 * Copyright (C) 2014 Misgana Bayetta
 * Copyright (C) 2015 OpenCog Foundation
 *
 * Author: Misgana Bayetta <misgana.bayetta@gmail.com>  October 2014
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "BackwardChainerPMCB.h"

using namespace opencog;

BackwardChainerPMCB::BackwardChainerPMCB(AtomSpace * as)
    : InitiateSearchCB(as), DefaultPatternMatchCB(as), as_(as)
 // : Implicator(as), DefaultPatternMatchCB(as), AttentionalFocusCB(as), PLNImplicator(as), as_(as)
{
}

BackwardChainerPMCB::~BackwardChainerPMCB()
{
}

bool BackwardChainerPMCB::grounding(const std::map<Handle, Handle> &var_soln,
                               const std::map<Handle, Handle> &pred_soln)
{
	std::map<Handle, Handle> true_var_soln;

	// get rid of non-var mapping
	for (auto& p : var_soln)
	{
		if (_variables->varset.count(p.first) == 1)
			true_var_soln[p.first] = p.second;
	}

	// XXX TODO if a variable match to itself, reject?

	if (true_var_soln.size() == 0)
		return false;

	// store the variable solution
	var_solns_.push_back(true_var_soln);
	pred_solns_.push_back(pred_soln);

	return false;
}

std::vector<std::map<Handle, Handle>> BackwardChainerPMCB::get_var_list()
{
	return var_solns_;
}
std::vector<std::map<Handle, Handle>> BackwardChainerPMCB::get_pred_list()
{
	return pred_solns_;
}
<|endoftext|>


<commit_before>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2012, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/* Author: E. Gil Jones */

#include <ros/ros.h>
#include <chomp_motion_planner/chomp_planner.h>
#include <chomp_motion_planner/chomp_trajectory.h>
#include <chomp_motion_planner/chomp_optimizer.h>
#include <moveit/robot_state/conversions.h>
#include <moveit_msgs/MotionPlanRequest.h>

namespace chomp
{
ChompPlanner::ChompPlanner()
{
}

bool ChompPlanner::solve(const planning_scene::PlanningSceneConstPtr& planning_scene,
                         const moveit_msgs::MotionPlanRequest& req, const chomp::ChompParameters& params,
                         moveit_msgs::MotionPlanDetailedResponse& res) const
{
  if (!planning_scene)
  {
    ROS_ERROR_STREAM("No planning scene initialized.");
    return false;
  }

  ros::WallTime start_time = ros::WallTime::now();
  ChompTrajectory trajectory(planning_scene->getRobotModel(), 3.0, .03, req.group_name);
  jointStateToArray(planning_scene->getRobotModel(), req.start_state.joint_state, req.group_name,
                    trajectory.getTrajectoryPoint(0));

  int goal_index = trajectory.getNumPoints() - 1;
  trajectory.getTrajectoryPoint(goal_index) = trajectory.getTrajectoryPoint(0);
  sensor_msgs::JointState js;
  for (unsigned int i = 0; i < req.goal_constraints[0].joint_constraints.size(); i++)
  {
    js.name.push_back(req.goal_constraints[0].joint_constraints[i].joint_name);
    js.position.push_back(req.goal_constraints[0].joint_constraints[i].position);
    ROS_INFO_STREAM("Setting joint " << req.goal_constraints[0].joint_constraints[i].joint_name << " to position "
                                     << req.goal_constraints[0].joint_constraints[i].position);
  }
  jointStateToArray(planning_scene->getRobotModel(), js, req.group_name, trajectory.getTrajectoryPoint(goal_index));

  const moveit::core::JointModelGroup* model_group =
      planning_scene->getRobotModel()->getJointModelGroup(req.group_name);
  // fix the goal to move the shortest angular distance for wrap-around joints:
  for (size_t i = 0; i < model_group->getActiveJointModels().size(); i++)
  {
    const moveit::core::JointModel* model = model_group->getActiveJointModels()[i];
    const moveit::core::RevoluteJointModel* revolute_joint =
        dynamic_cast<const moveit::core::RevoluteJointModel*>(model);

    if (revolute_joint != NULL)
    {
      if (revolute_joint->isContinuous())
      {
        double start = (trajectory)(0, i);
        double end = (trajectory)(goal_index, i);
        ROS_INFO_STREAM("Start is " << start << " end " << end << " short " << shortestAngularDistance(start, end));
        (trajectory)(goal_index, i) = start + shortestAngularDistance(start, end);
      }
    }
  }

  // fill in an initial quintic spline trajectory
  trajectory.fillInMinJerk();

  // optimize!
  moveit::core::RobotState start_state(planning_scene->getCurrentState());
  moveit::core::robotStateMsgToRobotState(req.start_state, start_state);
  start_state.update();

  ros::WallTime create_time = ros::WallTime::now();
  ChompOptimizer optimizer(&trajectory, planning_scene, req.group_name, &params, start_state);
  if (!optimizer.isInitialized())
  {
    ROS_WARN_STREAM("Could not initialize optimizer");
    res.error_code.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED;
    return false;
  }
  ROS_INFO("Optimization took %f sec to create", (ros::WallTime::now() - create_time).toSec());
  optimizer.optimize();
  ROS_INFO("Optimization actually took %f sec to run", (ros::WallTime::now() - create_time).toSec());
  create_time = ros::WallTime::now();
  // assume that the trajectory is now optimized, fill in the output structure:

  ROS_INFO("Output trajectory has %d joints", trajectory.getNumJoints());

  res.trajectory.resize(1);

  for (size_t i = 0; i < model_group->getActiveJointModels().size(); i++)
  {
    res.trajectory[0].joint_trajectory.joint_names.push_back(model_group->getActiveJointModels()[i]->getName());
  }

  res.trajectory[0].joint_trajectory.header = req.start_state.joint_state.header;  // @TODO this is probably a hack

  // fill in the entire trajectory
  res.trajectory[0].joint_trajectory.points.resize(trajectory.getNumPoints());
  for (int i = 0; i < trajectory.getNumPoints(); i++)
  {
    res.trajectory[0].joint_trajectory.points[i].positions.resize(trajectory.getNumJoints());
    for (size_t j = 0; j < res.trajectory[0].joint_trajectory.points[i].positions.size(); j++)
    {
      res.trajectory[0].joint_trajectory.points[i].positions[j] = trajectory.getTrajectoryPoint(i)(j);
      if (i == trajectory.getNumPoints() - 1)
      {
        ROS_INFO_STREAM("Joint " << j << " " << res.trajectory[0].joint_trajectory.points[i].positions[j]);
      }
    }
    // Setting invalid timestamps.
    // Further filtering is required to set valid timestamps accounting for velocity and acceleration constraints.
    res.trajectory[0].joint_trajectory.points[i].time_from_start = ros::Duration(0.0);
  }

  ROS_INFO("Bottom took %f sec to create", (ros::WallTime::now() - create_time).toSec());
  ROS_INFO("Serviced planning request in %f wall-seconds, trajectory duration is %f",
           (ros::WallTime::now() - start_time).toSec(),
           res.trajectory[0].joint_trajectory.points[goal_index].time_from_start.toSec());
  res.error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
  res.processing_time.push_back((ros::WallTime::now() - start_time).toSec());
  return true;
}
}
<commit_msg>Fail without joint-space goal<commit_after>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2012, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/* Author: E. Gil Jones */

#include <ros/ros.h>
#include <chomp_motion_planner/chomp_planner.h>
#include <chomp_motion_planner/chomp_trajectory.h>
#include <chomp_motion_planner/chomp_optimizer.h>
#include <moveit/robot_state/conversions.h>
#include <moveit_msgs/MotionPlanRequest.h>

namespace chomp
{
ChompPlanner::ChompPlanner()
{
}

bool ChompPlanner::solve(const planning_scene::PlanningSceneConstPtr& planning_scene,
                         const moveit_msgs::MotionPlanRequest& req, const chomp::ChompParameters& params,
                         moveit_msgs::MotionPlanDetailedResponse& res) const
{
  if (!planning_scene)
  {
    ROS_ERROR_STREAM("No planning scene initialized.");
    res.error_code.val = moveit_msgs::MoveItErrorCodes::FAILURE;
    return false;
  }

  ros::WallTime start_time = ros::WallTime::now();
  ChompTrajectory trajectory(planning_scene->getRobotModel(), 3.0, .03, req.group_name);
  jointStateToArray(planning_scene->getRobotModel(), req.start_state.joint_state, req.group_name,
                    trajectory.getTrajectoryPoint(0));

  if(req.goal_constraints[0].joint_constraints.empty())
  {
    ROS_ERROR_STREAM("CHOMP only supports joint-space goals");
    res.error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_GOAL_CONSTRAINTS;
    return false;
  }
  int goal_index = trajectory.getNumPoints() - 1;
  trajectory.getTrajectoryPoint(goal_index) = trajectory.getTrajectoryPoint(0);
  sensor_msgs::JointState js;
  for (unsigned int i = 0; i < req.goal_constraints[0].joint_constraints.size(); i++)
  {
    js.name.push_back(req.goal_constraints[0].joint_constraints[i].joint_name);
    js.position.push_back(req.goal_constraints[0].joint_constraints[i].position);
    ROS_INFO_STREAM("Setting joint " << req.goal_constraints[0].joint_constraints[i].joint_name << " to position "
                                     << req.goal_constraints[0].joint_constraints[i].position);
  }
  jointStateToArray(planning_scene->getRobotModel(), js, req.group_name, trajectory.getTrajectoryPoint(goal_index));

  const moveit::core::JointModelGroup* model_group =
      planning_scene->getRobotModel()->getJointModelGroup(req.group_name);
  // fix the goal to move the shortest angular distance for wrap-around joints:
  for (size_t i = 0; i < model_group->getActiveJointModels().size(); i++)
  {
    const moveit::core::JointModel* model = model_group->getActiveJointModels()[i];
    const moveit::core::RevoluteJointModel* revolute_joint =
        dynamic_cast<const moveit::core::RevoluteJointModel*>(model);

    if (revolute_joint != NULL)
    {
      if (revolute_joint->isContinuous())
      {
        double start = (trajectory)(0, i);
        double end = (trajectory)(goal_index, i);
        ROS_INFO_STREAM("Start is " << start << " end " << end << " short " << shortestAngularDistance(start, end));
        (trajectory)(goal_index, i) = start + shortestAngularDistance(start, end);
      }
    }
  }

  // fill in an initial quintic spline trajectory
  trajectory.fillInMinJerk();

  // optimize!
  moveit::core::RobotState start_state(planning_scene->getCurrentState());
  moveit::core::robotStateMsgToRobotState(req.start_state, start_state);
  start_state.update();

  ros::WallTime create_time = ros::WallTime::now();
  ChompOptimizer optimizer(&trajectory, planning_scene, req.group_name, &params, start_state);
  if (!optimizer.isInitialized())
  {
    ROS_WARN_STREAM("Could not initialize optimizer");
    res.error_code.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED;
    return false;
  }
  ROS_INFO("Optimization took %f sec to create", (ros::WallTime::now() - create_time).toSec());
  optimizer.optimize();
  ROS_INFO("Optimization actually took %f sec to run", (ros::WallTime::now() - create_time).toSec());
  create_time = ros::WallTime::now();
  // assume that the trajectory is now optimized, fill in the output structure:

  ROS_INFO("Output trajectory has %d joints", trajectory.getNumJoints());

  res.trajectory.resize(1);

  for (size_t i = 0; i < model_group->getActiveJointModels().size(); i++)
  {
    res.trajectory[0].joint_trajectory.joint_names.push_back(model_group->getActiveJointModels()[i]->getName());
  }

  res.trajectory[0].joint_trajectory.header = req.start_state.joint_state.header;  // @TODO this is probably a hack

  // fill in the entire trajectory
  res.trajectory[0].joint_trajectory.points.resize(trajectory.getNumPoints());
  for (int i = 0; i < trajectory.getNumPoints(); i++)
  {
    res.trajectory[0].joint_trajectory.points[i].positions.resize(trajectory.getNumJoints());
    for (size_t j = 0; j < res.trajectory[0].joint_trajectory.points[i].positions.size(); j++)
    {
      res.trajectory[0].joint_trajectory.points[i].positions[j] = trajectory.getTrajectoryPoint(i)(j);
      if (i == trajectory.getNumPoints() - 1)
      {
        ROS_INFO_STREAM("Joint " << j << " " << res.trajectory[0].joint_trajectory.points[i].positions[j]);
      }
    }
    // Setting invalid timestamps.
    // Further filtering is required to set valid timestamps accounting for velocity and acceleration constraints.
    res.trajectory[0].joint_trajectory.points[i].time_from_start = ros::Duration(0.0);
  }

  ROS_INFO("Bottom took %f sec to create", (ros::WallTime::now() - create_time).toSec());
  ROS_INFO("Serviced planning request in %f wall-seconds, trajectory duration is %f",
           (ros::WallTime::now() - start_time).toSec(),
           res.trajectory[0].joint_trajectory.points[goal_index].time_from_start.toSec());
  res.error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
  res.processing_time.push_back((ros::WallTime::now() - start_time).toSec());
  return true;
}
}
<|endoftext|>


<commit_before>//========================================================
// Hazi feladat keret.
// A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// sorokon beluli reszben celszeru garazdalkodni, mert
// a tobbit ugyis toroljuk.
// A Hazi feladat csak ebben a fajlban lehet
// Tilos:
// - mast "beincludolni", illetve mas konyvtarat hasznalni
// - faljmuveleteket vegezni
//========================================================

#include <math.h>
#include <stdlib.h>

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
// MsWindows-on ez is kell
#include <windows.h>
#else // g++ nem fordit a stanard include-ok nelkul :-/
#include <string.h>
#endif // Win32 platform

#include <GL/gl.h>
#include <GL/glu.h>
// A GLUT-ot le kell tolteni: http://www.opengl.org/resources/libraries/glut/
#include <GL/glut.h>
#include <stdio.h>

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Innentol modosithatod...

//--------------------------------------------------------
// Nev: Vajna Miklos
// Neptun: AYU9RZ
//--------------------------------------------------------

#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))

class Vector {
public:
	float x, y, z;

	Vector(float x0, float y0, float z0) {
		x = x0;
		y = y0;
		z = z0;
	}

	Vector operator+(const Vector& v) {
		return Vector(x + v.x, y + v.y, z + v.z);
	}

	Vector operator*(float f) {
		return Vector(x * f, y * f, z * f);
	}
};

class Matrix {
public:
	float m[4][4];

	void Clear() {
		memset(&m[0][0], 0, sizeof(m));
	}

	void LoadIdentify() {
		Clear();
		m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1;
	}

	Vector operator*(const Vector& v) {
		float Xh = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3];
		float Yh = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3];
		float Zh = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3];
		float  h = m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3];

		return Vector(Xh/h, Yh/h, Zh/h);
	}

	float *GetArray() {
		return &m[0][0];
	}
};

enum {
	NOOP = 0,
	SCALE,
	ROTATE,
	SHIFT
};

int trans_state = NOOP;

enum {
	OPENGL = 0,
	MANUAL
};

int matrix_state = MANUAL;

// csak mert math.ht nemszabad ;-/
# define M_PI           3.14159265358979323846

const Vector* points[2][7];

Matrix* transs[4];

void onInitialization( ) {
	points[0][0] = new Vector(160, 20, 0);
	points[0][1] = new Vector(250, 80, 0);
	points[0][2] = new Vector(270, 20, 0);
	points[0][3] = new Vector(360, 80, 0);
	points[0][4] = new Vector(390, 20, 0);
	points[0][5] = new Vector(470, 80, 0);
	points[0][6] = new Vector(490, 20, 0);

	points[1][0] = new Vector(160, 120, 0);
	points[1][1] = new Vector(250, 180, 0);
	points[1][2] = new Vector(270, 120, 0);
	points[1][3] = new Vector(360, 180, 0);
	points[1][4] = new Vector(390, 120, 0);
	points[1][5] = new Vector(470, 180, 0);
	points[1][6] = new Vector(490, 120, 0);

	/*
	 * 1 0 0 0
	 * 0 1 0 0
	 * 0 0 1 0
	 * 0 0 0 1
	 */
	transs[NOOP] = new Matrix();
	transs[NOOP]->LoadIdentify();

	/*
	 * 0.5   0   0   0
	 *   0 0.5   0   0
	 *   0   0 0.5   0
	 *   0   0   0   1
	 */
	transs[SCALE] = new Matrix();
	transs[SCALE]->LoadIdentify();
	transs[SCALE]->m[0][0] = 0.5;
	transs[SCALE]->m[1][1] = 0.5;
	transs[SCALE]->m[2][2] = 0.5;

	/*
	 *  cos  sin    0    0
	 * -sin  cos    0    0
	 *    0    0    1    0
	 *    0    0    0    1
	 */
	float angle = M_PI/4;
	transs[ROTATE] = new Matrix();
	transs[ROTATE]->LoadIdentify();
	transs[ROTATE]->m[0][0] = cosf(angle);
	transs[ROTATE]->m[0][1] = -sinf(angle);
	transs[ROTATE]->m[1][0] = sinf(angle);
	transs[ROTATE]->m[1][1] = cosf(angle);

	/*
	 *  1  0  0  0
	 *  0  1  0  0
	 *  0  0  1  0
	 * px py pz  1
	 */
	transs[SHIFT] = new Matrix();
	transs[SHIFT]->LoadIdentify();
	transs[SHIFT]->m[1][3] = 100;
}

void onDisplay( ) {
	glClearColor(0.1f, 0.2f, 0.3f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glColor4d(0.9f, 0.8f, 0.7f, 1.0f);

	glMatrixMode(GL_PROJECTION);
	if (matrix_state == MANUAL) {
		glLoadIdentity();
	} else {
		glLoadMatrixf(transs[trans_state]->GetArray());
	}
	gluOrtho2D(0., 600., 0., 600.);
	for (int i = 0; i < ARRAY_SIZE(points); i++) {
		glBegin(GL_LINE_STRIP);
		for (int j = 0; j < ARRAY_SIZE(points[i]); j++) {
			if (matrix_state == MANUAL) {
				Vector v = *transs[trans_state] * *points[i][j];
				glVertex2d(v.x, v.y);
			} else {
				Vector v = *points[i][j];
				glVertex2d(v.x, v.y);
			}
		}
		glEnd();
	}

	// Buffercsere: rajzolas vege
	glFinish();
	glutSwapBuffers();
}

void onMouse(int button, int state, int x, int y) {
	// A GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON
	// ill. a GLUT_DOWN / GLUT_UP makrokat hasznald.
}

void onIdle( ) {
}

void onKeyboard(unsigned char key, int x, int y) {
	if (key != 's' && key != 'S')
		return;
	if (key == 's')
		matrix_state = MANUAL;
	else
		matrix_state = OPENGL;
	trans_state = (trans_state + 1) % 4;
	onDisplay();
}

// ...Idaig modosithatod
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

int main(int argc, char **argv) {
	glutInit(&argc, argv);
	glutInitWindowSize(600, 600);
	glutInitWindowPosition(100, 100);
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);

	glutCreateWindow("Grafika hazi feladat");

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	onInitialization();

	glutDisplayFunc(onDisplay);
	glutMouseFunc(onMouse);
	glutIdleFunc(onIdle);
	glutKeyboardFunc(onKeyboard);

	glutMainLoop();

	return 0;
}
<commit_msg>simplify, still buggy<commit_after>//========================================================
// Hazi feladat keret.
// A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// sorokon beluli reszben celszeru garazdalkodni, mert
// a tobbit ugyis toroljuk.
// A Hazi feladat csak ebben a fajlban lehet
// Tilos:
// - mast "beincludolni", illetve mas konyvtarat hasznalni
// - faljmuveleteket vegezni
//========================================================

#include <math.h>
#include <stdlib.h>

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
// MsWindows-on ez is kell
#include <windows.h>
#else // g++ nem fordit a stanard include-ok nelkul :-/
#include <string.h>
#endif // Win32 platform

#include <GL/gl.h>
#include <GL/glu.h>
// A GLUT-ot le kell tolteni: http://www.opengl.org/resources/libraries/glut/
#include <GL/glut.h>
#include <stdio.h>

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Innentol modosithatod...

//--------------------------------------------------------
// Nev: Vajna Miklos
// Neptun: AYU9RZ
//--------------------------------------------------------

#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))

class Vector {
public:
	float x, y, z;

	Vector(float x0, float y0, float z0) {
		x = x0;
		y = y0;
		z = z0;
	}

	Vector operator+(const Vector& v) {
		return Vector(x + v.x, y + v.y, z + v.z);
	}

	Vector operator*(float f) {
		return Vector(x * f, y * f, z * f);
	}
};

class Matrix {
public:
	float m[16];

	void Clear() {
		memset(&m[0], 0, sizeof(m));
	}

	void LoadIdentify() {
		Clear();
		m[0] = m[5] = m[10] = m[15] = 1;
	}

	Vector operator*(const Vector& v) {
		float Xh = m[0] * v.x + m[1] * v.y + m[2] * v.z + m[3];
		float Yh = m[4] * v.x + m[5] * v.y + m[6] * v.z + m[7];
		float Zh = m[8] * v.x + m[9] * v.y + m[10] * v.z + m[11];
		float  h = m[12] * v.x + m[13] * v.y + m[14] * v.z + m[15];

		return Vector(Xh/h, Yh/h, Zh/h);
	}

	float *GetArray() {
		return &m[0];
	}

	void Dump() {
		printf("%f\t%f\t%f\t%f\n", m[0], m[4], m[8], m[12]);
		printf("%f\t%f\t%f\t%f\n", m[1], m[5], m[9], m[13]);
		printf("%f\t%f\t%f\t%f\n", m[2], m[6], m[10], m[14]);
		printf("%f\t%f\t%f\t%f\n", m[3], m[7], m[11], m[15]);
		printf("--end--\n");
	}
};

enum {
	NOOP = 0,
	SCALE,
	ROTATE,
	SHIFT
};

int trans_state = NOOP;

enum {
	OPENGL = 0,
	MANUAL
};

int matrix_state = MANUAL;

// csak mert math.ht nemszabad ;-/
# define M_PI           3.14159265358979323846

const Vector* points[2][7];

Matrix* transs[4];

void onInitialization( ) {
	points[0][0] = new Vector(160, 20, 0);
	points[0][1] = new Vector(250, 80, 0);
	points[0][2] = new Vector(270, 20, 0);
	points[0][3] = new Vector(360, 80, 0);
	points[0][4] = new Vector(390, 20, 0);
	points[0][5] = new Vector(470, 80, 0);
	points[0][6] = new Vector(490, 20, 0);

	points[1][0] = new Vector(160, 120, 0);
	points[1][1] = new Vector(250, 180, 0);
	points[1][2] = new Vector(270, 120, 0);
	points[1][3] = new Vector(360, 180, 0);
	points[1][4] = new Vector(390, 120, 0);
	points[1][5] = new Vector(470, 180, 0);
	points[1][6] = new Vector(490, 120, 0);

	/*
	 * 1 0 0 0
	 * 0 1 0 0
	 * 0 0 1 0
	 * 0 0 0 1
	 */
	transs[NOOP] = new Matrix();
	transs[NOOP]->LoadIdentify();
	transs[NOOP]->Dump();

	/*
	 * 0.5   0   0   0
	 *   0 0.5   0   0
	 *   0   0 0.5   0
	 *   0   0   0   1
	 */
	transs[SCALE] = new Matrix();
	transs[SCALE]->LoadIdentify();
	transs[SCALE]->m[0] = 0.5;
	transs[SCALE]->m[5] = 0.5;
	transs[SCALE]->m[10] = 0.5;
	transs[SCALE]->Dump();

	/*
	 *  cos  sin    0    0
	 * -sin  cos    0    0
	 *    0    0    1    0
	 *    0    0    0    1
	 */
	float angle = M_PI/4;
	transs[ROTATE] = new Matrix();
	transs[ROTATE]->LoadIdentify();
	transs[ROTATE]->m[0] = cosf(angle);
	transs[ROTATE]->m[1] = -sinf(angle);
	transs[ROTATE]->m[4] = sinf(angle);
	transs[ROTATE]->m[5] = cosf(angle);
	transs[ROTATE]->Dump();

	/*
	 *  1  0  0  0
	 *  0  1  0  0
	 *  0  0  1  0
	 * px py pz  1
	 */
	transs[SHIFT] = new Matrix();
	transs[SHIFT]->LoadIdentify();
	transs[SHIFT]->m[7] = 100;
	transs[SHIFT]->Dump();
}

void onDisplay( ) {
	glClearColor(0.1f, 0.2f, 0.3f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glColor4d(0.9f, 0.8f, 0.7f, 1.0f);

	glMatrixMode(GL_PROJECTION);
	if (matrix_state == MANUAL) {
		glLoadIdentity();
	} else {
		glLoadMatrixf(transs[trans_state]->GetArray());
	}
	gluOrtho2D(0., 600., 0., 600.);
	for (int i = 0; i < ARRAY_SIZE(points); i++) {
		glBegin(GL_LINE_STRIP);
		for (int j = 0; j < ARRAY_SIZE(points[i]); j++) {
			if (matrix_state == MANUAL) {
				Vector v = *transs[trans_state] * *points[i][j];
				glVertex2d(v.x, v.y);
			} else {
				Vector v = *points[i][j];
				glVertex2d(v.x, v.y);
			}
		}
		glEnd();
	}

	// Buffercsere: rajzolas vege
	glFinish();
	glutSwapBuffers();
}

void onMouse(int button, int state, int x, int y) {
	// A GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON
	// ill. a GLUT_DOWN / GLUT_UP makrokat hasznald.
}

void onIdle( ) {
}

void onKeyboard(unsigned char key, int x, int y) {
	if (key != 's' && key != 'S')
		return;
	if (key == 's')
		matrix_state = MANUAL;
	else
		matrix_state = OPENGL;
	trans_state = (trans_state + 1) % 4;
	onDisplay();
}

// ...Idaig modosithatod
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

int main(int argc, char **argv) {
	glutInit(&argc, argv);
	glutInitWindowSize(600, 600);
	glutInitWindowPosition(100, 100);
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);

	glutCreateWindow("Grafika hazi feladat");

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();

	onInitialization();

	glutDisplayFunc(onDisplay);
	glutMouseFunc(onMouse);
	glutIdleFunc(onIdle);
	glutKeyboardFunc(onKeyboard);

	glutMainLoop();

	return 0;
}
<|endoftext|>


<commit_before>/*
* 17 - Check armstrong number
/

#include <iostream>
using namespace std;

int main()
{
    int n,temp,r,result = 0;
    cin>>n;
    temp = n;

    while(temp)
    {
        r = temp%10;
        result += r*r*r;
        temp /= 10;
    }

    if(result == n)
        cout<<"Armstrong number"<<endl;
    else
        cout<<"not an Armstrong number"<<endl;
    return 0;
}
<commit_msg>Update Armstrong.cpp<commit_after>/*
* 17 - Check armstrong number
*/

#include <iostream>
using namespace std;

int main()
{
    int n,temp,r,result = 0;
    cin>>n;
    temp = n;

    while(temp)
    {
        r = temp%10;
        result += r*r*r;
        temp /= 10;
    }

    if(result == n)
        cout<<"Armstrong number"<<endl;
    else
        cout<<"not an Armstrong number"<<endl;
    return 0;
}
<|endoftext|>


<commit_before>#ifndef RAZORTASK_CPP
#define RAZORTASK_CPP

/**
 * @file razortask.cpp
 * @brief implements the class Razortask
 * @author Christopher "VdoP" Regali
 */

#include "razortask.h"
#include "razorbartask.h"
#include "razor.h"
RazorPlugin* init(RazorBar* panel, QWidget* parent, const QString & name)
{
    RazorTaskManager * ret = new RazorTaskManager(panel, parent, name);
    Q_ASSERT(ret);
    return ret;
}

/**
 * @brief constructor
 */
RazorTask::RazorTask(Window _id, int _screen)
{
    client=_id;
    onScreen = _screen;
    hasIcon = false;
    qDebug() << "getting name";
    title=Razor::getInstance().get_Xfitman()->getName(client);
    qDebug() << "getting icon";
    if (Razor::getInstance().get_Xfitman()->getClientIcon(client,clientIcon))
        hasIcon = true;
    qDebug() << "getting desktop";
    desktop=Razor::getInstance().get_Xfitman()->getWindowDesktop(_id);
    qDebug() << "getting hidden";
    hidden=Razor::getInstance().get_Xfitman()->isHidden(_id);
}

/**
 * @brief returns the task-title
 */
QString RazorTask::getTitle()
{
    title = Razor::getInstance().get_Xfitman()->getName(client);
    return title;
}

/**
 * @brief raises the window
 */
void RazorTask::raiseMe()
{
    Razor::getInstance().get_Xfitman()->raiseWindow(client);
}

/**
 * @brief requests Xfitman to toggle minimalize-flag for this tasks window!
 */
void RazorTask::toogleMin()
{
    hidden = Razor::getInstance().get_Xfitman()->isHidden(client);
    qDebug() << "Razortask::toggleMin, hidden:" << hidden;
    Razor::getInstance().get_Xfitman()->setClientStateFlag(client,"net_wm_state_hidden",2);
    hidden = !hidden;
    qDebug() << "Razortask::toggleMin, hidden:" << hidden;
    if (!hidden)
        Razor::getInstance().get_Xfitman()->raiseWindow(client);
}

/**
 * @brief returns if the window has hiddenflag turned on
 */
bool RazorTask::isHidden()
{
    hidden = Razor::getInstance().get_Xfitman()->isHidden(client);
    return hidden;
}

/**
 * @brief returns true if task has inputfocus
 */
bool RazorTask::isActive()
{
    return (Razor::getInstance().get_Xfitman()->getActiveAppWindow()==client);
}

/**
 * @brief requests Xfitman to set the window to fullscreen (UNTESTED!)
 */
void RazorTask::setFullscreen()
{
    //first remove hidden-flag so make us visible / unminimize
    Razor::getInstance().get_Xfitman()->setClientStateFlag(client,"net_wm_state_hidden",0);
    //then add the fullscreen-flag
    Razor::getInstance().get_Xfitman()->setClientStateFlag(client,"net_wm_state_fullscreen",1);
}

/**
 * @brief destructor
 */
RazorTask::~RazorTask()
{

}

/**
 * @brief gets the client icon, if we have one!
 */
bool RazorTask::getIcon(QPixmap& _pixm)
{
    qDebug() << "Has this client an Icon?" <<  hasIcon << title;
    if (hasIcon)
        _pixm = clientIcon;
    return hasIcon;
}

/**
 * @brief handles the X events and sets client - gui states
 */
bool RazorTaskManager::handleEvent(XEvent* _event)
{
    //destroy or create windows? thats whats interesting.. we dont care about the rest!
    //so we just fetch "propertynotify" events
    if (_event->type == PropertyNotify)
        updateMap();
    return false;
}

/**
 * @brief constructor
 */
RazorTaskManager::RazorTaskManager(RazorBar * panel, QWidget * parent, const QString & name)
    : RazorPlugin(panel, parent, name)
{
    qDebug() << "Razortaskmanager init";
    //now we setup our gui element
    gui = new RazorBarTask(this, panel);
    mainLayout()->addWidget(gui);

    //now we need an updated map for the clients running
    //updateMap();

    qDebug() << "Razortaskmanager updateMap done";
    //now we add our taskbar to the panel
    // it's aligned to left and it should occypy all free space
    // in the panel.
    // TODO: it doesn't work with sizeHints and with the stretch =1 too...

//    Razor::getInstance().get_gui()->addWidget(gui,_bar, 1, Qt::AlignLeft);

    qDebug() << "Razortaskmanager added widget";
    //we need the events so we can process the tasks correctly

    Razor::getInstance().get_events()->registerCallback(this);

    qDebug() << "Razortaskmanager callback registered";

}
/**
 * @brief updates our clientmap
 */
void RazorTaskManager::updateMap()
{
    QList<Window>* tmp = Razor::getInstance().get_Xfitman()->getClientlist();

    //first we need to get rid of tasks that got closed
    QMapIterator<Window,RazorTask*> iter(clientList);
    while (iter.hasNext())
    {
        iter.next();
        if (!tmp->contains(iter.key()))
        {
            //  qDebug() << "DELTHIS!";
            //get the pointer
            RazorTask* deltask = iter.value();
            //remove the link from the list
            clientList.remove(iter.key());
            //free the heap
            delete deltask;
        }
    }

    //now we got the window-ids and we got the count so we get through all of them
    for (int i = 0; i < tmp->count(); i++)
    {
        //add new clients to the list making new entries for the new windows
        if (!clientList.contains(tmp->at(i)) && Razor::getInstance().get_Xfitman()->acceptWindow(tmp->at(i)))
        {
            RazorTask* rtask = new RazorTask(tmp->at(i),Razor::getInstance().get_Xfitman()->getWindowDesktop(tmp->at(i)));
            qDebug() << "title: " <<rtask->getTitle();
            clientList[tmp->at(i)]=rtask;
        }
    }

    delete tmp;

    //then update the stuff in our gui
    gui->updateTasks(&clientList);
    gui->updateFocus();
}

int RazorTaskManager::widthForHeight(int h)
{
    return gui->width();
}
int RazorTaskManager::heightForWidth(int w)
{
    return gui->height();
}
RazorPlugin::RazorPluginSizing RazorTaskManager::sizePriority()
{
    return RazorPlugin::Expanding;
}

/**
 * @brief destructor
 */
RazorTaskManager::~RazorTaskManager()
{
    for (int i = 0; i < clientList.values().count(); i++)
        delete clientList.values().at(i);
}

#endif
<commit_msg>forgotten refactored getClientList<commit_after>#ifndef RAZORTASK_CPP
#define RAZORTASK_CPP

/**
 * @file razortask.cpp
 * @brief implements the class Razortask
 * @author Christopher "VdoP" Regali
 */

#include "razortask.h"
#include "razorbartask.h"
#include "razor.h"
RazorPlugin* init(RazorBar* panel, QWidget* parent, const QString & name)
{
    RazorTaskManager * ret = new RazorTaskManager(panel, parent, name);
    Q_ASSERT(ret);
    return ret;
}

/**
 * @brief constructor
 */
RazorTask::RazorTask(Window _id, int _screen)
{
    client=_id;
    onScreen = _screen;
    hasIcon = false;
    qDebug() << "getting name";
    title=Razor::getInstance().get_Xfitman()->getName(client);
    qDebug() << "getting icon";
    if (Razor::getInstance().get_Xfitman()->getClientIcon(client,clientIcon))
        hasIcon = true;
    qDebug() << "getting desktop";
    desktop=Razor::getInstance().get_Xfitman()->getWindowDesktop(_id);
    qDebug() << "getting hidden";
    hidden=Razor::getInstance().get_Xfitman()->isHidden(_id);
}

/**
 * @brief returns the task-title
 */
QString RazorTask::getTitle()
{
    title = Razor::getInstance().get_Xfitman()->getName(client);
    return title;
}

/**
 * @brief raises the window
 */
void RazorTask::raiseMe()
{
    Razor::getInstance().get_Xfitman()->raiseWindow(client);
}

/**
 * @brief requests Xfitman to toggle minimalize-flag for this tasks window!
 */
void RazorTask::toogleMin()
{
    hidden = Razor::getInstance().get_Xfitman()->isHidden(client);
    qDebug() << "Razortask::toggleMin, hidden:" << hidden;
    Razor::getInstance().get_Xfitman()->setClientStateFlag(client,"net_wm_state_hidden",2);
    hidden = !hidden;
    qDebug() << "Razortask::toggleMin, hidden:" << hidden;
    if (!hidden)
        Razor::getInstance().get_Xfitman()->raiseWindow(client);
}

/**
 * @brief returns if the window has hiddenflag turned on
 */
bool RazorTask::isHidden()
{
    hidden = Razor::getInstance().get_Xfitman()->isHidden(client);
    return hidden;
}

/**
 * @brief returns true if task has inputfocus
 */
bool RazorTask::isActive()
{
    return (Razor::getInstance().get_Xfitman()->getActiveAppWindow()==client);
}

/**
 * @brief requests Xfitman to set the window to fullscreen (UNTESTED!)
 */
void RazorTask::setFullscreen()
{
    //first remove hidden-flag so make us visible / unminimize
    Razor::getInstance().get_Xfitman()->setClientStateFlag(client,"net_wm_state_hidden",0);
    //then add the fullscreen-flag
    Razor::getInstance().get_Xfitman()->setClientStateFlag(client,"net_wm_state_fullscreen",1);
}

/**
 * @brief destructor
 */
RazorTask::~RazorTask()
{

}

/**
 * @brief gets the client icon, if we have one!
 */
bool RazorTask::getIcon(QPixmap& _pixm)
{
    qDebug() << "Has this client an Icon?" <<  hasIcon << title;
    if (hasIcon)
        _pixm = clientIcon;
    return hasIcon;
}

/**
 * @brief handles the X events and sets client - gui states
 */
bool RazorTaskManager::handleEvent(XEvent* _event)
{
    //destroy or create windows? thats whats interesting.. we dont care about the rest!
    //so we just fetch "propertynotify" events
    if (_event->type == PropertyNotify)
        updateMap();
    return false;
}

/**
 * @brief constructor
 */
RazorTaskManager::RazorTaskManager(RazorBar * panel, QWidget * parent, const QString & name)
    : RazorPlugin(panel, parent, name)
{
    qDebug() << "Razortaskmanager init";
    //now we setup our gui element
    gui = new RazorBarTask(this, panel);
    mainLayout()->addWidget(gui);

    //now we need an updated map for the clients running
    //updateMap();

    qDebug() << "Razortaskmanager updateMap done";
    //now we add our taskbar to the panel
    // it's aligned to left and it should occypy all free space
    // in the panel.
    // TODO: it doesn't work with sizeHints and with the stretch =1 too...

//    Razor::getInstance().get_gui()->addWidget(gui,_bar, 1, Qt::AlignLeft);

    qDebug() << "Razortaskmanager added widget";
    //we need the events so we can process the tasks correctly

    Razor::getInstance().get_events()->registerCallback(this);

    qDebug() << "Razortaskmanager callback registered";

}
/**
 * @brief updates our clientmap
 */
void RazorTaskManager::updateMap()
{
    QList<Window> tmp = Razor::getInstance().get_Xfitman()->getClientList();

    //first we need to get rid of tasks that got closed
    QMapIterator<Window,RazorTask*> iter(clientList);
    while (iter.hasNext())
    {
        iter.next();
        if (!tmp.contains(iter.key()))
        {
            //  qDebug() << "DELTHIS!";
            //get the pointer
            RazorTask* deltask = iter.value();
            //remove the link from the list
            clientList.remove(iter.key());
            //free the heap
            delete deltask;
        }
    }

    //now we got the window-ids and we got the count so we get through all of them
    for (int i = 0; i < tmp.count(); i++)
    {
        //add new clients to the list making new entries for the new windows
        if (!clientList.contains(tmp.at(i)) && Razor::getInstance().get_Xfitman()->acceptWindow(tmp.at(i)))
        {
            RazorTask* rtask = new RazorTask(tmp.at(i),Razor::getInstance().get_Xfitman()->getWindowDesktop(tmp.at(i)));
            qDebug() << "title: " <<rtask->getTitle();
            clientList[tmp.at(i)]=rtask;
        }
    }

    //then update the stuff in our gui
    gui->updateTasks(&clientList);
    gui->updateFocus();
}

int RazorTaskManager::widthForHeight(int h)
{
    return gui->width();
}
int RazorTaskManager::heightForWidth(int w)
{
    return gui->height();
}
RazorPlugin::RazorPluginSizing RazorTaskManager::sizePriority()
{
    return RazorPlugin::Expanding;
}

/**
 * @brief destructor
 */
RazorTaskManager::~RazorTaskManager()
{
    for (int i = 0; i < clientList.values().count(); i++)
        delete clientList.values().at(i);
}

#endif
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>

#include <boost/make_shared.hpp>

#include <gtest/gtest.h>

#include <osquery/dispatcher.h>

#include "osquery/events/kernel.h"

namespace osquery {

class KernelCommunicationTests : public testing::Test {
  void TearDown() override {
    Dispatcher::stopServices();
    Dispatcher::joinServices();
  }
};

#ifdef KERNEL_TEST
class KernelProducerRunnable : public InternalRunnable {
 public:
  explicit KernelProducerRunnable(unsigned int events_to_produce,
                                  unsigned int event_type)
      : events_to_produce_(events_to_produce), event_type_(event_type) {}

  virtual void start() {
    int fd = open(kKernelDevice.c_str(), O_RDWR);
    if (fd >= 0) {
      for (unsigned int i = 0; i < events_to_produce_; i++) {
        ioctl(fd, OSQUERY_IOCTL_TEST, &event_type_);
      }

      close(fd);
    }
  }

 private:
  unsigned int events_to_produce_;
  unsigned int event_type_;
};

TEST_F(KernelCommunicationTests, test_communication) {
  unsigned int num_threads = 20;
  unsigned int events_per_thread = 100000;
  unsigned int drops = 0;
  unsigned int reads = 0;

  CQueue queue(kKernelDevice, 8 * (1 << 20));

  auto& dispatcher = Dispatcher::instance();

  for (unsigned int c = 0; c < num_threads; ++c) {
    dispatcher.addService(
        std::make_shared<KernelProducerRunnable>(events_per_thread, c % 2));
  }

  osquery_event_t event;
  osquery::CQueue::event* event_buf = nullptr;
  unsigned int tasks = 0;
  do {
    tasks = dispatcher.serviceCount();
    drops += queue.kernelSync(OSQUERY_OPTIONS_NO_BLOCK);
    unsigned int max_before_sync = 2000;
    while (max_before_sync > 0 && (event = queue.dequeue(&event_buf))) {
      switch (event) {
      case OSQUERY_TEST_EVENT_0:
      case OSQUERY_TEST_EVENT_1:
        reads++;
        break;
      default:
        throw std::runtime_error("Uh oh. Unknown event.");
      }
      max_before_sync--;
    }
  } while (tasks > 0);

  EXPECT_EQ(num_threads * events_per_thread, reads + drops);
}
#endif // KERNEL_TEST
}
<commit_msg>Allow the non-blocking kernel-test publisher to drop 5% (#2336)<commit_after>/*
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>

#include <boost/make_shared.hpp>

#include <gtest/gtest.h>

#include <osquery/dispatcher.h>

#include "osquery/events/kernel.h"

namespace osquery {

class KernelCommunicationTests : public testing::Test {
  void TearDown() override {
    Dispatcher::stopServices();
    Dispatcher::joinServices();
  }
};

#ifdef KERNEL_TEST
class KernelProducerRunnable : public InternalRunnable {
 public:
  explicit KernelProducerRunnable(unsigned int events_to_produce,
                                  unsigned int event_type)
      : events_to_produce_(events_to_produce), event_type_(event_type) {}

  virtual void start() {
    int fd = open(kKernelDevice.c_str(), O_RDWR);
    if (fd >= 0) {
      for (unsigned int i = 0; i < events_to_produce_; i++) {
        ioctl(fd, OSQUERY_IOCTL_TEST, &event_type_);
      }

      close(fd);
    }
  }

 private:
  unsigned int events_to_produce_;
  unsigned int event_type_;
};

TEST_F(KernelCommunicationTests, test_communication) {
  unsigned int num_threads = 20;
  unsigned int events_per_thread = 100000;
  unsigned int drops = 0;
  unsigned int reads = 0;

  CQueue queue(kKernelDevice, 8 * (1 << 20));

  auto& dispatcher = Dispatcher::instance();

  for (unsigned int c = 0; c < num_threads; ++c) {
    dispatcher.addService(
        std::make_shared<KernelProducerRunnable>(events_per_thread, c % 2));
  }

  osquery_event_t event;
  osquery::CQueue::event* event_buf = nullptr;
  unsigned int tasks = 0;
  do {
    tasks = dispatcher.serviceCount();
    drops += queue.kernelSync(OSQUERY_OPTIONS_NO_BLOCK);
    unsigned int max_before_sync = 2000;
    while (max_before_sync > 0 && (event = queue.dequeue(&event_buf))) {
      switch (event) {
      case OSQUERY_TEST_EVENT_0:
      case OSQUERY_TEST_EVENT_1:
        reads++;
        break;
      default:
        throw std::runtime_error("Uh oh. Unknown event.");
      }
      max_before_sync--;
    }
  } while (tasks > 0);

  auto total_events = reads + drops;
  auto expected_events = num_threads * events_per_thread;

  // Since the sync is opened non-blocking we allow a 5% drop rate.
  EXPECT_GT(total_events, expected_events * 0.95);
  EXPECT_LE(total_events, expected_events);
}
#endif // KERNEL_TEST
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;

int main()
{
    int n;
    cin>>n;
    bool (*a) = new bool[n+1];
    memset(a,true,sizeof(bool)*(n+1));
    for (int i = 2; i <= sqrt(n); i++)
        if (a[i]) for (int j = i; j*i <= n; j++) a[j*i] = false;
    int (*p) = new int[n];int countp = 0;
    for (int k = 2; k <= n; k++)
        if (a[k]) {p[countp] = k;countp++;}
    int countn = 0;
    for(int l = 0; l < countp; l++)
        if(p[l+1] - p[l] == 2) countn++;
    cout<<countn<<endl;
    delete [] a;delete [] p;
}
<commit_msg>Clean up.<commit_after>#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;

int main()
{
    int n;
    cin>>n;
    bool (*a) = new bool[n+1];
    memset(a,true,sizeof(bool)*(n+1));
    for (int i = 2; i <= sqrt(n); i++)
        if (a[i]) for(int j = i; j*i <= n; j++) a[j*i] = false;
    int first = 0;int last = 0;int countn = 0;
    for(int i = 2; i < n + 1; i++)
    {
        if(a[i])
        {
            if(!first) first = i;
            else
            {
                if(last) first = last;
                last = i;
                if(last - first == 2) countn++;
            }
        }
    }
    cout<<countn<<endl;
    delete [] a;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <limits>
#include <string>
using namespace std;
int main()
{
	string answer,temp;int n,countn;
	cin>>answer>>n;
	cin.clear();
	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	countn = 0;
	for(;(getline(cin,temp)) && (temp != "#");)
	{
		countn++;
		if(countn < n)
		{
			if(temp == answer)
			{
				cout<<"Welcome in"<<endl;
				break;
			}
			else
			{
                cout<<"Wrong password: "<<temp<<endl;
                continue;
			}
		}
		else if(countn = n)
		{
			if(temp == answer)
			{
				cout<<"Welcome in"<<endl;
				break;
			}
			else
			{
                cout<<"Wrong password: "<<temp<<endl<<"Account locked"<<endl;
				break;
			}
		}
		else break;
	}
}
<commit_msg>Update 1067.cpp<commit_after>#include <iostream>
#include <limits>
#include <string>
using namespace std;
int main()
{
	string answer,temp;int n,countn;
	cin>>answer>>n;
	cin.clear();
	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	countn = 0;
	for(;(getline(cin,temp)) && (temp != "#");)
	{
		countn++;
		if(countn < n)
		{
			if(temp == answer)
			{
				cout<<"Welcome in"<<endl;
				break;
			}
			else
			{
                		cout<<"Wrong password: "<<temp<<endl;
                		continue;
			}
		}
		else if(countn == n)
		{
			if(temp == answer)
			{
				cout<<"Welcome in"<<endl;
				break;
			}
			else
			{
                		cout<<"Wrong password: "<<temp<<endl<<"Account locked"<<endl;
				break;
			}
		}
		else break;
	}
}
<|endoftext|>