code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*******************************************************************************
*
* Potato Engine
*
* Copyright (C) 2007-2009 Remi Papillie, Jonathan Giroux
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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 program. If not, see <http://www.gnu.org/licenses/>.
*
******************************************************************************/
#ifndef __PE_MAT44_HPP__
#define __PE_MAT44_HPP__
#include <pe/common.hpp>
#include <pe/math/Vec3.hpp>
#include <pe/math/Mat33.hpp>
namespace pe {
namespace math {
/**
* \class Mat33
* \brief 4x4 Matrix
* \author Remi Papillie
* \author Jonathan Giroux
*
* This class represents a 4x4 matrix. The values are stored as 32-bits floats.
* Along with other math classes, this class shows as public its coordinate
* members, to let the user directly access those data.
*/
class Mat44
{
public:
//! \brief The 16 values
f32 v[16];
/**
* \brief Construct the identity matrix
*/
Mat44();
/**
* \brief Alternate constructor
*
* Cell values (in a row-major order) are to be supplied as arguments.
*/
Mat44(f32 x0, f32 x1, f32 x2, f32 x3, f32 x4, f32 x5, f32 x6, f32 x7, f32 x8, f32 x9, f32 x10, f32 x11, f32 x12, f32 x13, f32 x14, f32 x15);
/**
* \brief Alternate constructor
*
* Cell values (in a row-major order) are to be supplied as an array.
*/
Mat44(f32 values[16]);
/**
* \brief Construct a matrix with its top-left values taken from a 3x3 matrix
* \param m the minor initialization matrix
*
* The remaining values (last row and last column) are zeroed out.
*/
Mat44(const Mat33& m);
/**
* \brief Addition of two matrices (per-component)
*/
Mat44 operator +(const Mat44& m) const;
/**
* \brief Addition of two matrices (per-component)
*/
Mat44& operator +=(const Mat44& m);
/**
* \brief Unary minus operator
*/
Mat44 operator -() const;
/**
* \brief Subtraction of two matrices (per-component)
*/
Mat44 operator -(const Mat44& m) const;
/**
* \brief Subtraction of two matrices (per-component)
*/
Mat44& operator -=(const Mat44& m);
/**
* \brief Multiplication by a real number
*/
Mat44 operator *(f32 k) const;
Mat44& operator *=(f32 k);
friend Mat44 operator *(f32 k, const Mat44& m);
/**
* \brief Usual 4x4 matrix multiplication
*/
Mat44 operator *(const Mat44& m) const;
/**
* \brief Usual 4x4 matrix multiplication
*/
Mat44& operator *=(const Mat44& m);
/**
* \brief Matrix determinant
*/
f32 determinant() const;
/**
* \brief Matrix transpose
*/
Mat44 transpose() const;
/**
* \brief Matrix inverse
*/
Mat44 inverse() const;
/**
* \brief Rotation matrix in homogeneous coordinates
* \return rotation matrix
*/
Mat33 rotationMatrix() const;
/**
* \brief Translation vector in homogeneous coordinates
* \return translation vector
*/
Vec3 translationVector() const;
/**
* \brief Text output
*/
friend std::ostream& operator <<(std::ostream& out, const Mat44& m);
};
} // math namespace
} // pe namespace
#include <pe/math/Mat44.inline.hpp>
#endif // __PE_MAT44_HPP__
| tectronics/potatoengine.testing | include/pe/math/Mat44.hpp | C++ | lgpl-2.1 | 3,927 |
/*
* $Id$
* ====================================================================
* AsoBrain 3D Toolkit
* Copyright (C) 1999-2012 Peter S. Heijnen
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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
* ====================================================================
*/
package ab.j3d.control;
import java.awt.*;
import java.util.*;
import java.util.List;
import ab.j3d.geom.*;
import ab.j3d.model.*;
import ab.j3d.view.*;
import ab.j3d.view.control.planar.*;
import org.jetbrains.annotations.*;
/**
* A control for manipulating a content node based on its bounding box.
*
* <p>
* The following diagram shows a fold-out of the box, including the sides and
* edges.
* <pre>
* +--+------------+--+
* | | Y+ | |
* +--+------------+--+
* | | | |
* |X-| Top |X+|
* | | (Z+) | |
* +--+------------+--+
* | | Y- | |
* +--+------------+--+--+------------+--+--+------------+--+--+------------+--+
* | | Y+ | | | Y+ | | | Y+ | | | Y+ | |
* +--+------------+--+--+------------+--+--+------------+--+--+------------+--+
* | | | | | | | | | | | | |
* |X-| Left |X+|X-| Front |X+|X-| Right |X+|X-| Rear |X+|
* | | (X-) | | | (Y-) | | | (X+) | | | (Y+) | |
* +--+------------+--+--+------------+--+--+------------+--+--+------------+--+
* | | Y- | | | Y- | | | Y- | | | Y- | |
* +---------------+--+--+------------+--+--+------------+--+--+------------+--+
* | | Y+ | |
* +--+------------+--+
* | | | |
* |X-| Bottom |X+|
* | | (Z-) | |
* +--+------------+--+
* | | Y- | |
* +--+------------+--+
* </pre>
*
* @author G. Meinders
* @version $Revision$ $Date$
*/
public class BoxControl
implements ContentNodeControl, ViewOverlay
{
/**
* The (six) sides of the box.
*/
private final List<BoxSide> _sides;
/**
* Side that is currently being dragged.
*/
private BoxSide _activeSide = null;
/**
* Listener to be used as a fallback, when no part of the box has captured
* an event.
*/
private ContentNodeControl _listener = null;
/**
* Precedence of the control relative to other content node controls.
*/
private int _precedence = 0;
/**
* An arbitrary object that will be included in the {@link #toString} of
* the control for easily recognizing a particular control.
*/
private Object _tag = null;
/**
* Whether the mouse is currently positioned inside the box.
*/
private boolean _hover;
/**
* Construct new control.
*
* @param node Content node to manipulate.
*/
public BoxControl( final ContentNode node )
{
this( node, false );
}
/**
* Construct new control.
*
* @param node Content node to manipulate.
* @param insideOfBox <code>true</code> for an inverted box,
* controlled from the inside.
*/
public BoxControl( final ContentNode node, final boolean insideOfBox )
{
final List<BoxSide> sides = new ArrayList<BoxSide>( BoxSide.Side.values().length );
for ( final BoxSide.Side side : BoxSide.Side.values() )
{
sides.add( new ContentNodeBoxSide( node, side, insideOfBox ) );
}
_sides = sides;
}
public int getPrecedence()
{
return _precedence;
}
/**
* Sets the precedence of the control.
*
* @param precedence Precedence to be set.
*/
public void setPrecedence( final int precedence )
{
_precedence = precedence;
}
/**
* Returns the object used to tag this control.
*
* @return Tag object.
*/
@Nullable
public Object getTag()
{
return _tag;
}
/**
* Sets an arbitrary object used to tag this control (e.g. for debugging).
*
* @param tag Tag object.
*/
public void setTag( @Nullable final Object tag )
{
_tag = tag;
}
/**
* Returns the control that handles events for the entire box, if no sides
* or edges handle a given event.
*
* @return Control for the entire box.
*/
public ContentNodeControl getListener()
{
return _listener;
}
/**
* Sets a control to handle events for the entire box, if no sides or edges
* handle a given event.
*
* @param listener Control to be set.
*/
public void setListener( final ContentNodeControl listener )
{
_listener = listener;
}
/**
* Sets the delegate to be used for the specified side of the box.
*
* @param side Side of the box.
* @param listener Delegate to be set.
*/
public void setListener( final BoxSide.Side side, final BoxControlDelegate listener )
{
setListener( side, listener, BoxSide.BehaviorHint.NONE );
}
/**
* Sets the delegate to be used for the specified side of the box.
* For convenience, this method also sets the side's behavior hint.
*
* @param side Side of the box.
* @param listener Delegate to be set.
* @param behaviorHint Behavior hint to be set.
*/
public void setListener( final BoxSide.Side side, final BoxControlDelegate listener, final BoxSide.BehaviorHint behaviorHint )
{
final BoxSide sideObject = getSide( side );
sideObject.setListener( listener );
sideObject.setBehaviorHint( behaviorHint );
}
/**
* Sets the delegate to be used for the specified side of the box.
* For convenience, this method also sets the side's behavior.
*
* @param side Side of the box.
* @param listener Delegate to be set.
* @param behavior Behavior to be set.
*/
public void setListener( final BoxSide.Side side, final BoxControlDelegate listener, final BoxSide.Behavior behavior )
{
setListener( side, listener, behavior, BoxSide.BehaviorHint.NONE );
}
/**
* Sets the delegate to be used for the specified side of the box.
* For convenience, this method also sets the side's behavior (and hint).
*
* @param side Side of the box.
* @param listener Delegate to be set.
* @param behavior Behavior to be set.
* @param behaviorHint Behavior hint to be set.
*/
public void setListener( final BoxSide.Side side, final BoxControlDelegate listener, final BoxSide.Behavior behavior, final BoxSide.BehaviorHint behaviorHint )
{
final BoxSide sideObject = getSide( side );
sideObject.setListener( listener );
sideObject.setBehavior( behavior );
sideObject.setBehaviorHint( behaviorHint );
}
/**
* Returns a side of the box.
*
* @param side Specifies a side.
*
* @return Object representing the specified side.
*/
public BoxSide getSide( @NotNull final BoxSide.Side side )
{
return _sides.get( side.ordinal() );
}
public Double getDepth( final Ray3D pointerRay )
{
Double result = null;
final boolean entireBoxHasListener = ( _listener != null );
for ( final BoxSide side : _sides )
{
if ( side.isEnabled() || entireBoxHasListener )
{
final Double reference = side.getDepth( pointerRay );
if ( reference != null )
{
if ( ( result == null ) || ( reference < result ) )
{
result = reference;
}
}
}
}
return result;
}
public void mouseMoved( final ControlInputEvent event, final ContentNode contentNode )
{
boolean hover = false;
for ( final BoxSide side : _sides )
{
side.mouseMoved( event, contentNode );
hover |= side.isHover();
}
_hover = hover;
if ( _listener != null )
{
_listener.mouseMoved( event, contentNode );
}
}
/**
* Returns whether the mouse is hovering above the box.
*
* @return {@code true} if the mouse is hovering above the box.
*/
public boolean isHover()
{
return _hover;
}
public boolean mousePressed( final ControlInputEvent event, final ContentNode contentNode )
{
boolean result = false;
if ( event.isMouseButton1Down() )
{
for ( final BoxSide side : _sides )
{
if ( side.isEnabled() && side.mousePressed( event, contentNode ) )
{
_activeSide = side;
result = true;
break;
}
}
if ( !result )
{
final ContentNodeControl listener = _listener;
if ( listener != null )
{
result = listener.mousePressed( event, contentNode );
}
}
}
return result;
}
public boolean mouseDragged( final ControlInputEvent event, final ContentNode contentNode )
{
boolean result = false;
final BoxSide side = _activeSide;
if ( side != null )
{
result = side.mouseDragged( event, contentNode );
}
else
{
final ContentNodeControl listener = _listener;
if ( listener != null )
{
result = listener.mouseDragged( event, contentNode );
}
}
return result;
}
public void mouseReleased( final ControlInputEvent event, final ContentNode contentNode )
{
final BoxSide activeSide = _activeSide;
if ( activeSide != null )
{
activeSide.mouseReleased( event, contentNode );
_activeSide = null;
}
else
{
final ContentNodeControl listener = _listener;
if ( listener != null )
{
listener.mouseReleased( event, contentNode );
}
}
}
public void mouseEntered( final ControlInputEvent event, final ContentNode contentNode )
{
boolean hover = false;
for ( final BoxSide side : _sides )
{
side.mouseEntered( event, contentNode );
hover |= side.isHover();
}
_hover = hover;
if ( _listener != null )
{
_listener.mouseEntered( event, contentNode );
}
}
public void mouseExited( final ControlInputEvent event, final ContentNode contentNode )
{
for ( final BoxSide side : _sides )
{
side.mouseExited( event, contentNode );
}
_hover = false;
if ( _listener != null )
{
_listener.mouseExited( event, contentNode );
}
}
public void paintOverlay( final View3D view, final Graphics2D g )
{
for ( final BoxSide side : _sides )
{
side.paintOverlay( view, g );
}
}
public void addView( final View3D view )
{
}
public void removeView( final View3D view )
{
}
/**
* Configures the edges on all sides of the box to use the specified
* listeners. This can be used, for example, to easily create a control to
* resize a box by dragging edges in the desired direction.
*
* @param x1 Listener for edges on the left side of the box.
* @param x2 Listener for edges on the right side of the box.
* @param y1 Listener for edges on the front side of the box.
* @param y2 Listener for edges on the rear side of the box.
* @param z1 Listener for edges on the bottom side of the box.
* @param z2 Listener for edges on the top side of the box.
*/
public void setupEdges( @Nullable final BoxControlDelegate x1, @Nullable final BoxControlDelegate x2, @Nullable final BoxControlDelegate y1, @Nullable final BoxControlDelegate y2, @Nullable final BoxControlDelegate z1, @Nullable final BoxControlDelegate z2 )
{
final BoxSide top = getSide( BoxSide.Side.TOP );
top.setEdgeBehavior( BoxSide.Behavior.PLANE );
top.setEdgeListenerX1( x1 );
top.setEdgeListenerX2( x2 );
top.setEdgeListenerY1( y1 );
top.setEdgeListenerY2( y2 );
final BoxSide bottom = getSide( BoxSide.Side.BOTTOM );
bottom.setEdgeBehavior( BoxSide.Behavior.PLANE );
bottom.setEdgeListenerX1( x2 );
bottom.setEdgeListenerX2( x1 );
bottom.setEdgeListenerY1( y1 );
bottom.setEdgeListenerY2( y2 );
final BoxSide left = getSide( BoxSide.Side.LEFT );
left.setEdgeBehavior( BoxSide.Behavior.PLANE );
left.setEdgeListenerX1( y2 );
left.setEdgeListenerX2( y1 );
left.setEdgeListenerY1( z1 );
left.setEdgeListenerY2( z2 );
final BoxSide right = getSide( BoxSide.Side.RIGHT );
right.setEdgeBehavior( BoxSide.Behavior.PLANE );
right.setEdgeListenerX1( y1 );
right.setEdgeListenerX2( y2 );
right.setEdgeListenerY1( z1 );
right.setEdgeListenerY2( z2 );
final BoxSide front = getSide( BoxSide.Side.FRONT );
front.setEdgeBehavior( BoxSide.Behavior.PLANE );
front.setEdgeListenerX1( x1 );
front.setEdgeListenerX2( x2 );
front.setEdgeListenerY1( z1 );
front.setEdgeListenerY2( z2 );
final BoxSide rear = getSide( BoxSide.Side.REAR );
rear.setEdgeBehavior( BoxSide.Behavior.PLANE );
rear.setEdgeListenerX1( x2 );
rear.setEdgeListenerX2( x1 );
rear.setEdgeListenerY1( z1 );
rear.setEdgeListenerY2( z2 );
}
/**
* Configures the edges on the left (X-) and right (X+) of the box to use
* the given listeners. This affects edges on all sides of the box.
*
* @param x1 Listener for edges on the left side of the box.
* @param x2 Listener for edges on the right side of the box.
*/
public void setupLeftRight( @Nullable final BoxControlDelegate x1, @Nullable final BoxControlDelegate x2 )
{
final BoxSide left = getSide( BoxSide.Side.LEFT );
left.setListener( x1 );
left.setBehavior( BoxSide.Behavior.NORMAL );
final BoxSide right = getSide( BoxSide.Side.RIGHT );
right.setListener( x2 );
right.setBehavior( BoxSide.Behavior.NORMAL );
final BoxSide top = getSide( BoxSide.Side.TOP );
top.setEdgeBehavior( BoxSide.Behavior.PLANE );
top.setEdgeListenerX1( x1 );
top.setEdgeListenerX2( x2 );
final BoxSide bottom = getSide( BoxSide.Side.BOTTOM );
bottom.setEdgeBehavior( BoxSide.Behavior.PLANE );
bottom.setEdgeListenerX1( x1 );
bottom.setEdgeListenerX2( x2 );
final BoxSide front = getSide( BoxSide.Side.FRONT );
front.setEdgeBehavior( BoxSide.Behavior.PLANE );
front.setEdgeListenerX1( x1 );
front.setEdgeListenerX2( x2 );
final BoxSide rear = getSide( BoxSide.Side.REAR );
rear.setEdgeBehavior( BoxSide.Behavior.PLANE );
rear.setEdgeListenerX1( x2 );
rear.setEdgeListenerX2( x1 );
}
/**
* Configures the edges on the front (Y-) and rear (Y+) of the box to use
* the given listeners. This affects edges on all sides of the box.
*
* @param y1 Listener for edges on the front side of the box.
* @param y2 Listener for edges on the rear side of the box.
*/
public void setupFrontRear( @Nullable final BoxControlDelegate y1, @Nullable final BoxControlDelegate y2 )
{
final BoxSide front = getSide( BoxSide.Side.FRONT );
front.setListener( y1 );
front.setBehavior( BoxSide.Behavior.NORMAL );
final BoxSide rear = getSide( BoxSide.Side.REAR );
rear.setListener( y2 );
rear.setBehavior( BoxSide.Behavior.NORMAL );
final BoxSide top = getSide( BoxSide.Side.TOP );
top.setEdgeBehavior( BoxSide.Behavior.PLANE );
top.setEdgeListenerY1( y1 );
top.setEdgeListenerY2( y2 );
final BoxSide bottom = getSide( BoxSide.Side.BOTTOM );
bottom.setEdgeBehavior( BoxSide.Behavior.PLANE );
bottom.setEdgeListenerY1( y1 );
bottom.setEdgeListenerY2( y2 );
final BoxSide left = getSide( BoxSide.Side.LEFT );
left.setEdgeBehavior( BoxSide.Behavior.PLANE );
left.setEdgeListenerX1( y2 );
left.setEdgeListenerX2( y1 );
final BoxSide right = getSide( BoxSide.Side.RIGHT );
right.setEdgeBehavior( BoxSide.Behavior.PLANE );
right.setEdgeListenerX1( y1 );
right.setEdgeListenerX2( y2 );
}
/**
* Configures the edges on the bottom (Z-) and top (Z+) of the box to use
* the given listeners. This affects edges on all sides of the box.
*
* @param z1 Listener for edges on the bottom side of the box.
* @param z2 Listener for edges on the top side of the box.
*/
public void setupBottomTop( @Nullable final BoxControlDelegate z1, @Nullable final BoxControlDelegate z2 )
{
final BoxSide bottom = getSide( BoxSide.Side.BOTTOM );
bottom.setListener( z1 );
bottom.setBehavior( BoxSide.Behavior.NORMAL );
final BoxSide top = getSide( BoxSide.Side.TOP );
top.setListener( z2 );
top.setBehavior( BoxSide.Behavior.NORMAL );
final BoxSide front = getSide( BoxSide.Side.FRONT );
front.setEdgeBehavior( BoxSide.Behavior.PLANE );
front.setEdgeListenerY1( z1 );
front.setEdgeListenerY2( z2 );
final BoxSide rear = getSide( BoxSide.Side.REAR );
rear.setEdgeBehavior( BoxSide.Behavior.PLANE );
rear.setEdgeListenerY1( z1 );
rear.setEdgeListenerY2( z2 );
final BoxSide left = getSide( BoxSide.Side.LEFT );
left.setEdgeBehavior( BoxSide.Behavior.PLANE );
left.setEdgeListenerY1( z1 );
left.setEdgeListenerY2( z2 );
final BoxSide right = getSide( BoxSide.Side.RIGHT );
right.setEdgeBehavior( BoxSide.Behavior.PLANE );
right.setEdgeListenerY1( z1 );
right.setEdgeListenerY2( z2 );
}
/**
* Sets the width of all edges.
*
* @param width Width to be set.
*/
public void setEdgeWidth( final double width )
{
for ( final BoxSide side : _sides )
{
side.setEdgeWidth( width );
}
}
/**
* Sets the color of all edges.
*
* @param color Color to be set.
*/
public void setEdgeColor( final Color color )
{
for ( final BoxSide side : _sides )
{
side.setEdgeColor( color );
}
}
@Override
public String toString()
{
return super.toString() + "[tag=" + _tag + ']';
}
}
| AsoBrain/AsoBrain3D | core/src/main/java/ab/j3d/control/BoxControl.java | Java | lgpl-2.1 | 17,816 |
/*
* $Id: OntologyURI.java 1572 2011-04-24 22:10:26Z euzenat $
*
* Copyright (C) INRIA, 2006-2009, 2011
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package fr.inrialpes.exmo.align.service.msg;
import java.util.Properties;
/**
* Contains the messages that should be sent according to the protocol
*/
public class OntologyURI extends Success {
public OntologyURI ( int surr, Message rep, String from, String to, String cont, Properties param ) {
super( surr, rep, from, to, cont, param );
}
public String HTMLString(){
return "Ontology URI: "+content;
}
public String RESTString(){
return "<uri>"+content+"</uri>";
}
}
| dozed/align-api-project | alignsvc/src/main/java/fr/inrialpes/exmo/align/service/msg/OntologyURI.java | Java | lgpl-2.1 | 1,356 |
package fr.toss.FF7Flora;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import fr.toss.FF7.ItemRegistry1;
public class Whisperweed extends Item
{
public Whisperweed(int id)
{
super();
setCreativeTab(ItemRegistry1.Flora);
setUnlocalizedName("Whisper_weed");
}
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister iconRegister)
{
this.itemIcon = iconRegister.registerIcon("FF7:" + getUnlocalizedName().substring(5));
}
}
| GhostMonk3408/MidgarCrusade | src/main/java/fr/toss/FF7Flora/Whisperweed.java | Java | lgpl-2.1 | 595 |
/*
·--------------------------------------------------------------------·
| ReportingCloud - Engine |
| Copyright (c) 2010, FlexibleCoder. |
| https://sourceforge.net/projects/reportingcloud |
·--------------------------------------------------------------------·
| This library is free software; you can redistribute it and/or |
| modify it under the terms of the GNU Lesser General Public |
| License as published by the Free Software Foundation; either |
| version 2.1 of the License, or (at your option) any later version. |
| |
| 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. |
| |
| GNU LGPL: http://www.gnu.org/copyleft/lesser.html |
·--------------------------------------------------------------------·
*/
using System;
using System.Xml;
using System.IO;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace ReportingCloud.Engine
{
///<summary>
/// StyleInfo (borders, fonts, background, padding, ...)
///</summary>
public class StyleInfo: ICloneable
{
// note: all sizes are expressed as points
// _BorderColor
/// <summary>
/// Color of the left border
/// </summary>
public Color BColorLeft; // (Color) Color of the left border
/// <summary>
/// Color of the right border
/// </summary>
public Color BColorRight; // (Color) Color of the right border
/// <summary>
/// Color of the top border
/// </summary>
public Color BColorTop; // (Color) Color of the top border
/// <summary>
/// Color of the bottom border
/// </summary>
public Color BColorBottom; // (Color) Color of the bottom border
// _BorderStyle
/// <summary>
/// Style of the left border
/// </summary>
public BorderStyleEnum BStyleLeft; // (Enum BorderStyle) Style of the left border
/// <summary>
/// Style of the left border
/// </summary>
public BorderStyleEnum BStyleRight; // (Enum BorderStyle) Style of the left border
/// <summary>
/// Style of the top border
/// </summary>
public BorderStyleEnum BStyleTop; // (Enum BorderStyle) Style of the top border
/// <summary>
/// Style of the bottom border
/// </summary>
public BorderStyleEnum BStyleBottom; // (Enum BorderStyle) Style of the bottom border
// _BorderWdith
/// <summary>
/// Width of the left border. Max: 20 pt Min: 0.25 pt
/// </summary>
public float BWidthLeft; //(Size) Width of the left border. Max: 20 pt Min: 0.25 pt
/// <summary>
/// Width of the right border. Max: 20 pt Min: 0.25 pt
/// </summary>
public float BWidthRight; //(Size) Width of the right border. Max: 20 pt Min: 0.25 pt
/// <summary>
/// Width of the right border. Max: 20 pt Min: 0.25 pt
/// </summary>
public float BWidthTop; //(Size) Width of the right border. Max: 20 pt Min: 0.25 pt
/// <summary>
/// Width of the bottom border. Max: 20 pt Min: 0.25 pt
/// </summary>
public float BWidthBottom; //(Size) Width of the bottom border. Max: 20 pt Min: 0.25 pt
/// <summary>
/// Color of the background
/// </summary>
public Color BackgroundColor; //(Color) Color of the background
public string BackgroundColorText; //(Textual Color) Color of the background
/// <summary>
/// The type of background gradient
/// </summary>
public BackgroundGradientTypeEnum BackgroundGradientType; // The type of background gradient
/// <summary>
/// End color for the background gradient.
/// </summary>
/// <summary>
/// The type of background pattern
/// </summary>
public patternTypeEnum PatternType;
public Color BackgroundGradientEndColor; //(Color) End color for the background gradient.
/// <summary>
/// A background image for the report item.
/// </summary>
public PageImage BackgroundImage; // A background image for the report item.
/// <summary>
/// Font style Default: Normal
/// </summary>
public FontStyleEnum FontStyle; // (Enum FontStyle) Font style Default: Normal
/// <summary>
/// Name of the font family Default: Arial
/// </summary>
private string _FontFamily; //(string)Name of the font family Default: Arial -- allow comma separated value?
/// <summary>
/// Point size of the font
/// </summary>
public float FontSize; //(Size) Point size of the font
/// <summary>
/// Thickness of the font
/// </summary>
public FontWeightEnum FontWeight; //(Enum FontWeight) Thickness of the font
/// <summary>
/// Cell format in Excel07 Default: General
/// </summary>
public string _Format; //WRP 28102008 Cell format string
/// <summary>
/// Special text formatting Default: none
/// </summary>
public TextDecorationEnum TextDecoration; // (Enum TextDecoration) Special text formatting Default: none
/// <summary>
/// Horizontal alignment of the text Default: General
/// </summary>
public TextAlignEnum TextAlign; // (Enum TextAlign) Horizontal alignment of the text Default: General
/// <summary>
/// Vertical alignment of the text Default: Top
/// </summary>
public VerticalAlignEnum VerticalAlign; // (Enum VerticalAlign) Vertical alignment of the text Default: Top
/// <summary>
/// The foreground color Default: Black
/// </summary>
public Color Color; // (Color) The foreground color Default: Black
public string ColorText; // (Color-text)
/// <summary>
/// Padding between the left edge of the report item.
/// </summary>
public float PaddingLeft; // (Size)Padding between the left edge of the report item.
/// <summary>
/// Padding between the right edge of the report item.
/// </summary>
public float PaddingRight; // (Size) Padding between the right edge of the report item.
/// <summary>
/// Padding between the top edge of the report item.
/// </summary>
public float PaddingTop; // (Size) Padding between the top edge of the report item.
/// <summary>
/// Padding between the bottom edge of the report item.
/// </summary>
public float PaddingBottom; // (Size) Padding between the bottom edge of the report item.
/// <summary>
/// Height of a line of text.
/// </summary>
public float LineHeight; // (Size) Height of a line of text
/// <summary>
/// Indicates whether text is written left-to-right (default)
/// </summary>
public DirectionEnum Direction; // (Enum Direction) Indicates whether text is written left-to-right (default)
/// <summary>
/// Indicates the writing mode; e.g. left right top bottom or top bottom left right.
/// </summary>
public WritingModeEnum WritingMode; // (Enum WritingMode) Indicates whether text is written
/// <summary>
/// The primary language of the text.
/// </summary>
public string Language; // (Language) The primary language of the text.
/// <summary>
/// Unused.
/// </summary>
public UnicodeBiDirectionalEnum UnicodeBiDirectional; // (Enum UnicodeBiDirection)
/// <summary>
/// Calendar to use.
/// </summary>
public CalendarEnum Calendar; // (Enum Calendar)
/// <summary>
/// The digit format to use.
/// </summary>
public string NumeralLanguage; // (Language) The digit format to use as described by its
/// <summary>
/// The variant of the digit format to use.
/// </summary>
public int NumeralVariant; //(Integer) The variant of the digit format to use.
/// <summary>
/// Constructor using all defaults for the style.
/// </summary>
public StyleInfo()
{
BColorLeft = BColorRight = BColorTop = BColorBottom = System.Drawing.Color.Black; // (Color) Color of the bottom border
BStyleLeft = BStyleRight = BStyleTop = BStyleBottom = BorderStyleEnum.None;
// _BorderWdith
BWidthLeft = BWidthRight = BWidthTop = BWidthBottom = 1;
BackgroundColor = System.Drawing.Color.Empty;
BackgroundColorText = string.Empty;
BackgroundGradientType = BackgroundGradientTypeEnum.None;
BackgroundGradientEndColor = System.Drawing.Color.Empty;
BackgroundImage = null;
FontStyle = FontStyleEnum.Normal;
_FontFamily = "Arial";
//WRP 291008 numFmtId should be 0 (Zero) for General format - will be interpreted as a string
//It has default values in Excel07 as per ECMA-376 standard (SEction 3.8.30) for Office Open XML Excel07
_Format = "General";
FontSize = 10;
FontWeight = FontWeightEnum.Normal;
PatternType = patternTypeEnum.None;
TextDecoration = TextDecorationEnum.None;
TextAlign = TextAlignEnum.General;
VerticalAlign = VerticalAlignEnum.Top;
Color = System.Drawing.Color.Black;
ColorText = "Black";
PaddingLeft = PaddingRight = PaddingTop = PaddingBottom = 0;
LineHeight = 0;
Direction = DirectionEnum.LTR;
WritingMode = WritingModeEnum.lr_tb;
Language = "en-US";
UnicodeBiDirectional = UnicodeBiDirectionalEnum.Normal;
Calendar = CalendarEnum.Gregorian;
NumeralLanguage = Language;
NumeralVariant=1;
}
/// <summary>
/// Name of the font family Default: Arial
/// </summary>
public string FontFamily
{
get
{
int i = _FontFamily.IndexOf(",");
return i > 0? _FontFamily.Substring(0, i): _FontFamily;
}
set { _FontFamily = value; }
}
/// <summary>
/// Name of the font family Default: Arial. Support list of families separated by ','.
/// </summary>
public string FontFamilyFull
{
get {return _FontFamily;}
}
/// <summary>
/// Gets the FontFamily instance using the FontFamily string. This supports lists of fonts.
/// </summary>
/// <returns></returns>
public FontFamily GetFontFamily()
{
return GetFontFamily(_FontFamily);
}
/// <summary>
/// Gets the FontFamily instance using the passed face name. This supports lists of fonts.
/// </summary>
/// <returns></returns>
static public FontFamily GetFontFamily(string fface)
{
string[] choices = fface.Split(',');
FontFamily ff=null;
foreach (string val in choices)
{
try
{
string font=null;
// TODO: should be better way than to hard code; could put in config file??
switch (val.Trim().ToLower())
{
case "serif":
font = "Times New Roman";
break;
case "sans-serif":
font = "Arial";
break;
case "cursive":
font = "Comic Sans MS";
break;
case "fantasy":
font = "Impact";
break;
case "monospace":
case "courier":
font = "Courier New";
break;
default:
font = val;
break;
}
ff = new FontFamily(font);
if (ff != null)
break;
}
catch {} // if font doesn't exist we will go to the next
}
if (ff == null)
ff = new FontFamily("Arial");
return ff;
}
/// <summary>
/// True if font is bold.
/// </summary>
/// <returns></returns>
public bool IsFontBold()
{
switch(FontWeight)
{
case FontWeightEnum.Bold:
case FontWeightEnum.Bolder:
case FontWeightEnum.W500:
case FontWeightEnum.W600:
case FontWeightEnum.W700:
case FontWeightEnum.W800:
case FontWeightEnum.W900:
return true;
default:
return false;
}
}
public bool IsFontItalic()
{
return FontStyle == FontStyleEnum.Italic;
}
/// <summary>
/// Gets the enumerated font weight.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
static public FontWeightEnum GetFontWeight(string v, FontWeightEnum def)
{
FontWeightEnum fw;
switch(v.ToLower())
{
case "Lighter":
fw = FontWeightEnum.Lighter;
break;
case "Normal":
fw = FontWeightEnum.Normal;
break;
case "bold":
fw = FontWeightEnum.Bold;
break;
case "bolder":
fw = FontWeightEnum.Bolder;
break;
case "500":
fw = FontWeightEnum.W500;
break;
case "600":
fw = FontWeightEnum.W600;
break;
case "700":
fw = FontWeightEnum.W700;
break;
case "800":
fw = FontWeightEnum.W800;
break;
case "900":
fw = FontWeightEnum.W900;
break;
default:
fw = def;
break;
}
return fw;
}
/// <summary>
/// Returns the font style (normal or italic).
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static FontStyleEnum GetFontStyle(string v, FontStyleEnum def)
{
FontStyleEnum f;
switch (v.ToLower())
{
case "normal":
f = FontStyleEnum.Normal;
break;
case "italic":
f = FontStyleEnum.Italic;
break;
default:
f = def;
break;
}
return f;
}
/// <summary>
/// Gets the background gradient type.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
static public BackgroundGradientTypeEnum GetBackgroundGradientType(string v, BackgroundGradientTypeEnum def)
{
BackgroundGradientTypeEnum gt;
switch(v.ToLower())
{
case "none":
gt = BackgroundGradientTypeEnum.None;
break;
case "leftright":
gt = BackgroundGradientTypeEnum.LeftRight;
break;
case "topbottom":
gt = BackgroundGradientTypeEnum.TopBottom;
break;
case "center":
gt = BackgroundGradientTypeEnum.Center;
break;
case "diagonalleft":
gt = BackgroundGradientTypeEnum.DiagonalLeft;
break;
case "diagonalright":
gt = BackgroundGradientTypeEnum.DiagonalRight;
break;
case "horizontalcenter":
gt = BackgroundGradientTypeEnum.HorizontalCenter;
break;
case "verticalcenter":
gt = BackgroundGradientTypeEnum.VerticalCenter;
break;
default:
gt = def;
break;
}
return gt;
}
/// <summary>
/// Gets the text decoration.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static TextDecorationEnum GetTextDecoration(string v, TextDecorationEnum def)
{
TextDecorationEnum td;
switch (v.ToLower())
{
case "underline":
td = TextDecorationEnum.Underline;
break;
case "overline":
td = TextDecorationEnum.Overline;
break;
case "linethrough":
td = TextDecorationEnum.LineThrough;
break;
case "none":
td = TextDecorationEnum.None;
break;
default:
td = def;
break;
}
return td;
}
/// <summary>
/// Gets the text alignment.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static TextAlignEnum GetTextAlign(string v, TextAlignEnum def)
{
TextAlignEnum ta;
switch(v.ToLower())
{
case "left":
ta = TextAlignEnum.Left;
break;
case "right":
ta = TextAlignEnum.Right;
break;
case "center":
ta = TextAlignEnum.Center;
break;
case "general":
ta = TextAlignEnum.General;
break;
case "justified":
ta = TextAlignEnum.Justified;
break;
case "justifiedline":
ta = TextAlignEnum.JustifiedLine;
break;
case "justifieddottedline":
ta = TextAlignEnum.JustifiedDottedLine;
break;
default:
ta = def;
break;
}
return ta;
}
/// <summary>
/// Gets the vertical alignment.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static VerticalAlignEnum GetVerticalAlign(string v, VerticalAlignEnum def)
{
VerticalAlignEnum va;
switch (v.ToLower())
{
case "top":
va = VerticalAlignEnum.Top;
break;
case "middle":
va = VerticalAlignEnum.Middle;
break;
case "bottom":
va = VerticalAlignEnum.Bottom;
break;
default:
va = def;
break;
}
return va;
}
/// <summary>
/// Gets the direction of the text.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static DirectionEnum GetDirection(string v, DirectionEnum def)
{
DirectionEnum d;
switch(v.ToLower())
{
case "ltr":
d = DirectionEnum.LTR;
break;
case "rtl":
d = DirectionEnum.RTL;
break;
default:
d = def;
break;
}
return d;
}
/// <summary>
/// Gets the writing mode; e.g. left right top bottom or top bottom left right.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static WritingModeEnum GetWritingMode(string v, WritingModeEnum def)
{
WritingModeEnum w;
switch(v.ToLower())
{
case "lr-tb":
w = WritingModeEnum.lr_tb;
break;
case "tb-rl":
w = WritingModeEnum.tb_rl;
break;
default:
w = def;
break;
}
return w;
}
/// <summary>
/// Gets the unicode BiDirectional.
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static UnicodeBiDirectionalEnum GetUnicodeBiDirectional(string v, UnicodeBiDirectionalEnum def)
{
UnicodeBiDirectionalEnum u;
switch (v.ToLower())
{
case "normal":
u = UnicodeBiDirectionalEnum.Normal;
break;
case "embed":
u = UnicodeBiDirectionalEnum.Embed;
break;
case "bidi-override":
u = UnicodeBiDirectionalEnum.BiDi_Override;
break;
default:
u = def;
break;
}
return u;
}
/// <summary>
/// Gets the calendar (e.g. Gregorian, GregorianArabic, and so on)
/// </summary>
/// <param name="v"></param>
/// <param name="def"></param>
/// <returns></returns>
public static CalendarEnum GetCalendar(string v, CalendarEnum def)
{
CalendarEnum c;
switch (v.ToLower())
{
case "gregorian":
c = CalendarEnum.Gregorian;
break;
case "gregorianarabic":
c = CalendarEnum.GregorianArabic;
break;
case "gregorianmiddleeastfrench":
c = CalendarEnum.GregorianMiddleEastFrench;
break;
case "gregoriantransliteratedenglish":
c = CalendarEnum.GregorianTransliteratedEnglish;
break;
case "gregoriantransliteratedfrench":
c = CalendarEnum.GregorianTransliteratedFrench;
break;
case "gregorianusenglish":
c = CalendarEnum.GregorianUSEnglish;
break;
case "hebrew":
c = CalendarEnum.Hebrew;
break;
case "hijri":
c = CalendarEnum.Hijri;
break;
case "japanese":
c = CalendarEnum.Japanese;
break;
case "korea":
c = CalendarEnum.Korea;
break;
case "taiwan":
c = CalendarEnum.Taiwan;
break;
case "thaibuddhist":
c = CalendarEnum.ThaiBuddhist;
break;
default:
c = def;
break;
}
return c;
}
// WRP 301008 return Excel07 format code as defined in section 3.8.30 of the ECMA-376 standard for Office Open XML Excel07 file formats
public static int GetFormatCode (string val)
{
switch (val)
{
case "General":
return 0;
case "0":
return 1;
case "0.00":
return 2;
case "#,##0":
return 3;
case "#,##0.00":
return 4;
case "0%":
return 9;
case "0.00%":
return 10;
case "0.00E+00":
return 11;
case "# ?/?":
return 12;
case " # ??/??":
return 13;
case "mm-dd-yy":
return 14;
case "d-mmm-yy":
return 15;
case "d-mmm":
return 16;
case "mmm-yy":
return 17;
case "h:mm AM/PM":
return 18;
case "h:mm:ss AM/PM":
return 19;
case "h:mm":
return 20;
case "h:mm:ss":
return 21;
case "m/d/yy h:mm":
return 22;
case "#,##0 ;(#,##0)":
return 37;
case "#,##0 ;[Red](#,##0)":
return 38;
case "#,##0.00;(#,##0.00)":
return 39;
case "#,##0.00;[Red](#,##0.00)":
return 40;
case "mm:ss":
return 45;
case "[h]:mm:ss":
return 46;
case "mmss.0":
return 47;
case "##0.0E+0":
return 48;
case "@":
return 49;
default:
return 999;
}
}
public static patternTypeEnum GetPatternType(System.Drawing.Drawing2D.HatchStyle hs)
{
switch (hs)
{
case HatchStyle.BackwardDiagonal:
return patternTypeEnum.BackwardDiagonal;
case HatchStyle.Cross:
return patternTypeEnum.Cross;
case HatchStyle.DarkDownwardDiagonal:
return patternTypeEnum.DarkDownwardDiagonal;
case HatchStyle.DarkHorizontal:
return patternTypeEnum.DarkHorizontal;
case HatchStyle.Vertical:
return patternTypeEnum.Vertical;
case HatchStyle.LargeConfetti:
return patternTypeEnum.LargeConfetti;
case HatchStyle.OutlinedDiamond:
return patternTypeEnum.OutlinedDiamond;
case HatchStyle.SmallConfetti:
return patternTypeEnum.SmallConfetti;
case HatchStyle.HorizontalBrick:
return patternTypeEnum.HorizontalBrick;
case HatchStyle.LargeCheckerBoard:
return patternTypeEnum.CheckerBoard;
case HatchStyle.SolidDiamond:
return patternTypeEnum.SolidDiamond;
case HatchStyle.DiagonalBrick:
return patternTypeEnum.DiagonalBrick;
default:
return patternTypeEnum.None;
}
}
#region ICloneable Members
public object Clone()
{
return this.MemberwiseClone();
}
#endregion
}
/// <summary>
/// The types of patterns supported.
/// </summary>
public enum patternTypeEnum
{
None,
LargeConfetti,
Cross,
DarkDownwardDiagonal,
OutlinedDiamond,
DarkHorizontal,
SmallConfetti,
HorizontalBrick,
CheckerBoard,
Vertical,
SolidDiamond,
DiagonalBrick,
BackwardDiagonal
}
/// <summary>
/// The types of background gradients supported.
/// </summary>
public enum BackgroundGradientTypeEnum
{
/// <summary>
/// No gradient
/// </summary>
None,
/// <summary>
/// Left Right gradient
/// </summary>
LeftRight,
/// <summary>
/// Top Bottom gradient
/// </summary>
TopBottom,
/// <summary>
/// Center gradient
/// </summary>
Center,
/// <summary>
/// Diagonal Left gradient
/// </summary>
DiagonalLeft,
/// <summary>
/// Diagonal Right gradient
/// </summary>
DiagonalRight,
/// <summary>
/// Horizontal Center gradient
/// </summary>
HorizontalCenter,
/// <summary>
/// Vertical Center
/// </summary>
VerticalCenter
}
/// <summary>
/// Font styles supported
/// </summary>
public enum FontStyleEnum
{
/// <summary>
/// Normal font
/// </summary>
Normal,
/// <summary>
/// Italic font
/// </summary>
Italic
}
/// <summary>
/// Potential font weights
/// </summary>
public enum FontWeightEnum
{
/// <summary>
/// Lighter font
/// </summary>
Lighter,
/// <summary>
/// Normal font
/// </summary>
Normal,
/// <summary>
/// Bold font
/// </summary>
Bold,
/// <summary>
/// Bolder font
/// </summary>
Bolder,
/// <summary>
/// W100 font
/// </summary>
W100,
/// <summary>
/// W200 font
/// </summary>
W200,
/// <summary>
/// W300 font
/// </summary>
W300,
/// <summary>
/// W400 font
/// </summary>
W400,
/// <summary>
/// W500 font
/// </summary>
W500,
/// <summary>
/// W600 font
/// </summary>
W600,
/// <summary>
/// W700 font
/// </summary>
W700,
/// <summary>
/// W800 font
/// </summary>
W800,
/// <summary>
/// W900 font
/// </summary>
W900
}
public enum TextDecorationEnum
{
Underline,
Overline,
LineThrough,
None
}
public enum TextAlignEnum
{
Left,
Center,
Right,
General,
Justified,
JustifiedLine,
JustifiedDottedLine
}
public enum VerticalAlignEnum
{
Top,
Middle,
Bottom
}
public enum DirectionEnum
{
LTR, // left to right
RTL // right to left
}
public enum WritingModeEnum
{
lr_tb, // left right - top bottom
tb_rl // top bottom - right left
}
public enum UnicodeBiDirectionalEnum
{
Normal,
Embed,
BiDi_Override
}
public enum CalendarEnum
{
Gregorian,
GregorianArabic,
GregorianMiddleEastFrench,
GregorianTransliteratedEnglish,
GregorianTransliteratedFrench,
GregorianUSEnglish,
Hebrew,
Hijri,
Japanese,
Korea,
Taiwan,
ThaiBuddhist
}
}
| bittercoder/reportingcloud | src/ReportingCloud.Engine/Runtime/StyleInfo.cs | C# | lgpl-2.1 | 25,517 |
/*--------------------------------------------------------------------
Perceptuum3 rendering components
Copyright (c) 2005, Harrison Ainsworth / HXA7241.
http://www.hxa7241.org/
--------------------------------------------------------------------*/
/*--------------------------------------------------------------------
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later
version.
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., 51 Franklin St, Fifth Floor, Boston,
MA 02110-1301 USA
--------------------------------------------------------------------*/
#ifndef png_h
#define png_h
#include <iosfwd>
#include "p3tonemapper_format.hpp"
namespace p3tonemapper_format
{
using std::istream;
using std::ostream;
/**
* Basic IO for the PNG format.<br/><br/>
*
* Supports these features:
* * RGB
* * 24 or 48 bit pixels
* * can include primaries and gamma
* * allows byte, pixel, and row re-ordering
* <br/>
*
* This implementation requires the libpng and zlib dynamic libraries when run.
* (from, for example, libpng-1.2.8-bin and libpng-1.2.8-dep archives)<br/><br/>
*
* <cite>http://www.libpng.org/</cite>
*/
namespace png
{
enum EOrderingFlags
{
IS_TOP_FIRST = 1,
IS_BGR = 2,
IS_LO_ENDIAN = 4
};
/**
* Write PNG image.<br/><br/>
*
* triples are bottom row first, R then G then B.
*
* @pngLibraryPathName if path not included then a standard system search
* strategy is used.
* @pPrimaries42 chromaticities of RGB and white:
* { rx, ry, gx, gy, bx, by, wx, wy }
* if zero, they are not written to image metadata
* @gamma if zero, it is not written to image metadata
* @is48Bit true for 48 bit triples, false for 24
* @orderingFlags bit combination of EOrderingFlags values
* @pTriples array of byte triples, or word triples if is48Bit is
* true
*
* @exceptions throws char[] message exceptions
*/
void write
(
const char pngLibraryPathName[],
dword width,
dword height,
const float* pPrimaries42,
float gamma,
bool is48Bit,
dword orderingFlags,
const void* pTriples,
ostream& outBytes
);
}
}//namespace
#endif//png_h
| hxa7241/p3tonemapper | application/src/format/png.hpp | C++ | lgpl-2.1 | 2,988 |
package net.minecraft.client.renderer.block.model;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.minecraft.util.JsonUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@SideOnly(Side.CLIENT)
public class ModelBlock
{
private static final Logger LOGGER = LogManager.getLogger();
static final Gson SERIALIZER = (new GsonBuilder()).registerTypeAdapter(ModelBlock.class, new ModelBlock.Deserializer()).registerTypeAdapter(BlockPart.class, new BlockPart.Deserializer()).registerTypeAdapter(BlockPartFace.class, new BlockPartFace.Deserializer()).registerTypeAdapter(BlockFaceUV.class, new BlockFaceUV.Deserializer()).registerTypeAdapter(ItemTransformVec3f.class, new ItemTransformVec3f.Deserializer()).registerTypeAdapter(ItemCameraTransforms.class, new ItemCameraTransforms.Deserializer()).create();
private final List elements;
private final boolean gui3d;
private final boolean ambientOcclusion;
private ItemCameraTransforms cameraTransforms;
public String name;
public final Map textures;
public ModelBlock parent;
protected ResourceLocation parentLocation;
private static final String __OBFID = "CL_00002503";
public static ModelBlock deserialize(Reader p_178307_0_)
{
return (ModelBlock)SERIALIZER.fromJson(p_178307_0_, ModelBlock.class);
}
public static ModelBlock deserialize(String p_178294_0_)
{
return deserialize(new StringReader(p_178294_0_));
}
protected ModelBlock(List p_i46225_1_, Map p_i46225_2_, boolean p_i46225_3_, boolean p_i46225_4_, ItemCameraTransforms p_i46225_5_)
{
this((ResourceLocation)null, p_i46225_1_, p_i46225_2_, p_i46225_3_, p_i46225_4_, p_i46225_5_);
}
protected ModelBlock(ResourceLocation p_i46226_1_, Map p_i46226_2_, boolean p_i46226_3_, boolean p_i46226_4_, ItemCameraTransforms p_i46226_5_)
{
this(p_i46226_1_, Collections.emptyList(), p_i46226_2_, p_i46226_3_, p_i46226_4_, p_i46226_5_);
}
private ModelBlock(ResourceLocation p_i46227_1_, List p_i46227_2_, Map p_i46227_3_, boolean p_i46227_4_, boolean p_i46227_5_, ItemCameraTransforms p_i46227_6_)
{
this.name = "";
this.elements = p_i46227_2_;
this.ambientOcclusion = p_i46227_4_;
this.gui3d = p_i46227_5_;
this.textures = p_i46227_3_;
this.parentLocation = p_i46227_1_;
this.cameraTransforms = p_i46227_6_;
}
public List getElements()
{
return this.hasParent() ? this.parent.getElements() : this.elements;
}
private boolean hasParent()
{
return this.parent != null;
}
public boolean isAmbientOcclusion()
{
return this.hasParent() ? this.parent.isAmbientOcclusion() : this.ambientOcclusion;
}
public boolean isGui3d()
{
return this.gui3d;
}
public boolean isResolved()
{
return this.parentLocation == null || this.parent != null && this.parent.isResolved();
}
public void getParentFromMap(Map p_178299_1_)
{
if (this.parentLocation != null)
{
this.parent = (ModelBlock)p_178299_1_.get(this.parentLocation);
}
}
public boolean isTexturePresent(String p_178300_1_)
{
return !"missingno".equals(this.resolveTextureName(p_178300_1_));
}
public String resolveTextureName(String p_178308_1_)
{
if (!this.startsWithHash(p_178308_1_))
{
p_178308_1_ = '#' + p_178308_1_;
}
return this.resolveTextureName(p_178308_1_, new ModelBlock.Bookkeep(null));
}
private String resolveTextureName(String p_178302_1_, ModelBlock.Bookkeep p_178302_2_)
{
if (this.startsWithHash(p_178302_1_))
{
if (this == p_178302_2_.modelExt)
{
LOGGER.warn("Unable to resolve texture due to upward reference: " + p_178302_1_ + " in " + this.name);
return "missingno";
}
else
{
String s1 = (String)this.textures.get(p_178302_1_.substring(1));
if (s1 == null && this.hasParent())
{
s1 = this.parent.resolveTextureName(p_178302_1_, p_178302_2_);
}
p_178302_2_.modelExt = this;
if (s1 != null && this.startsWithHash(s1))
{
s1 = p_178302_2_.model.resolveTextureName(s1, p_178302_2_);
}
return s1 != null && !this.startsWithHash(s1) ? s1 : "missingno";
}
}
else
{
return p_178302_1_;
}
}
private boolean startsWithHash(String p_178304_1_)
{
return p_178304_1_.charAt(0) == 35;
}
public ResourceLocation getParentLocation()
{
return this.parentLocation;
}
public ModelBlock getRootModel()
{
return this.hasParent() ? this.parent.getRootModel() : this;
}
public ItemTransformVec3f getThirdPersonTransform()
{
return this.parent != null && this.cameraTransforms.thirdPerson == ItemTransformVec3f.DEFAULT ? this.parent.getThirdPersonTransform() : this.cameraTransforms.thirdPerson;
}
public ItemTransformVec3f getFirstPersonTransform()
{
return this.parent != null && this.cameraTransforms.firstPerson == ItemTransformVec3f.DEFAULT ? this.parent.getFirstPersonTransform() : this.cameraTransforms.firstPerson;
}
public ItemTransformVec3f getHeadTransform()
{
return this.parent != null && this.cameraTransforms.head == ItemTransformVec3f.DEFAULT ? this.parent.getHeadTransform() : this.cameraTransforms.head;
}
public ItemTransformVec3f getInGuiTransform()
{
return this.parent != null && this.cameraTransforms.gui == ItemTransformVec3f.DEFAULT ? this.parent.getInGuiTransform() : this.cameraTransforms.gui;
}
public static void checkModelHierarchy(Map p_178312_0_)
{
Iterator iterator = p_178312_0_.values().iterator();
while (iterator.hasNext())
{
ModelBlock modelblock = (ModelBlock)iterator.next();
try
{
ModelBlock modelblock1 = modelblock.parent;
for (ModelBlock modelblock2 = modelblock1.parent; modelblock1 != modelblock2; modelblock2 = modelblock2.parent.parent)
{
modelblock1 = modelblock1.parent;
}
throw new ModelBlock.LoopException();
}
catch (NullPointerException nullpointerexception)
{
;
}
}
}
@SideOnly(Side.CLIENT)
final class Bookkeep
{
public final ModelBlock model;
public ModelBlock modelExt;
private static final String __OBFID = "CL_00002501";
private Bookkeep()
{
this.model = ModelBlock.this;
}
Bookkeep(Object p_i46224_2_)
{
this();
}
}
@SideOnly(Side.CLIENT)
public static class Deserializer implements JsonDeserializer
{
private static final String __OBFID = "CL_00002500";
public ModelBlock parseModelBlock(JsonElement p_178327_1_, Type p_178327_2_, JsonDeserializationContext p_178327_3_)
{
JsonObject jsonobject = p_178327_1_.getAsJsonObject();
List list = this.getModelElements(p_178327_3_, jsonobject);
String s = this.getParent(jsonobject);
boolean flag = StringUtils.isEmpty(s);
boolean flag1 = list.isEmpty();
if (flag1 && flag)
{
throw new JsonParseException("BlockModel requires either elements or parent, found neither");
}
else if (!flag && !flag1)
{
throw new JsonParseException("BlockModel requires either elements or parent, found both");
}
else
{
Map map = this.getTextures(jsonobject);
boolean flag2 = this.getAmbientOcclusionEnabled(jsonobject);
ItemCameraTransforms itemcameratransforms = ItemCameraTransforms.DEFAULT;
if (jsonobject.has("display"))
{
JsonObject jsonobject1 = JsonUtils.getJsonObject(jsonobject, "display");
itemcameratransforms = (ItemCameraTransforms)p_178327_3_.deserialize(jsonobject1, ItemCameraTransforms.class);
}
return flag1 ? new ModelBlock(new ResourceLocation(s), map, flag2, true, itemcameratransforms) : new ModelBlock(list, map, flag2, true, itemcameratransforms);
}
}
private Map getTextures(JsonObject p_178329_1_)
{
HashMap hashmap = Maps.newHashMap();
if (p_178329_1_.has("textures"))
{
JsonObject jsonobject1 = p_178329_1_.getAsJsonObject("textures");
Iterator iterator = jsonobject1.entrySet().iterator();
while (iterator.hasNext())
{
Entry entry = (Entry)iterator.next();
hashmap.put(entry.getKey(), ((JsonElement)entry.getValue()).getAsString());
}
}
return hashmap;
}
private String getParent(JsonObject p_178326_1_)
{
return JsonUtils.getJsonObjectStringFieldValueOrDefault(p_178326_1_, "parent", "");
}
protected boolean getAmbientOcclusionEnabled(JsonObject p_178328_1_)
{
return JsonUtils.getJsonObjectBooleanFieldValueOrDefault(p_178328_1_, "ambientocclusion", true);
}
protected List getModelElements(JsonDeserializationContext p_178325_1_, JsonObject p_178325_2_)
{
ArrayList arraylist = Lists.newArrayList();
if (p_178325_2_.has("elements"))
{
Iterator iterator = JsonUtils.getJsonObjectJsonArrayField(p_178325_2_, "elements").iterator();
while (iterator.hasNext())
{
JsonElement jsonelement = (JsonElement)iterator.next();
arraylist.add((BlockPart)p_178325_1_.deserialize(jsonelement, BlockPart.class));
}
}
return arraylist;
}
public Object deserialize(JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_)
{
return this.parseModelBlock(p_deserialize_1_, p_deserialize_2_, p_deserialize_3_);
}
}
@SideOnly(Side.CLIENT)
public static class LoopException extends RuntimeException
{
private static final String __OBFID = "CL_00002499";
}
} | kelthalorn/ConquestCraft | build/tmp/recompSrc/net/minecraft/client/renderer/block/model/ModelBlock.java | Java | lgpl-2.1 | 11,878 |
module.exports = iterator
const normalizePaginatedListResponse = require('./normalize-paginated-list-response')
function iterator (octokit, options) {
const headers = options.headers
let url = octokit.request.endpoint(options).url
return {
[Symbol.asyncIterator]: () => ({
next () {
if (!url) {
return Promise.resolve({ done: true })
}
return octokit.request({ url, headers })
.then((response) => {
normalizePaginatedListResponse(octokit, url, response)
// `response.headers.link` format:
// '<https://api.github.com/users/aseemk/followers?page=2>; rel="next", <https://api.github.com/users/aseemk/followers?page=2>; rel="last"'
// sets `url` to undefined if "next" URL is not present or `link` header is not set
url = ((response.headers.link || '').match(/<([^>]+)>;\s*rel="next"/) || [])[1]
return { value: response }
})
}
})
}
}
| checkstyle/contribution | comment-action/node_modules/@octokit/rest/plugins/pagination/iterator.js | JavaScript | lgpl-2.1 | 993 |
/*!
* This program 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.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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 Lesser General Public License for more details.
*
* Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved.
*/
package org.pentaho.reporting.engine.classic.core.crosstab;
import junit.framework.TestCase;
import org.pentaho.reporting.engine.classic.core.ClassicEngineBoot;
import org.pentaho.reporting.engine.classic.core.InvalidReportStateException;
import org.pentaho.reporting.engine.classic.core.ReportProcessingException;
import org.pentaho.reporting.engine.classic.core.states.crosstab.CrosstabSpecification;
import org.pentaho.reporting.engine.classic.core.util.TypedTableModel;
public class SortedMergeCrosstabSpecificationIT extends TestCase {
public SortedMergeCrosstabSpecificationIT() {
}
public SortedMergeCrosstabSpecificationIT( final String name ) {
super( name );
}
public void setUp() throws Exception {
ClassicEngineBoot.getInstance().start();
}
public void testMinimalSpecification() throws ReportProcessingException {
final TypedTableModel model = new TypedTableModel( new String[] { "Rows", "Cols", "Data" } );
model.addRow( "R0", "C0", 1 );
model.addRow( "R1", "C1", 2 );
model.addRow( "R2", "C2", 3 );
model.addRow( "R3", "C3", 4 );
final CrosstabSpecification crosstabSpecification = CrosstabTestUtil.fillSortedCrosstabSpec( model );
assertEquals( 4, crosstabSpecification.size() );
CrosstabTestUtil.assertEqualsArray( new Object[] { "C0" }, crosstabSpecification.getKeyAt( 0 ) );
CrosstabTestUtil.assertEqualsArray( new Object[] { "C1" }, crosstabSpecification.getKeyAt( 1 ) );
CrosstabTestUtil.assertEqualsArray( new Object[] { "C2" }, crosstabSpecification.getKeyAt( 2 ) );
CrosstabTestUtil.assertEqualsArray( new Object[] { "C3" }, crosstabSpecification.getKeyAt( 3 ) );
}
public void testCompleteLateSpecification() throws ReportProcessingException {
final TypedTableModel model = new TypedTableModel( new String[] { "Rows", "Cols", "Data" } );
model.addRow( "R0", "C0", 1 );
model.addRow( "R1", "C1", 2 );
model.addRow( "R2", "C2", 3 );
model.addRow( "R3", "C3", 4 );
model.addRow( "R4", "C3", 4 );
model.addRow( "R4", "C2", 4 );
model.addRow( "R4", "C1", 4 );
model.addRow( "R4", "C0", 4 );
final CrosstabSpecification crosstabSpecification = CrosstabTestUtil.fillSortedCrosstabSpec( model );
assertEquals( 4, crosstabSpecification.size() );
CrosstabTestUtil.assertEqualsArray( new Object[] { "C0" }, crosstabSpecification.getKeyAt( 3 ) );
CrosstabTestUtil.assertEqualsArray( new Object[] { "C1" }, crosstabSpecification.getKeyAt( 2 ) );
CrosstabTestUtil.assertEqualsArray( new Object[] { "C2" }, crosstabSpecification.getKeyAt( 1 ) );
CrosstabTestUtil.assertEqualsArray( new Object[] { "C3" }, crosstabSpecification.getKeyAt( 0 ) );
}
public void testOverlappingSpecification() throws ReportProcessingException {
final TypedTableModel model = new TypedTableModel( new String[] { "Rows", "Cols", "Data" } );
model.addRow( "R0", "C0", 4 );
model.addRow( "R0", "C1", 4 );
model.addRow( "R1", "C1", 4 );
model.addRow( "R1", "C2", 4 );
model.addRow( "R2", "C0", 5 );
model.addRow( "R2", "C2", 5 );
final CrosstabSpecification crosstabSpecification = CrosstabTestUtil.fillSortedCrosstabSpec( model );
assertEquals( 3, crosstabSpecification.size() );
CrosstabTestUtil.assertEqualsArray( new Object[] { "C0" }, crosstabSpecification.getKeyAt( 0 ) );
CrosstabTestUtil.assertEqualsArray( new Object[] { "C1" }, crosstabSpecification.getKeyAt( 1 ) );
CrosstabTestUtil.assertEqualsArray( new Object[] { "C2" }, crosstabSpecification.getKeyAt( 2 ) );
}
public void testConflictingSpecification() throws ReportProcessingException {
final TypedTableModel model = new TypedTableModel( new String[] { "Rows", "Cols", "Data" } );
model.addRow( "R4", "C3", 4 );
model.addRow( "R4", "C2", 4 );
model.addRow( "R4", "C1", 4 );
model.addRow( "R4", "C0", 4 );
model.addRow( "R5", "C0", 5 );
model.addRow( "R5", "C1", 5 );
model.addRow( "R5", "C2", 5 );
model.addRow( "R5", "C3", 5 );
try {
final CrosstabSpecification crosstabSpecification = CrosstabTestUtil.fillSortedCrosstabSpec( model );
fail();
} catch ( InvalidReportStateException rse ) {
// good catch ..
}
}
public void testDiagonalMasterDatarow() throws ReportProcessingException {
final TypedTableModel model = new TypedTableModel( new String[] { "Rows", "Cols", "Data" } );
model.addRow( "R0", "C0", 1 );
model.addRow( "R1", "C1", 2 );
model.addRow( "R2", "C2", 3 );
model.addRow( "R3", "C3", 4 );
final String[][] validateData =
new String[][] { { "R0", "C0" }, { "R0", "C1" }, { "R0", "C2" }, { "R0", "C3" }, { "R1", "C0" },
{ "R1", "C1" }, { "R1", "C2" }, { "R1", "C3" }, { "R2", "C0" }, { "R2", "C1" }, { "R2", "C2" },
{ "R2", "C3" }, { "R3", "C0" }, { "R3", "C1" }, { "R3", "C2" }, { "R3", "C3" }, };
final CrosstabSpecification crosstabSpecification = CrosstabTestUtil.fillSortedCrosstabSpec( model );
final int itCount = CrosstabTestUtil.advanceCrosstab( crosstabSpecification, model, validateData );
assertEquals( 16, itCount );
}
}
| EgorZhuk/pentaho-reporting | engine/core/src/it/java/org/pentaho/reporting/engine/classic/core/crosstab/SortedMergeCrosstabSpecificationIT.java | Java | lgpl-2.1 | 5,975 |
package org.skyve.metadata.model.document;
import org.skyve.metadata.MetaData;
public interface Interface extends MetaData {
String getInterfaceName();
}
| skyvers/wildcat | skyve-core/src/main/java/org/skyve/metadata/model/document/Interface.java | Java | lgpl-2.1 | 157 |
/////////////////////////////////////////////////////////////////////////////
// This file is part of the "OPeNDAP 4 Data Server (aka Hyrax)" project.
//
//
// Copyright (c) 2011 OPeNDAP, Inc.
// Author: Nathan David Potter <ndp@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
/////////////////////////////////////////////////////////////////////////////
package opendap.wcs.gatewayClient;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* User: ndp
* Date: Mar 12, 2008
* Time: 4:35:34 PM
*/
public class WcsService {
private Logger log = org.slf4j.LoggerFactory.getLogger(getClass());
private Element config;
private Document capabilitiesDocument;
private Date capabilitiesDocumentTimeAcquired;
//private Document coverageDescriptionDocument;
//private Date coverageDescriptionDocumentTimeAcquired;
private long cacheTime;
private ReentrantReadWriteLock capablitiesDocLock;
//private ReentrantReadWriteLock coverageDescDocLock;
private HashMap<String,Element> coverages;
private UpdateCapabilitiesThread capabilitiesUpdater;
//private UpdateCoverageThread coverageUpdater;
/**
* A value of 1000 makes the cacheTime attribute's units seconds.
* A value of 1 would make the cachTime attributes's units milliseconds.
*/
private static int SECONDS = 1000;
public WcsService(Element configuration) throws Exception{
log.debug("Configuring...");
config = (Element) configuration.clone();
config();
log.debug("\n"+this);
coverages = new HashMap<String,Element>();
capablitiesDocLock = new ReentrantReadWriteLock();
log.debug("Created capablitiesDocLock.");
log.debug("Creating UpdateCapabilitiesThread thread.");
capabilitiesUpdater = new UpdateCapabilitiesThread();
log.debug("Created UpdateCapabilitiesThread thread.");
log.debug("Calling UpdateCapabilitiesThread.update(true)...");
capabilitiesUpdater.update(true);
log.debug("UpdateCapabilitiesThread.update(true) completed");
capabilitiesDocumentTimeAcquired = new Date();
capabilitiesUpdater.start();
/*
coverageDescDocLock = new ReentrantReadWriteLock();
log.debug("Created coverageDescDocLock.");
log.debug("Creating UpdateCoverageThread thread.");
coverageUpdater = new UpdateCoverageThread();
log.debug("Created UpdateCoverageThread thread.");
log.debug("Calling UpdateCoverageThread.update(true)...");
coverageUpdater.update(true);
log.debug("UpdateCoverageThread.update(true) completed");
coverageDescriptionDocumentTimeAcquired = new Date();
coverageUpdater.start();
*/
}
public ReentrantReadWriteLock.ReadLock getReadLock(){
return capablitiesDocLock.readLock();
}
public Document getCapabilitiesDocument(){
return capabilitiesDocument;
}
public String OLDgetWcsRequestURL(Site site,
WcsCoverageOffering coverage,
String dateName) {
//"http://g0dup05u.ecs.nasa.gov/cgi-bin/ceopAIRX2RET?
// service=WCS
// &version=1.0.0
// &request=GetCoverage
// &coverage=TSurfAir
// &TIME=2002-10-01
String url = getServiceURL();
if(!url.endsWith("?"))
url += "?";
url += "service="+getService();
url += "&version="+getVersion();
url += "&request=GetCoverage";
url += "&coverage="+coverage.getName();
if(dateName!=null)
url += "&TIME="+dateName;
// &crs=WGS84
// &bbox=-107.375000,51.625000,-102.625000,56.375000
// &format=netCDF
// &resx=0.25
// &resy=0.25
// &interpolationMethod=Nearest%20neighbor"/>
List params = site.getWCSParameters();
for (Object param1 : params) {
Element param = (Element) param1;
if (!param.getName().equals("time"))
url += "&" + param.getName() + "=" + param.getTextTrim();
}
log.debug("WCS REQUEST URL: "+ url);
return url;
}
public String getWcsRequestURL(Site site,
WcsCoverageOffering coverage,
String dateName) {
//"http://g0dup05u.ecs.nasa.gov/cgi-bin/ceopAIRX2RET?
// service=WCS
// &version=1.0.0
// &request=GetCoverage
// &coverage=TSurfAir
// &TIME=2002-10-01
String url = getServiceURL();
if(!url.endsWith("?"))
url += "?";
url += "service="+getService();
url += "&version="+getVersion();
url += "&request=GetCoverage";
url += "&coverage="+coverage.getName();
//url += "&"+coverage.getSpatialDomainConstraint();
if(dateName!=null)
url += "&TIME="+dateName;
// &crs=WGS84
// &bbox=-107.375000,51.625000,-102.625000,56.375000
// &format=netCDF
// &resx=0.25
// &resy=0.25
// &interpolationMethod=Nearest%20neighbor"/>
List params = site.getWCSParameters();
for (Object param1 : params) {
Element param = (Element) param1;
if (!param.getName().equals("time"))
url += "&" + param.getName() + "=" + param.getTextTrim();
}
log.debug("WCS REQUEST URL: "+ url);
return url;
}
public void destroy(){
capabilitiesUpdater.interrupt();
//coverageUpdater.interrupt();
log.debug("Destroyed");
}
/*
public WcsCoverageOffering getCoverageOffering(String coverageName) throws Exception {
Element coverageElement = coverages.get(coverageName);
if(coverageElement==null){
throw new Exception("Coverage \""+coverageName+"\" is not " +
"avaliable on the WCS Service: "+getName());
}
return new WcsCoverageOffering(coverageElement);
}
*/
public WcsCoverageOffering getCoverageOffering(String hashedName) throws Exception{
Element coverageOfferingBrief = coverages.get(hashedName);
if(coverageOfferingBrief==null){
return null;
}
String[] name = new String[1];
name[0] = coverageOfferingBrief.getChild(WCS.NAME,WCS.NS).getTextTrim();
Document doc = httpDescribeCoverage(name);
Element coverageOffering = doc.getRootElement().getChild(WCS.COVERAGE_OFFERING,WCS.NS);
return new WcsCoverageOffering(coverageOffering);
}
public Document httpDescribeCoverage(String[] coverages) throws Exception {
HttpClient httpClient = new HttpClient();
String q;
if(getServiceURL().endsWith("?"))
q="";
else
q="?";
String requestURI = getServiceURL() + q +
"service="+getService()+
"&version="+getVersion()+
"&request=DescribeCoverage";
if(coverages != null){
String coverageString = "&coverage=";
for(int i=0; i< coverages.length ; i++){
if(i>0)
coverageString += ",";
coverageString += coverages[i];
}
requestURI+=coverageString;
}
log.debug("requestURI: "+requestURI);
GetMethod request = new GetMethod(requestURI);
try {
// Execute the method.
int statusCode = httpClient.executeMethod(request);
if (statusCode != HttpStatus.SC_OK) {
log.error("Method failed: " + request.getStatusLine());
}
// Parse the XML doc into a Document object.
SAXBuilder sb = new SAXBuilder();
InputStream is = request.getResponseBodyAsStream();
try {
Document doc = sb.build(is);
log.debug("Got and parsed coverage description document.");
//XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
//xmlo.output(doc, System.out);
return doc;
}
finally {
try{
is.close();
}
catch(IOException e){
log.error("Failed to InputStream for "+requestURI+" Error MEssage: "+e.getMessage());
}
}
}
finally {
request.releaseConnection();
}
}
/**
*
*/
private class UpdateCapabilitiesThread extends Thread {
private Logger log = org.slf4j.LoggerFactory.getLogger(getClass());
private HttpClient httpClient;
UpdateCapabilitiesThread(){
super();
log.debug("Constructor.");
httpClient = new HttpClient();
}
public void run() {
log.info("Starting.");
boolean done = false;
while(!done) {
try {
update(false);
done = interrupted();
Thread.sleep(cacheTime);
} catch (InterruptedException e) {
log.info("Interrupted Exception.");
done = true;
}
}
log.info("Exiting");
}
public long getCacheAge(){
Date now = new Date();
return now.getTime() - capabilitiesDocumentTimeAcquired.getTime();
}
private void update(boolean force){
int biffCount=0;
log.debug("Attempting to update cached " +
"capablities document. force="+force);
if(force || cacheTime<getCacheAge()){
ReentrantReadWriteLock.WriteLock lock = capablitiesDocLock.writeLock();
try {
lock.lock();
log.debug("capablitiesDocLock WriteLock Acquired.");
if(force || cacheTime<getCacheAge()){
log.debug("Updating Capabilities Document.");
Document doc = httpGetCapabilities();
ingestCapabilitiesDocument(doc);
}
}
catch(Exception e){
log.error("I has a problem: "+
e.getMessage() +
" biffCount: "+ (++biffCount) );
}
finally {
lock.unlock();
log.debug("WriteLock Released.");
}
}
}
public Document httpGetCapabilities() throws Exception {
String q;
if(getServiceURL().endsWith("?"))
q="";
else
q="?";
String requestURI = getServiceURL() + q +
"service="+getService()+
"&version="+getVersion()+
"&request=GetCapabilities";
log.debug("requestURI: "+requestURI);
GetMethod request = new GetMethod(requestURI);
log.debug("HttpClient: "+httpClient);
try {
// Execute the method.
int statusCode = httpClient.executeMethod(request);
if (statusCode != HttpStatus.SC_OK) {
log.error("Method failed: " + request.getStatusLine());
}
// Parse the XML doc into a Document object.
SAXBuilder sb = new SAXBuilder();
InputStream is = request.getResponseBodyAsStream();
try {
Document doc = sb.build(is);
log.debug("Got and parsed capabilites document.");
//XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
//xmlo.output(doc, System.out);
return doc;
}
finally {
try{
is.close();
}
catch(IOException e){
log.error("Failed to InputStream for "+requestURI+" Error MEssage: "+e.getMessage());
}
}
}
finally {
log.debug("Releasing Http connection.");
request.releaseConnection();
}
}
}
/*
private class UpdateCoverageThread extends Thread {
private Logger log = org.slf4j.LoggerFactory.getLogger(getClass());
private HttpClient httpClient = new HttpClient();
UpdateCoverageThread(){
super();
log.debug("Creating.");
}
public void run() {
log.info("Starting.");
boolean done = false;
while(!done) {
try {
update(false);
done = interrupted();
Thread.sleep(cacheTime);
} catch (InterruptedException e) {
log.info("Caught Interrupted " +
"Exception.");
done = true;
}
}
log.info("Exiting");
}
public long getCatalogAge(){
Date now = new Date();
return now.getTime() - coverageDescriptionDocumentTimeAcquired.getTime();
}
public void update(boolean force){
int biffCount=0;
log.debug("Attempting to update cached " +
"coverage description document. force="+force);
if(force || cacheTime<getCatalogAge()){
coverageDescDocLock.writeLock().lock();
log.debug("WriteLock Acquired.");
try {
if(force || cacheTime<getCatalogAge()){
log.debug("Updating Coverage Description Document.");
Document doc = httpDescribeCoverage(null);
ingestCoverageDesription(doc);
}
}
catch(Exception e){
log.error("I HAS A PROBLEM: "+
e.getMessage() +
" biffCount: "+ (++biffCount) );
}
finally {
coverageDescDocLock.writeLock().unlock();
log.debug("WriteLock Released..");
}
}
}
}
*/
/*
public void ingestCoverageDesription(Document doc){
coverageDescriptionDocument = doc;
Element coverageOffering;
String name, hashedName;
List coverageList = coverageDescriptionDocument.getRootElement().getChildren(WCS.COVERAGE_OFFERING,WCS.NS);
for (Object cvrgOffrElem : coverageList) {
coverageOffering = (Element) cvrgOffrElem;
name = coverageOffering.getChild(WCS.NAME, WCS.NS).getTextTrim();
hashedName = getHashedName(name);
log.debug("Adding coverage "+name+" to coverage HashMap. hashMapName: "+hashedName);
coverages.put(hashedName, coverageOffering);
log.debug("Adding link name "+hashedName+" to CoverageOffering Element.");
Element link = new Element("DapLink",WCS.DAPWCS_NS);
link.setText(hashedName);
coverageOffering.addContent(link);
}
}
*/
public void ingestCapabilitiesDocument(Document doc){
capabilitiesDocument = doc;
Element coverageOfferingBrief, contentMetatdata;
String name;
//String hashedName;
contentMetatdata = capabilitiesDocument.getRootElement().getChild(WCS.CONTENT_METADATA,WCS.NS);
List coverageList = contentMetatdata.getChildren(WCS.COVERAGE_OFFERING_BRIEF,WCS.NS);
for (Object cvrgOffrElem : coverageList) {
coverageOfferingBrief = (Element) cvrgOffrElem;
name = coverageOfferingBrief.getChild(WCS.NAME, WCS.NS).getTextTrim();
/*
hashedName = getHashedName(name);
log.debug("Adding coverageOfferingBrief "+name+" to coverage HashMap. hashMapName: "+hashedName);
coverages.put(hashedName, coverageOfferingBrief);
log.debug("Adding link name "+hashedName+" to CoverageOfferingBrief Element.");
Element link = new Element("DapLink",WCS.DAPWCS_NS);
link.setText(hashedName);
coverageOfferingBrief.addContent(link);
*/
log.debug("Adding coverageOfferingBrief "+name+" to coverage HashMap. hashMapName: "+name);
coverages.put(name, coverageOfferingBrief);
log.debug("Adding link name "+name+" to CoverageOfferingBrief Element.");
Element link = new Element("DapLink",WCS.DAPWCS_NS);
link.setText(name);
coverageOfferingBrief.addContent(link);
}
}
public static String getHashedName(String name){
String s = "";
byte[] b = name.getBytes();
for (byte aB : b) {
s += Integer.toHexString(aB);
}
return s;
}
private void config() throws Exception{
Attribute attr;
String s;
if(!config.getName().equals("WCSService"))
throw new Exception("Cannot build a "+getClass()+" using " +
"<"+config.getName()+"> element.");
attr = config.getAttribute("name");
if(attr==null)
throw new Exception("Missing \"name\" attribute. " +
"<WCSService> elements must have a " +
"name attribute.");
log.debug("name: "+attr.getValue());
attr = config.getAttribute("autoUpdate");
if(attr==null)
setAutoUpdate(false);
if(autoUpdate()){
attr = config.getAttribute("cacheTime");
if(attr==null)
throw new Exception("Missing \"cacheTime\" attribute. " +
"<WCSService> elements must have a " +
"name attribute if the \"autoUpdate\" element is" +
"presentand set to 'true'");
log.debug("cacheTime: "+attr.getValue());
cacheTime = Integer.parseInt(attr.getValue());
cacheTime = cacheTime * SECONDS;
}
else
cacheTime = 600 * SECONDS;
Element elm = config.getChild("ServiceURL");
if(elm==null)
throw new Exception("Missing <ServiceURL> element. " +
"<WCSService name=\""+getName()+"\"> elements must have a " +
"<ServiceURL>" +
" child element.");
s = elm.getTextTrim();
if(s==null)
throw new Exception("Missing <ServiceURL> content. " +
"<WCSService name=\""+getName()+"\"> elements must have a " +
"valid <ServiceURL>" +
" child element.");
s= getServiceURL();
log.debug("ServiceURI: "+s);
elm = config.getChild("service");
if(elm==null)
throw new Exception("Missing <service> element. " +
"<WCSService name=\""+getName()+"\"> elements must have a " +
"<service>" +
" child element.");
s = getService();
log.debug("service: "+s);
elm = config.getChild("version");
if(elm==null)
throw new Exception("Missing <version> element. " +
"<WCSService name=\""+getName()+"\"> elements must have a " +
"<version>" +
" child element.");
s=getVersion();
log.debug("version: "+s);
}
public String getName() {
return config.getAttributeValue("name");
}
public boolean autoUpdate(){
String s;
s = config.getAttributeValue("autoUpdate");
return Boolean.parseBoolean(s);
}
public void setAutoUpdate(boolean val){
config.setAttribute("autoUpdate",val+"");
}
public long getCacheTime() {
return cacheTime;
}
public String getVersion() {
return config.getChild("version").getTextTrim();
}
public String getService() {
return config.getChild("service").getTextTrim();
}
public String getServiceURL() {
return config.getChild("ServiceURL").getTextTrim();
}
public String toString(){
String s = "WcsService: \n";
try {
s += " name: " + getName() + "\n";
s += " serviceURL: " + getServiceURL() + "\n";
s += " service: " + getService() + "\n";
s += " version: " + getVersion() + "\n";
s += " autoUpdate: " + autoUpdate() + "\n";
s += " cacheTime: " + getCacheTime() + "\n";
}
catch (Exception e) {
log.error(e.getMessage() + "\n"+s);
}
return s;
}
}
| OPENDAP/olfs | retired/src/opendap/wcs/gatewayClient/WcsService.java | Java | lgpl-2.1 | 22,463 |
/**
* Copyright (c) 2014, the Railo Company Ltd.
* Copyright (c) 2015, Lucee Assosication Switzerland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>.
*
*/
package lucee.runtime.util;
import lucee.runtime.exp.PageException;
import lucee.runtime.type.Collection;
import lucee.runtime.type.Collection.Key;
/**
* Object to test if a Object is a specific type
*/
public interface Decision {
// FUTURE add function isJson and others we support in the core
// FUTURE add function is(String type, Object value)
public boolean isAnyType(String type);
/**
* tests if value is a simple value (Number,String,Boolean,Date,Printable)
*
* @param value value to test
* @return is value a simple value
*/
public boolean isSimpleValue(Object value);
/**
* tests if value is Numeric
*
* @param value value to test
* @return is value numeric
*/
public boolean isNumber(Object value);
/**
* tests if String value is Numeric
*
* @param str value to test
* @return is value numeric
*/
public boolean isNumber(String str);
/**
* @deprecated use insteas isNumber
*/
public boolean isNumeric(Object value);
/**
* @deprecated use insteas isNumber
*/
public boolean isNumeric(String str);
/**
* tests if String value is Hex Value
*
* @param str value to test
* @return is value numeric
*/
public boolean isHex(String str);
/**
* tests if String value is UUID Value
*
* @param str value to test
* @return is value numeric
*/
public boolean isUUID(String str);
/**
* tests if value is a Boolean (Numbers are not acctepeted)
*
* @param value value to test
* @return is value boolean
*/
public boolean isBoolean(Object value);
/**
* tests if value is a Boolean
*
* @param str value to test
* @return is value boolean
*/
public boolean isBoolean(String str);
/**
* tests if value is DateTime Object
*
* @param value value to test
* @param alsoNumbers interpret also a number as date
* @return is value a DateTime Object
*/
public boolean isDate(Object value, boolean alsoNumbers);
/**
* tests if object is a struct
*
* @param o
* @return is struct or not
*/
public boolean isStruct(Object o);
/**
* tests if object is a array
*
* @param o
* @return is array or not
*/
public boolean isArray(Object o);
/**
* tests if object is a native java array
*
* @param o
* @return is a native (java) array
*/
public boolean isNativeArray(Object o);
/**
* tests if object is a binary
*
* @param object
* @return boolean
*/
public boolean isBinary(Object object);
/**
* tests if object is a Component
*
* @param object
* @return boolean
*/
public boolean isComponent(Object object);
/**
* tests if object is a Query
*
* @param object
* @return boolean
*/
public boolean isQuery(Object object);
/**
* tests if object is a binary
*
* @param object
* @return boolean
*/
public boolean isUserDefinedFunction(Object object);
// FUTURE add isClosure and isFunction, set function above to deprecated
/**
* tests if year is a leap year
*
* @param year year to check
* @return boolean
*/
public boolean isLeapYear(int year);
/**
* tests if object is a WDDX Object
*
* @param o Object to check
* @return boolean
*/
public boolean isWddx(Object o);
/**
* tests if object is a XML Object
*
* @param o Object to check
* @return boolean
*/
public boolean isXML(Object o);
/**
* tests if object is a XML Element Object
*
* @param o Object to check
* @return boolean
*/
public boolean isXMLElement(Object o);
/**
* tests if object is a XML Document Object
*
* @param o Object to check
* @return boolean
*/
public boolean isXMLDocument(Object o);
/**
* tests if object is a XML Root Element Object
*
* @param o Object to check
* @return boolean
*/
public boolean isXMLRootElement(Object o);
/**
* @param string
* @return returns if string represent a variable name
*/
public boolean isVariableName(String string);
/**
* @param string
* @return returns if string represent a variable name
*/
public boolean isSimpleVariableName(String string);
/**
* returns if object is a CFML object
*
* @param o Object to check
* @return is or not
*/
public boolean isObject(Object o);
/**
*
* @param str
* @return return if a String is "Empty", that means NULL or String with
* length 0 (whitespaces will not counted)
*/
public boolean isEmpty(String str);
/**
*
* @param str
* @param trim
* @return return if a String is "Empty", that means NULL or String with
* length 0 (whitespaces will not counted)
*/
public boolean isEmpty(String str, boolean trim);
public Key toKey(Object obj) throws PageException;
public Key toKey(Object obj, Collection.Key defaultValue);
/**
* Checks if number is valid (not infinity or NaN)
* @param dbl
* @return
*/
public boolean isValid(double from);
public boolean isCastableTo(String type, Object o, boolean alsoAlias, boolean alsoPattern, int maxlength);
public boolean isCastableToArray(Object o);
public boolean isCastableToBinary(Object object,boolean checkBase64String);
public boolean isCastableToBoolean(Object obj);
public boolean isCastableToDate(Object o);
public boolean isCastableToNumeric(Object o);
public boolean isCastableToString(Object o);
public boolean isCastableToStruct(Object o);
} | lucee/unoffical-Lucee-no-jre | source/java/loader/src/lucee/runtime/util/Decision.java | Java | lgpl-2.1 | 6,135 |
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Linq.Expressions;
using LinqToTTreeInterfacesLib;
using LINQToTTreeLib.Expressions;
using LINQToTTreeLib.Statements;
using Remotion.Linq;
using Remotion.Linq.Clauses;
using Remotion.Linq.Clauses.ResultOperators;
namespace LINQToTTreeLib.ResultOperators
{
/// <summary>
/// Implement the result operator that will deal with the Count predicate.
/// </summary>
[Export(typeof(IQVScalarResultOperator))]
class ROCount : IQVScalarResultOperator
{
/// <summary>
/// Get the proper value here.
/// </summary>
/// <param name="resultOperatorType"></param>
/// <returns></returns>
public bool CanHandle(Type resultOperatorType)
{
return resultOperatorType == typeof(CountResultOperator);
}
/// <summary>
/// Actually try and process this! The count consisits of a count integer and something to increment it
/// at its current spot.
/// </summary>
/// <param name="resultOperator"></param>
/// <param name="queryModel"></param>
/// <param name="codeEnv"></param>
/// <returns></returns>
public Expression ProcessResultOperator(ResultOperatorBase resultOperator, QueryModel queryModel, IGeneratedQueryCode gc, ICodeContext cc, CompositionContainer container)
{
if (gc == null)
throw new ArgumentNullException("CodeEnv must not be null!");
var c = resultOperator as CountResultOperator;
if (c == null)
throw new ArgumentNullException("resultOperator can only be a CountResultOperator and must not be null");
//
// The accumulator where we will store the result.
//
var accumulator = DeclarableParameter.CreateDeclarableParameterExpression(typeof(int));
accumulator.SetInitialValue("0");
//
// Use the Aggregate infrasturcutre to do the adding. This
// has the advantage that it will correctly combine with
// similar statements during query optimization.
//
var add = Expression.Add(accumulator, Expression.Constant((int)1));
var addResolved = ExpressionToCPP.GetExpression(add, gc, cc, container);
gc.Add(new StatementAggregate(accumulator, addResolved));
return accumulator;
}
/// <summary>
/// Try to do a fast count. Basically, what we are dealing with here is the fact that we have
/// a simple array, we need only take its length, and return that.
/// </summary>
/// <param name="resultOperator"></param>
/// <param name="queryModel"></param>
/// <param name="_codeEnv"></param>
/// <param name="_codeContext"></param>
/// <param name="container"></param>
/// <returns></returns>
public Tuple<bool, Expression> ProcessIdentityQuery(ResultOperatorBase resultOperator, QueryModel queryModel, IGeneratedQueryCode _codeEnv, ICodeContext _codeContext, CompositionContainer container)
{
//
// We just need to return a length expression. We are low enough level we need to do some basic resolution.
//
if (!queryModel.MainFromClause.FromExpression.Type.IsArray)
return Tuple.Create(false, null as Expression);
var lengthExpr = Expression.ArrayLength(queryModel.MainFromClause.FromExpression).Resolve(_codeEnv, _codeContext, container);
return Tuple.Create(true, lengthExpr as Expression);
}
}
}
| gordonwatts/LINQtoROOT | LINQToTTree/LINQToTTreeLib/ResultOperators/ROCount.cs | C# | lgpl-2.1 | 3,845 |
/****************************************************************************
** Meta object code from reading C++ file 'qdeclarativeextensionplugin.h'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../qml/qdeclarativeextensionplugin.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'qdeclarativeextensionplugin.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_QDeclarativeExtensionPlugin[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_QDeclarativeExtensionPlugin[] = {
"QDeclarativeExtensionPlugin\0"
};
void QDeclarativeExtensionPlugin::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObjectExtraData QDeclarativeExtensionPlugin::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject QDeclarativeExtensionPlugin::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_QDeclarativeExtensionPlugin,
qt_meta_data_QDeclarativeExtensionPlugin, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &QDeclarativeExtensionPlugin::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *QDeclarativeExtensionPlugin::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *QDeclarativeExtensionPlugin::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QDeclarativeExtensionPlugin))
return static_cast<void*>(const_cast< QDeclarativeExtensionPlugin*>(this));
if (!strcmp(_clname, "QDeclarativeExtensionInterface"))
return static_cast< QDeclarativeExtensionInterface*>(const_cast< QDeclarativeExtensionPlugin*>(this));
if (!strcmp(_clname, "com.trolltech.Qt.QDeclarativeExtensionInterface/1.0"))
return static_cast< QDeclarativeExtensionInterface*>(const_cast< QDeclarativeExtensionPlugin*>(this));
return QObject::qt_metacast(_clname);
}
int QDeclarativeExtensionPlugin::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| nonrational/qt-everywhere-opensource-src-4.8.6 | src/declarative/.moc/release-shared/moc_qdeclarativeextensionplugin.cpp | C++ | lgpl-2.1 | 2,976 |
/****************************************************************************
**
** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>.
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtWebSockets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
/*!
\class QWebSocket
\inmodule QtWebSockets
\since 5.3
\brief Implements a TCP socket that talks the WebSocket protocol.
WebSockets is a web technology providing full-duplex communications channels over
a single TCP connection.
The WebSocket protocol was standardized by the IETF as
\l {http://tools.ietf.org/html/rfc6455} {RFC 6455} in 2011.
QWebSocket can both be used in a client application and server application.
This class was modeled after QAbstractSocket.
QWebSocket currently does not support
\l {http://tools.ietf.org/html/rfc6455#page-39} {extensions} and
\l {http://tools.ietf.org/html/rfc6455#page-12} {subprotocols}.
QWebSocket only supports version 13 of the WebSocket protocol, as outlined in
\l {http://tools.ietf.org/html/rfc6455}{RFC 6455}.
\note Some proxies do not understand certain HTTP headers used during a WebSocket handshake.
In that case, non-secure WebSocket connections fail. The best way to mitigate against
this problem is to use WebSocket over a secure connection.
\warning To generate masks, this implementation of WebSockets uses the cryptographically
insecure qrand() function.
For more information about the importance of good masking,
see \l {http://w2spconf.com/2011/papers/websocket.pdf}.
The best measure against attacks mentioned in the document above,
is to use QWebSocket over a secure connection (\e wss://).
In general, always be careful to not have 3rd party script access to
a QWebSocket in your application.
\sa QAbstractSocket, QTcpSocket
\sa {QWebSocket client example}
*/
/*!
\page echoclient.html example
\title QWebSocket client example
\brief A sample WebSocket client that sends a message and displays the message that
it receives back.
\section1 Description
The EchoClient example implements a WebSocket client that sends a message to a WebSocket server
and dumps the answer that it gets back.
This example should ideally be used with the EchoServer example.
\section1 Code
We start by connecting to the `connected()` signal.
\snippet echoclient/echoclient.cpp constructor
After the connection, we open the socket to the given \a url.
\snippet echoclient/echoclient.cpp onConnected
When the client is connected successfully, we connect to the `onTextMessageReceived()` signal,
and send out "Hello, world!".
If connected with the EchoServer, we will receive the same message back.
\snippet echoclient/echoclient.cpp onTextMessageReceived
Whenever a message is received, we write it out.
*/
/*!
\fn void QWebSocket::connected()
\brief Emitted when a connection is successfully established.
A connection is successfully established when the socket is connected
and the handshake was successful.
\sa open(), disconnected()
*/
/*!
\fn void QWebSocket::disconnected()
\brief Emitted when the socket is disconnected.
\sa close(), connected()
*/
/*!
\fn void QWebSocket::aboutToClose()
This signal is emitted when the socket is about to close.
Connect this signal if you have operations that need to be performed before the socket closes
(e.g., if you have data in a separate buffer that needs to be written to the device).
\sa close()
*/
/*!
\fn void QWebSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
This signal can be emitted when a \a proxy that requires
authentication is used. The \a authenticator object can then be
filled in with the required details to allow authentication and
continue the connection.
\note It is not possible to use a QueuedConnection to connect to
this signal, as the connection will fail if the authenticator has
not been filled in with new information when the signal returns.
\sa QAuthenticator, QNetworkProxy
*/
/*!
\fn void QWebSocket::stateChanged(QAbstractSocket::SocketState state);
This signal is emitted whenever QWebSocket's state changes.
The \a state parameter is the new state.
\note QAbstractSocket::ConnectedState is emitted after the handshake
with the server has succeeded.
QAbstractSocket::SocketState is not a registered metatype, so for queued
connections, you will have to register it with Q_REGISTER_METATYPE() and
qRegisterMetaType().
\sa state()
*/
/*!
\fn void QWebSocket::readChannelFinished()
This signal is emitted when the input (reading) stream is closed in this device.
It is emitted as soon as the closing is detected.
\sa close()
*/
/*!
\fn void QWebSocket::bytesWritten(qint64 bytes)
This signal is emitted every time a payload of data has been written to the socket.
The \a bytes argument is set to the number of bytes that were written in this payload.
\note This signal has the same meaning both for secure and non-secure WebSockets.
As opposed to QSslSocket, bytesWritten() is only emitted when encrypted data is effectively
written (see QSslSocket::encryptedBytesWritten()).
\sa close()
*/
/*!
\fn void QWebSocket::textFrameReceived(const QString &frame, bool isLastFrame);
This signal is emitted whenever a text frame is received. The \a frame contains the data and
\a isLastFrame indicates whether this is the last frame of the complete message.
This signal can be used to process large messages frame by frame, instead of waiting for the
complete message to arrive.
\sa binaryFrameReceived()
*/
/*!
\fn void QWebSocket::binaryFrameReceived(const QByteArray &frame, bool isLastFrame);
This signal is emitted whenever a binary frame is received. The \a frame contains the data and
\a isLastFrame indicates whether this is the last frame of the complete message.
This signal can be used to process large messages frame by frame, instead of waiting for the
complete message to arrive.
\sa textFrameReceived()
*/
/*!
\fn void QWebSocket::textMessageReceived(const QString &message);
This signal is emitted whenever a text message is received. The \a message contains the
received text.
\sa binaryMessageReceived()
*/
/*!
\fn void QWebSocket::binaryMessageReceived(const QByteArray &message);
This signal is emitted whenever a binary message is received. The \a message contains the
received bytes.
\sa textMessageReceived()
*/
/*!
\fn void QWebSocket::error(QAbstractSocket::SocketError error);
This signal is emitted after an error occurred. The \a error
parameter describes the type of error that occurred.
QAbstractSocket::SocketError is not a registered metatype, so for queued
connections, you will have to register it with Q_DECLARE_METATYPE() and
qRegisterMetaType().
\sa error(), errorString()
*/
/*!
\fn void QWebSocket::sslErrors(const QList<QSslError> &errors)
QWebSocket emits this signal after the SSL handshake to indicate that one or more errors have
occurred while establishing the identity of the peer.
The errors are usually an indication that QWebSocket is unable to securely identify the peer.
Unless any action is taken, the connection will be dropped after this signal has been emitted.
If you want to continue connecting despite the errors that have occurred, you must call
QWebSocket::ignoreSslErrors() from inside a slot connected to this signal.
If you need to access the error list at a later point, you can call sslErrors()
(without arguments).
\a errors contains one or more errors that prevent QWebSocket from verifying the identity of
the peer.
\note You cannot use Qt::QueuedConnection when connecting to this signal, or calling
QWebSocket::ignoreSslErrors() will have no effect.
*/
/*!
\fn void QWebSocket::pong(quint64 elapsedTime, const QByteArray &payload)
Emitted when a pong message is received in reply to a previous ping.
\a elapsedTime contains the roundtrip time in milliseconds and \a payload contains an optional
payload that was sent with the ping.
\sa ping()
*/
#include "qwebsocket.h"
#include "qwebsocket_p.h"
#include <QtCore/QUrl>
#include <QtNetwork/QTcpSocket>
#include <QtCore/QByteArray>
#include <QtNetwork/QHostAddress>
#include <QtCore/QDebug>
#include <limits>
QT_BEGIN_NAMESPACE
/*!
* \brief Creates a new QWebSocket with the given \a origin,
* the \a version of the protocol to use and \a parent.
*
* The \a origin of the client is as specified in \l {http://tools.ietf.org/html/rfc6454}{RFC 6454}.
* (The \a origin is not required for non-web browser clients
* (see \l {http://tools.ietf.org/html/rfc6455}{RFC 6455})).
* The \a origin may not contain new line characters, otherwise the connection will be
* aborted immediately during the handshake phase.
* \note Currently only V13 (\l {http://tools.ietf.org/html/rfc6455} {RFC 6455}) is supported
*/
QWebSocket::QWebSocket(const QString &origin,
QWebSocketProtocol::Version version,
QObject *parent) :
QObject(*(new QWebSocketPrivate(origin, version, this)), parent)
{
Q_D(QWebSocket);
d->init();
}
/*!
* \brief Destroys the QWebSocket. Closes the socket if it is still open,
* and releases any used resources.
*/
QWebSocket::~QWebSocket()
{
}
/*!
* \brief Aborts the current socket and resets the socket.
* Unlike close(), this function immediately closes the socket,
* discarding any pending data in the write buffer.
*/
void QWebSocket::abort()
{
Q_D(QWebSocket);
d->abort();
}
/*!
* Returns the type of error that last occurred
* \sa errorString()
*/
QAbstractSocket::SocketError QWebSocket::error() const
{
Q_D(const QWebSocket);
return d->error();
}
//only called by QWebSocketPrivate::upgradeFrom
/*!
\internal
*/
QWebSocket::QWebSocket(QTcpSocket *pTcpSocket,
QWebSocketProtocol::Version version, QObject *parent) :
QObject(*(new QWebSocketPrivate(pTcpSocket, version, this)), parent)
{
Q_D(QWebSocket);
d->init();
}
/*!
* Returns a human-readable description of the last error that occurred
*
* \sa error()
*/
QString QWebSocket::errorString() const
{
Q_D(const QWebSocket);
return d->errorString();
}
/*!
This function writes as much as possible from the internal write buffer
to the underlying network socket, without blocking.
If any data was written, this function returns true; otherwise false is returned.
Call this function if you need QWebSocket to start sending buffered data immediately.
The number of bytes successfully written depends on the operating system.
In most cases, you do not need to call this function,
because QWebSocket will start sending data automatically
once control goes back to the event loop.
*/
bool QWebSocket::flush()
{
Q_D(QWebSocket);
return d->flush();
}
/*!
\brief Sends the given \a message over the socket as a text message and
returns the number of bytes actually sent.
\sa sendBinaryMessage()
*/
qint64 QWebSocket::sendTextMessage(const QString &message)
{
Q_D(QWebSocket);
return d->sendTextMessage(message);
}
/*!
\brief Sends the given \a data over the socket as a binary message and
returns the number of bytes actually sent.
\sa sendTextMessage()
*/
qint64 QWebSocket::sendBinaryMessage(const QByteArray &data)
{
Q_D(QWebSocket);
return d->sendBinaryMessage(data);
}
/*!
\brief Gracefully closes the socket with the given \a closeCode and \a reason.
Any data in the write buffer is flushed before the socket is closed.
The \a closeCode is a QWebSocketProtocol::CloseCode indicating the reason to close, and
\a reason describes the reason of the closure more in detail
*/
void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode, const QString &reason)
{
Q_D(QWebSocket);
d->close(closeCode, reason);
}
/*!
\brief Opens a WebSocket connection using the given \a url.
If the url contains newline characters (\\r\\n), then the error signal will be emitted
with QAbstractSocket::ConnectionRefusedError as error type.
*/
void QWebSocket::open(const QUrl &url)
{
Q_D(QWebSocket);
d->open(url, true);
}
/*!
\brief Pings the server to indicate that the connection is still alive.
Additional \a payload can be sent along the ping message.
The size of the \a payload cannot be bigger than 125.
If it is larger, the \a payload is clipped to 125 bytes.
\sa pong()
*/
void QWebSocket::ping(const QByteArray &payload)
{
Q_D(QWebSocket);
d->ping(payload);
}
#ifndef QT_NO_SSL
/*!
This slot tells QWebSocket to ignore errors during QWebSocket's
handshake phase and continue connecting. If you want to continue
with the connection even if errors occur during the handshake
phase, then you must call this slot, either from a slot connected
to sslErrors(), or before the handshake phase. If you don't call
this slot, either in response to errors or before the handshake,
the connection will be dropped after the sslErrors() signal has
been emitted.
\warning Be sure to always let the user inspect the errors
reported by the sslErrors() signal, and only call this method
upon confirmation from the user that proceeding is ok.
If there are unexpected errors, the connection should be aborted.
Calling this method without inspecting the actual errors will
most likely pose a security risk for your application. Use it
with great care!
\sa sslErrors(), QSslSocket::ignoreSslErrors(), QNetworkReply::ignoreSslErrors()
*/
void QWebSocket::ignoreSslErrors()
{
Q_D(QWebSocket);
d->ignoreSslErrors();
}
/*!
\overload
This method tells QWebSocket to ignore the errors given in \a errors.
Note that you can set the expected certificate in the SSL error:
If, for instance, you want to connect to a server that uses
a self-signed certificate, consider the following snippet:
\snippet src_websockets_ssl_qwebsocket.cpp 6
Multiple calls to this function will replace the list of errors that
were passed in previous calls.
You can clear the list of errors you want to ignore by calling this
function with an empty list.
\sa sslErrors()
*/
void QWebSocket::ignoreSslErrors(const QList<QSslError> &errors)
{
Q_D(QWebSocket);
d->ignoreSslErrors(errors);
}
/*!
Sets the socket's SSL configuration to be the contents of \a sslConfiguration.
This function sets the local certificate, the ciphers, the private key and
the CA certificates to those stored in \a sslConfiguration.
It is not possible to set the SSL-state related fields.
\sa sslConfiguration()
*/
void QWebSocket::setSslConfiguration(const QSslConfiguration &sslConfiguration)
{
Q_D(QWebSocket);
d->setSslConfiguration(sslConfiguration);
}
/*!
Returns the socket's SSL configuration state.
The default SSL configuration of a socket is to use the default ciphers,
default CA certificates, no local private key or certificate.
The SSL configuration also contains fields that can change with time without notice.
\sa setSslConfiguration()
*/
QSslConfiguration QWebSocket::sslConfiguration() const
{
Q_D(const QWebSocket);
return d->sslConfiguration();
}
#endif //not QT_NO_SSL
/*!
\brief Returns the version the socket is currently using.
*/
QWebSocketProtocol::Version QWebSocket::version() const
{
Q_D(const QWebSocket);
return d->version();
}
/*!
\brief Returns the name of the resource currently accessed.
*/
QString QWebSocket::resourceName() const
{
Q_D(const QWebSocket);
return d->resourceName();
}
/*!
\brief Returns the url the socket is connected to or will connect to.
*/
QUrl QWebSocket::requestUrl() const
{
Q_D(const QWebSocket);
return d->requestUrl();
}
/*!
\brief Returns the current origin.
*/
QString QWebSocket::origin() const
{
Q_D(const QWebSocket);
return d->origin();
}
/*!
\brief Returns the code indicating why the socket was closed.
\sa QWebSocketProtocol::CloseCode, closeReason()
*/
QWebSocketProtocol::CloseCode QWebSocket::closeCode() const
{
Q_D(const QWebSocket);
return d->closeCode();
}
/*!
\brief Returns the reason why the socket was closed.
\sa closeCode()
*/
QString QWebSocket::closeReason() const
{
Q_D(const QWebSocket);
return d->closeReason();
}
/*!
\brief Returns the current state of the socket.
*/
QAbstractSocket::SocketState QWebSocket::state() const
{
Q_D(const QWebSocket);
return d->state();
}
/*!
Returns the local address
*/
QHostAddress QWebSocket::localAddress() const
{
Q_D(const QWebSocket);
return d->localAddress();
}
/*!
Returns the local port
*/
quint16 QWebSocket::localPort() const
{
Q_D(const QWebSocket);
return d->localPort();
}
/*!
Returns the pause mode of this socket
*/
QAbstractSocket::PauseModes QWebSocket::pauseMode() const
{
Q_D(const QWebSocket);
return d->pauseMode();
}
/*!
Returns the peer address
*/
QHostAddress QWebSocket::peerAddress() const
{
Q_D(const QWebSocket);
return d->peerAddress();
}
/*!
Returns the peerName
*/
QString QWebSocket::peerName() const
{
Q_D(const QWebSocket);
return d->peerName();
}
/*!
Returns the peerport
*/
quint16 QWebSocket::peerPort() const
{
Q_D(const QWebSocket);
return d->peerPort();
}
#ifndef QT_NO_NETWORKPROXY
/*!
Returns the currently configured proxy
*/
QNetworkProxy QWebSocket::proxy() const
{
Q_D(const QWebSocket);
return d->proxy();
}
/*!
Sets the proxy to \a networkProxy
*/
void QWebSocket::setProxy(const QNetworkProxy &networkProxy)
{
Q_D(QWebSocket);
d->setProxy(networkProxy);
}
#endif
/*!
Sets the generator to use for creating masks to \a maskGenerator.
The default QWebSocket generator can be reset by supplying a \e Q_NULLPTR.
The mask generator can be changed at any time, even while the connection is open.
*/
void QWebSocket::setMaskGenerator(const QMaskGenerator *maskGenerator)
{
Q_D(QWebSocket);
d->setMaskGenerator(maskGenerator);
}
/*!
Returns the mask generator that is currently used by this QWebSocket.
*/
const QMaskGenerator *QWebSocket::maskGenerator() const
{
Q_D(const QWebSocket);
return d->maskGenerator();
}
/*!
Returns the size in bytes of the readbuffer that is used by the socket.
*/
qint64 QWebSocket::readBufferSize() const
{
Q_D(const QWebSocket);
return d->readBufferSize();
}
/*!
Continues data transfer on the socket. This method should only be used after the socket
has been set to pause upon notifications and a notification has been received.
The only notification currently supported is sslErrors().
Calling this method if the socket is not paused results in undefined behavior.
\sa pauseMode(), setPauseMode()
*/
void QWebSocket::resume()
{
Q_D(QWebSocket);
d->resume();
}
/*!
Controls whether to pause upon receiving a notification. The \a pauseMode parameter specifies
the conditions in which the socket should be paused.
The only notification currently supported is sslErrors().
If set to PauseOnSslErrors, data transfer on the socket will be paused
and needs to be enabled explicitly again by calling resume().
By default, this option is set to PauseNever. This option must be called
before connecting to the server, otherwise it will result in undefined behavior.
\sa pauseMode(), resume()
*/
void QWebSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)
{
Q_D(QWebSocket);
d->setPauseMode(pauseMode);
}
/*!
Sets the size of QWebSocket's internal read buffer to be \a size bytes.
If the buffer size is limited to a certain size, QWebSocket won't buffer more than
this size of data.
Exceptionally, a buffer size of 0 means that the read buffer is unlimited and
all incoming data is buffered. This is the default.
This option is useful if you only read the data at certain points in time
(for example, in a real-time streaming application) or if you want to protect your socket against
receiving too much data, which may eventually cause your application to run out of memory.
\sa readBufferSize()
*/
void QWebSocket::setReadBufferSize(qint64 size)
{
Q_D(QWebSocket);
d->setReadBufferSize(size);
}
/*!
Returns \c true if the socket is ready for reading and writing; otherwise
returns \c false.
*/
bool QWebSocket::isValid() const
{
Q_D(const QWebSocket);
return d->isValid();
}
QT_END_NAMESPACE
| pixty/qtwebsockets | src/websockets/qwebsocket.cpp | C++ | lgpl-2.1 | 22,296 |
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "buildprogress.h"
#include <utils/stylehelper.h>
#include <QtGui/QVBoxLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QFont>
#include <QtGui/QPixmap>
#include <QtDebug>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
BuildProgress::BuildProgress(TaskWindow *taskWindow)
: m_errorIcon(new QLabel),
m_warningIcon(new QLabel),
m_errorLabel(new QLabel),
m_warningLabel(new QLabel),
m_taskWindow(taskWindow)
{
QVBoxLayout *layout = new QVBoxLayout;
layout->setContentsMargins(8, 4, 0, 4);
layout->setSpacing(2);
setLayout(layout);
QHBoxLayout *errorLayout = new QHBoxLayout;
errorLayout->setSpacing(4);
layout->addLayout(errorLayout);
errorLayout->addWidget(m_errorIcon);
errorLayout->addWidget(m_errorLabel);
QHBoxLayout *warningLayout = new QHBoxLayout;
warningLayout->setSpacing(4);
layout->addLayout(warningLayout);
warningLayout->addWidget(m_warningIcon);
warningLayout->addWidget(m_warningLabel);
// ### TODO this setup should be done by style
QFont f = this->font();
f.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
f.setBold(true);
m_errorLabel->setFont(f);
m_warningLabel->setFont(f);
m_errorLabel->setPalette(Utils::StyleHelper::sidebarFontPalette(m_errorLabel->palette()));
m_warningLabel->setPalette(Utils::StyleHelper::sidebarFontPalette(m_warningLabel->palette()));
m_errorIcon->setAlignment(Qt::AlignRight);
m_warningIcon->setAlignment(Qt::AlignRight);
m_errorIcon->setPixmap(QPixmap(":/projectexplorer/images/compile_error.png"));
m_warningIcon->setPixmap(QPixmap(":/projectexplorer/images/compile_warning.png"));
hide();
connect(m_taskWindow, SIGNAL(tasksChanged()), this, SLOT(updateState()));
updateState();
}
void BuildProgress::updateState()
{
if (!m_taskWindow)
return;
int errors = m_taskWindow->errorTaskCount();
bool haveErrors = (errors > 0);
m_errorIcon->setEnabled(haveErrors);
m_errorLabel->setEnabled(haveErrors);
m_errorLabel->setText(QString("%1").arg(errors));
int warnings = m_taskWindow->taskCount()-errors;
bool haveWarnings = (warnings > 0);
m_warningIcon->setEnabled(haveWarnings);
m_warningLabel->setEnabled(haveWarnings);
m_warningLabel->setText(QString("%1").arg(warnings));
// Hide warnings and errors unless you need them
setVisible(haveWarnings | haveErrors);
m_warningIcon->setVisible(haveWarnings);
m_warningLabel->setVisible(haveWarnings);
m_errorIcon->setVisible(haveErrors);
m_errorLabel->setVisible(haveErrors);
}
| enricoros/k-qt-creator-inspector | src/plugins/projectexplorer/buildprogress.cpp | C++ | lgpl-2.1 | 3,876 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Axiom.Core;
using Gallio.Framework;
using MbUnit.Framework;
using MbUnit.Framework.ContractVerifiers;
namespace Axiom.UnitTests.Core
{
[TestFixture]
public class ResourceGroupManagerTests
{
[Test]
public void CreateResource()
{
new Root( "AxiomTests.log" );
ResourceGroupManager.Instance.AddResourceLocation( ".", "Folder" );
Stream io = ResourceGroupManager.Instance.CreateResource( "CreateResource.Test", ResourceGroupManager.DefaultResourceGroupName, true, "." );
Assert.IsNotNull( io );
io.Close();
}
}
}
| mono-soc-2011/axiom | Projects/Tests/Axiom.Tests.Unit/Core/ResourceGroupManager.ManualResourceCreation.Test.cs | C# | lgpl-2.1 | 760 |
// This file is part of the Phoenix CTMS project (www.phoenixctms.org),
// distributed under LGPL v2.1. Copyright (C) 2011 - 2017.
//
package org.phoenixctms.ctsms.service.course.test;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* <p>
* Test case for method <code>getCourseParticipationStatusEntryCount</code> of service <code>CourseService</code>.
* </p>
*
* @see org.phoenixctms.ctsms.service.course.CourseService#getCourseParticipationStatusEntryCount(org.phoenixctms.ctsms.vo.AuthenticationVO, java.lang.Long, java.lang.Long, java.lang.Long)
*/
@Test(groups={"service","CourseService"})
public class CourseService_getCourseParticipationStatusEntryCountTest extends CourseServiceBaseTest {
/**
* Test succes path for service method <code>getCourseParticipationStatusEntryCount</code>
*
* Tests expected behaviour of service method.
*/
@Test
public void testSuccessPath() {
Assert.fail( "Test 'CourseService_getCourseParticipationStatusEntryCountTest.testSuccessPath()}' not implemented." );
}
/*
* Add test methods for each test case of the 'CourseService.org.andromda.cartridges.spring.metafacades.SpringServiceOperationLogicImpl[org.phoenixctms.ctsms.service.course.CourseService.getCourseParticipationStatusEntryCount]()' service method.
*/
/**
* Test special case XYZ for service method <code></code>
*/
/*
@Test
public void testCaseXYZ() {
}
*/
} | phoenixctms/ctsms | core/src/test/java/org/phoenixctms/ctsms/service/course/test/CourseService_getCourseParticipationStatusEntryCountTest.java | Java | lgpl-2.1 | 1,437 |
/*
© 2011 CloudSixteen.com do not share, re-distribute or modify
this file without the permission of its owner(s).
*/
#include "Camera.h"
#include "Display.h"
Camera::Camera()
{
m_bRectDirty = true;
m_worldPos.x = -1.0f;
m_worldPos.y = -1.0f;
m_stack = 0;
m_scale = -1.0f;
m_angle = CL_Angle(-1.0f, CL_AngleUnit::cl_degrees);
Reset();
}
Camera::~Camera() {}
bool Camera::IsInScreenBounds(CL_Vec2f& position)
{
return m_screenBounds.contains(position);
}
void Camera::SetScreenBounds(int x, int y, int w, int h)
{
m_screenBounds.bottom = y + h;
m_screenBounds.right = x + w;
m_screenBounds.left = x;
m_screenBounds.top = y;
AdjustPosition();
}
void Camera::SetWorldBounds(int x, int y, int w, int h)
{
m_worldBounds.bottom = y + h;
m_worldBounds.right = x + w;
m_worldBounds.left = x;
m_worldBounds.top = y;
AdjustPosition();
}
CL_Sizef Camera::GetVisibleArea(bool bNoScale)
{
float scale = (!bNoScale ? m_scale : 1);
float sin = std::abs(m_sin);
float cos = std::abs(m_cos);
CL_Sizef size;
size.width = GetW() / m_scale;
size.height = GetH() / m_scale;
size.width = cos * size.width + sin * size.height;
size.height = sin * size.width + cos * size.height;
size.width = std::min<float>(size.width, (float)m_worldBounds.get_width());
size.height = std::min<float>(size.height, (float)m_worldBounds.get_height());
return size;
}
CL_Rect& Camera::GetScreenBounds()
{
return m_screenBounds;
}
CL_Rectf& Camera::GetWorldRect()
{
if (m_bRectDirty)
{
CL_Sizef visibleArea = GetVisibleArea();
float x = m_worldPos.x - (visibleArea.width * 0.5f);
float y = m_worldPos.y - (visibleArea.height * 0.5f);
m_worldRect = CL_Rectf(x, y, x + visibleArea.width, y + visibleArea.height);
m_bRectDirty = false;
}
return m_worldRect;
}
void Camera::AdjustPosition()
{
CL_Sizef visibleArea = GetVisibleArea();
float worldWidth = (float)m_worldBounds.get_width();
float worldHeight = (float)m_worldBounds.get_height();
float halfWW = visibleArea.width * 0.5f;
float halfWH = visibleArea.height * 0.5f;
float left = m_worldBounds.left + halfWW;
float right = m_worldBounds.left + worldWidth - halfWW;
float top = m_worldBounds.top + halfWH;
float bottom = m_worldBounds.top + worldHeight - halfWH;
m_worldPos.x = floor(cl_clamp(m_worldPos.x, left, right));
m_worldPos.y = floor(cl_clamp(m_worldPos.y, top, bottom));
m_bRectDirty = true;
}
CL_Vec2f Camera::ToScreen(CL_Vec2f& position)
{
CL_Vec2f screenPos;
float x = position.x - m_worldPos.x;
float y = position.y - m_worldPos.y;
screenPos.x = -m_cos*x + m_sin*y;
screenPos.y = -m_sin*x - m_cos*y;
screenPos.x = m_worldPos.x - (screenPos.x / m_scale + m_screenBounds.left);
screenPos.y = m_worldPos.y - (screenPos.y / m_scale + m_screenBounds.top);
return screenPos - GetWorldRect().get_top_left();
}
CL_Vec2f Camera::ToWorld(CL_Vec2f& position)
{
CL_Vec2f worldPos;
float halfW = m_screenBounds.get_width() * 0.5f;
float halfH = m_screenBounds.get_height() * 0.5f;
float x = (position.x - halfW - m_screenBounds.left) / m_scale;
float y = (position.y - halfH - m_screenBounds.top) / m_scale;
worldPos.x = m_cos*x - m_sin*y;
worldPos.y = m_sin*x + m_cos*y;
worldPos.x = worldPos.x + m_worldPos.x;
worldPos.y = worldPos.y + m_worldPos.y;
return worldPos;
}
void Camera::AdjustScale()
{
CL_Sizef visibleArea = GetVisibleArea(true);
float sx = visibleArea.width / m_worldBounds.get_width();
float sy = visibleArea.height / m_worldBounds.get_height();
float newScale = std::max<float>(sx, sy);
m_scale = std::max<float>(m_scale, newScale);
m_bRectDirty = true;
}
void Camera::SetAngle(float angle)
{
if (m_angle.to_degrees() == angle)
return;
m_angle.set_degrees(angle);
m_sin = std::sin(m_angle.to_radians());
m_cos = std::cos(m_angle.to_radians());
AdjustScale();
AdjustPosition();
}
CL_Vec2f& Camera::GetWorldPos()
{
return m_worldPos;
}
CL_Vec2f& Camera::GetDrawPos()
{
return m_worldPos;
}
void Camera::SetWorldPos(CL_Vec2f& position)
{
float x = floor(position.x);
float y = floor(position.y);
if (m_worldPos.x == x && m_worldPos.y == y)
return;
m_worldPos.x = x;
m_worldPos.y = y;
AdjustPosition();
}
void Camera::SetScale(float scale)
{
if (m_scale == scale)
return;
if (scale < 0.0f)
scale = 0.0f;
m_scale = scale;
AdjustScale();
AdjustPosition();
}
float Camera::GetAngle() { return m_angle.to_degrees(); }
float Camera::GetScale()
{
return m_scale;
}
CL_Vec2f& Camera::GetPos()
{
if (m_enabled)
{
return GetDrawPos();
}
else
{
return m_origin;
}
}
bool Camera::IsEnabled()
{
return m_enabled;
}
void Camera::ClearStack() { m_stack = 0; }
void Camera::Begin()
{
CL_GraphicContext graphics = g_Display->Graphics().Object();
if (!m_enabled)
{
graphics.push_cliprect(m_screenBounds);
graphics.push_modelview();
graphics.mult_scale(m_scale, m_scale);
graphics.mult_translate(
((GetW() * 0.5f) + m_screenBounds.left) / m_scale,
((GetH() * 0.5f) + m_screenBounds.top) / m_scale
);
graphics.mult_rotate(m_angle);
graphics.mult_translate(-m_worldPos.x, -m_worldPos.y);
m_enabled = true;
m_stack++;
}
}
void Camera::Finish()
{
CL_GraphicContext graphics = g_Display->Graphics().Object();
if (m_enabled)
{
graphics.pop_modelview();
m_enabled = false;
}
if (m_stack > 0)
{
graphics.pop_cliprect();
m_stack--;
}
}
void Camera::Reset()
{
int screenHeight = g_Display->GetH();
int screenWidth = g_Display->GetW();
SetScreenBounds(0, 0, screenWidth, screenHeight);
SetWorldBounds(0, 0, screenWidth, screenHeight);
SetWorldPos(CL_Vec2f(0.0f, 0.0f));
SetScale(1.0f);
SetAngle(0.0f);
}
int Camera::GetH()
{
return m_screenBounds.get_height();
}
int Camera::GetW()
{
return m_screenBounds.get_width();
}
int Camera::GetX()
{
if (m_enabled)
return m_screenBounds.get_top_left().x;
return int(m_origin.x);
}
int Camera::GetY()
{
if (m_enabled)
return int(floor(m_screenBounds.get_top_left().y));
return int(m_origin.y);
}
void Camera::LuaBind(luabind::object& globals)
{
luabind::module( g_Lua->State() )
[
luabind::class_<Camera>("Camera")
.def("IsInScreenBounds", &Camera::IsInScreenBounds)
.def("SetScreenBounds", &Camera::SetScreenBounds)
.def("SetWorldBounds", &Camera::SetWorldBounds)
.def("GetWorldPos", &Camera::GetWorldPos)
.def("GetWorldRect", &Camera::GetWorldRect)
.def("GetVisibleArea", &Camera::GetVisibleArea)
.def("SetWorldPos", &Camera::SetWorldPos)
.def("GetDrawPos", &Camera::GetDrawPos)
.def("IsEnabled", &Camera::IsEnabled)
.def("SetAngle", &Camera::SetAngle)
.def("GetAngle", &Camera::GetAngle)
.def("ToScreen", &Camera::ToScreen)
.def("ToWorld", &Camera::ToWorld)
.def("GetScale", &Camera::GetScale)
.def("SetScale", &Camera::SetScale)
.def("GetPos", &Camera::GetPos)
.def("Finish", &Camera::Finish)
.def("Begin", &Camera::Begin)
.def("Reset", &Camera::Reset)
.def("GetH", &Camera::GetH)
.def("GetW", &Camera::GetW)
.def("GetX", &Camera::GetX)
.def("GetY", &Camera::GetY)
];
globals["CameraInstance"] = g_Camera;
} | kurozael/codekiddy | source/Camera.cpp | C++ | lgpl-2.1 | 7,053 |
<?php
/**
* kreXX: Krumo eXXtended
*
* kreXX is a debugging tool, which displays structured information
* about any PHP object. It is a nice replacement for print_r() or var_dump()
* which are used by a lot of PHP developers.
*
* kreXX is a fork of Krumo, which was originally written by:
* Kaloyan K. Tsvetkov <kaloyan@kaloyan.info>
*
* @author
* brainworXX GmbH <info@brainworxx.de>
*
* @license
* http://opensource.org/licenses/LGPL-2.1
*
* GNU Lesser General Public License Version 2.1
*
* kreXX Copyright (C) 2014-2022 Brainworxx GmbH
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at
* your option) any later version.
* 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
*/
declare(strict_types=1);
namespace Brainworxx\Krexx\Analyse\Callback\Analyse\Objects;
use Brainworxx\Krexx\Analyse\Callback\AbstractCallback;
use Brainworxx\Krexx\Analyse\Callback\CallbackConstInterface;
use Brainworxx\Krexx\Analyse\Callback\Iterate\ThroughProperties;
use Brainworxx\Krexx\Analyse\Model;
use Brainworxx\Krexx\Service\Factory\Pool;
use Brainworxx\Krexx\Service\Reflection\ReflectionClass;
use Reflector;
/**
* Abstract class for the object analysis.
*/
abstract class AbstractObjectAnalysis extends AbstractCallback implements CallbackConstInterface
{
/**
* Gets the properties from a reflection property of the object.
*
* @param \ReflectionProperty[] $refProps
* The list of the reflection properties.
* @param ReflectionClass $ref
* The reflection of the object we are currently analysing.
* @param string|null $label
* The additional part of the template file. If set, we will use a wrapper
* around the analysis output.
*
* @return string
* The generated markup.
*/
protected function getReflectionPropertiesData(array $refProps, ReflectionClass $ref, string $label = null): string
{
// We are dumping public properties direct into the main-level, without
// any "abstraction level", because they can be accessed directly.
/** @var Model $model */
$model = $this->pool->createClass(Model::class)
->addParameter(static::PARAM_DATA, $refProps)
->addParameter(static::PARAM_REF, $ref)
->injectCallback(
$this->pool->createClass(ThroughProperties::class)
);
if (isset($label)) {
// Protected or private properties.
return $this->pool->render->renderExpandableChild(
$this->dispatchEventWithModel(
static::EVENT_MARKER_ANALYSES_END,
$model->setName($label)
->setType(static::TYPE_INTERNALS)
)
);
}
// Public properties.
// We render them directly in the object "root", so we call
// the render directly.
return $this->dispatchEventWithModel(
static::EVENT_MARKER_ANALYSES_END,
$model
)->renderMe();
}
/**
* Simple sorting callback for reflections.
*
* @param \Reflector $reflectionA
* The first reflection.
* @param \Reflector $reflectionB
* The second reflection.
* @return int
*/
protected function reflectionSorting(Reflector $reflectionA, Reflector $reflectionB): int
{
/** @var \ReflectionMethod | \ReflectionProperty $reflectionA */
/** @var \ReflectionMethod | \ReflectionProperty $reflectionB */
return strcmp($reflectionA->getName(), $reflectionB->getName());
}
}
| brainworxx/kreXX-TYPO3-Extension | Resources/Private/krexx/src/Analyse/Callback/Analyse/Objects/AbstractObjectAnalysis.php | PHP | lgpl-2.1 | 4,204 |
/**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.runtime.type.scope.storage;
import lucee.commons.io.log.Log;
import lucee.runtime.PageContext;
import lucee.runtime.type.StructImpl;
import lucee.runtime.type.dt.DateTimeImpl;
import lucee.runtime.type.scope.ScopeContext;
/**
* client scope that not store it's data
*/
public abstract class StorageScopeMemory extends StorageScopeImpl implements MemoryScope {
private static final long serialVersionUID = -6917303245683342065L;
/**
* Constructor of the class
*
* @param pc
* @param log
* @param name
*/
protected StorageScopeMemory(PageContext pc, String strType, int type, Log log) {
super(new StructImpl(), new DateTimeImpl(pc.getConfig()), null, -1, 1, strType, type);
ScopeContext.info(log, "create new memory based " + strType + " scope for " + pc.getApplicationContext().getName() + "/" + pc.getCFID());
}
/**
* Constructor of the class, clone existing
*
* @param other
*/
protected StorageScopeMemory(StorageScopeMemory other, boolean deepCopy) {
super(other, deepCopy);
}
@Override
public String getStorageType() {
return "Memory";
}
} | jzuijlek/Lucee | core/src/main/java/lucee/runtime/type/scope/storage/StorageScopeMemory.java | Java | lgpl-2.1 | 1,921 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import argparse
import os
import sys
import gettext
def create_users_and_groups(args):
if os.path.exists(args.homes_prefix):
if not os.path.isdir(args.homes_prefix):
print _("path '%s' is not a directory") % args.homes_prefix
return 3
else:
try:
print _("make path to homes: '%s'") % args.homes_prefix
os.makedirs(args.homes_prefix,0755)
except OSError, e:
print e
return 3
user_group_map=dict()
file_descr=open(args.prefix+"user_in_groups_map","r")
for line in file_descr:
tupl=line.split(':')
user=tupl[0].strip()
groups_line=tupl[1].strip()
groups_tupl=groups_line.split(',')
groups=list()
for group in groups_tupl:
groups.append(group.strip(' \t\n\r'))
user_group_map[user]=groups
file_descr.close()
file_descr=open(args.prefix+"groups_map","r")
for line in file_descr:
tupl=line.split(':')
group=tupl[0].strip()
command_line = "groupadd --force '%s'" % group
print _("create group: '%s'") % group
if os.system(command_line):
return 1
#print command_line
file_descr.close()
file_descr=open(args.prefix+"users_map","r")
for line in file_descr:
tupl=line.split(':')
user=tupl[0].strip()
command_line="useradd "
command_line+="--create-home --home \'%s/%s\' " % (args.homes_prefix, user)
command_line+="--gid '%s' " % user_group_map[user][0]
groups_line=""
for i in xrange (1, len(user_group_map[user])):
groups_line+="%s," % user_group_map[user][i]
groups_line=groups_line.strip("\t\r '")
if groups_line != "":
command_line+="--groups '%s'"
command_line+=" '%s'" % user
print _("create user: '%s'") % user
if os.system(command_line):
return 1
#print command_line
file_descr.close()
def delete_users_and_groups(args):
file_descr=open(args.prefix+"users_map","r")
for line in file_descr:
tupl=line.split(':')
user=tupl[0].strip()
command_line="userdel '%s'" % user
print _("delete user: '%s'") % user
if os.system(command_line):
print _(" warning for user '%s'") % user
#print command_line
file_descr.close()
file_descr=open(args.prefix+"groups_map","r")
for line in file_descr:
tupl=line.split(':')
group=tupl[0].strip()
command_line = "groupdel '%s'" % group
print _("delete group: '%s'") % group
if os.system(command_line):
print _(" warning for group '%s'") % group
#print command_line
file_descr.close()
return 0
def main(argv=None):
"""
То, с чего начинается программа
"""
if argv == None:
argv=sys.argv
gettext.install('pseudo-cluster')
parser = argparse.ArgumentParser(
description=\
_("""
Данный скрипт создаёт пользователей и группы,
а так же добавляет пользователей в группы. При этом
пользователи и группы берутся из специальных файлов,
которые предоставляется утилитами разбора статистики.
Например утилитой parse_slurm_db.py
"""),
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
epilog=_("Например можно запустить так:\n ")+argv[0]+" --prefix /tmp/cluster_name_"
)
parser.add_argument(
'--prefix',
dest='prefix',
required=True,
default="./",
help=_("префикс, по которому находятся файлы с отображениями пользователей")
)
parser.add_argument(
'--mode',
dest='mode',
required=False,
choices=["create","delete"],
default="create",
help=\
_("""
определяет режим в котором всё работает:
create -- создаются пользователи и группы,
а так же домашние каталоги
пользователей.
delete -- удаляются пользователи и группы,
каталоги пользователей остаются неизменными.
""")
)
parser.add_argument(
'--homes-prefix',
dest='homes_prefix',
required=False,
default="/home/pseudo_cluster_users",
help=_("префикс, по которому находятся каталоги пользователей псевдокластера")
)
args=parser.parse_args()
if os.geteuid() != 0:
print _("""
Данная программа требует
полномочий пользователя root.
Запустите её от имени пользователя root,
либо с использованием команды sudo.
""")
return 2
if args.mode == "create":
return create_users_and_groups(args)
if args.mode == "delete":
return delete_users_and_groups(args)
return 100
if __name__ == "__main__":
sys.exit(main())
| pseudo-cluster/pseudo-cluster | scripts/pseudo_users_and_groups_operations.py | Python | lgpl-2.1 | 5,936 |
/* THIS FILE IS A MEMBER OF THE COFFEESHOP LIBRARY
*
* License:
*
* Coffeeshop is a conglomerate of handy general purpose Java classes.
*
* Copyright (C) 2006-2008 Luka Cehovin
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* 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.
*
* http://www.opensource.org/licenses/lgpl-license.php
*
* 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
*
*/
package org.coffeeshop.application;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.coffeeshop.arguments.Arguments;
import org.coffeeshop.arguments.ArgumentsException;
import org.coffeeshop.arguments.ArgumentsResult;
import org.coffeeshop.arguments.FlaggedOption;
import org.coffeeshop.arguments.Parameter;
import org.coffeeshop.arguments.Switch;
import org.coffeeshop.arguments.UnflaggedOption;
import org.coffeeshop.external.OperatingSystem;
import org.coffeeshop.io.Files;
import org.coffeeshop.io.TempDirectory;
import org.coffeeshop.log.Logger;
import org.coffeeshop.settings.Settings;
import org.coffeeshop.settings.ReadableSettings;
import org.coffeeshop.settings.PropertiesSettings;
import org.coffeeshop.settings.SettingsNotFoundException;
import org.coffeeshop.string.parsers.StringParser;
/**
* This is the main application class that an application should override to use
* CoffeeShop toolbox.
*
*
* @author luka
* @since CoffeeShop 1.0
*/
public abstract class Application {
public interface SettingsSetter {
public boolean addDefaultElement(String key, String value, String description, String shortFlag, String longFlag, StringParser parser);
public boolean addDefaultElement(String key, String value, String description);
}
/**
* Generates a suitable storage directory path according to the current user
* and the underlying operating system.
*
* @param a
* the application descriptor
* @return the suitable storage directory path according to the current user
* and the underlying operating system.
*/
public static File applicationStorageDirectory(Application a) {
return new File(OperatingSystem.getSystemConfigurationDirectory(), a.getUnixName());
}
/**
* Attempt to load default settings from the location of the application class.
*
* @return {@link ReadableSettings} object or <code>null</code>.
*/
private ReadableSettings loadDefaults() {
InputStream stream = this.getClass().getResourceAsStream("defaults.ini");
if (stream == null) return null;
PropertiesSettings settings = new PropertiesSettings();
try {
settings.loadSettings(stream);
return settings;
} catch (IOException e) {
return null;
}
}
private class ApplicationSettingsImpl extends Settings implements SettingsSetter {
private static final String PASSTHROUGH_ARGUMENTS_ID = "__coffeeshop.passthrough";
private class DefaultElement {
public String value, description;
public DefaultElement(String value, String description) {
if (value == null)
throw new IllegalArgumentException("Must define default value");
this.value = value;
this.description = description;
}
}
private class ArgumentElement extends DefaultElement {
private String longFlag = null;
private char shortFlag = 0;
private StringParser parser;
public ArgumentElement(String value, String description, String shortFlag, String longFlag, StringParser parser) {
super(value, description);
if (shortFlag != null) {
if (shortFlag.length() != 1)
throw new IllegalArgumentException("Short flag must be only one character or null");
this.shortFlag = shortFlag.charAt(0);
}
this.longFlag = longFlag;
if (shortFlag == null && longFlag == null)
throw new IllegalArgumentException("At least one flag type must be set");
this.parser = parser;
}
}
protected HashMap<String, DefaultElement> map = new HashMap<String, DefaultElement>();
private boolean modified = false;
private Arguments argumentsParser = null;
private ArgumentsResult reconfigured;
private PropertiesSettings storage = null;
public ApplicationSettingsImpl(Application a) {
super(null);
this.storage = Application.getApplication().getSettingsManager().getSettings(Application.getApplication().getSubname().toLowerCase() + ".ini", loadDefaults());
}
public boolean addDefaultElement(String key, String value, String description, String shortFlag, String longFlag, StringParser parser) {
return addDefaultElement(key, new ArgumentElement(value, description, shortFlag, longFlag, parser));
}
public boolean addDefaultElement(String key, String value, String description) {
return addDefaultElement(key, new DefaultElement(value, description));
}
protected boolean addDefaultElement(String key, DefaultElement e) {
if (key.equals(PASSTHROUGH_ARGUMENTS_ID))
throw new IllegalArgumentException("This is the only illegal key and you must use this one!?");
if (map.containsKey(key))
return false;
map.put(key, e);
return true;
}
public String[] parseArguments(String[] args) throws ArgumentsException {
if (argumentsParser == null || modified) {
argumentsParser = new Arguments();
Set<String> keys = map.keySet();
Switch help = new Switch("help").setLongFlag("help").setShortFlag('h');
help.setHelp("Display this message and exit.");
argumentsParser.registerParameter(help);
for (String key : keys) {
DefaultElement d = map.get(key);
if (!(d instanceof ArgumentElement))
continue;
Parameter p = makeParameter(key, (ArgumentElement)d);
argumentsParser.registerParameter(p);
}
UnflaggedOption passthrough = new UnflaggedOption(PASSTHROUGH_ARGUMENTS_ID);
passthrough.setGreedy(true);
argumentsParser.registerParameter(passthrough);
}
reconfigured = argumentsParser.parse(args);
if (!reconfigured.success()) {
Iterator<?> i = reconfigured.getErrorMessageIterator();
for (; i.hasNext(); ) {
System.out.println((String) i.next());
}
System.exit(5000);
}
if (reconfigured.getBoolean("help")) {
System.out.println(argumentsParser.getHelp());
System.exit(0);
}
return reconfigured.getStringArray(PASSTHROUGH_ARGUMENTS_ID);
}
protected String getProperty(String key) {
if (reconfigured != null) {
Object o = reconfigured.getObject(key);
if (o != null)
return o.toString();
}
if (storage == null) return null;
try {
String s = storage.getString(key);
return s;
} catch (SettingsNotFoundException e) {}
DefaultElement e = map.get(key);
if (e == null) return null;
return e.value;
}
private Parameter makeParameter(String name, ArgumentElement e) {
if (e.parser == null) {
Switch s = new Switch(name);
if (e.description != null)
s.setHelp(e.description);
if (e.longFlag != null)
s.setLongFlag(e.longFlag);
if (e.shortFlag != 0)
s.setShortFlag(e.shortFlag);
return s;
} else {
FlaggedOption o = new FlaggedOption(name);
if (e.description != null)
o.setHelp(e.description);
if (e.longFlag != null)
o.setLongFlag(e.longFlag);
if (e.shortFlag != 0)
o.setShortFlag(e.shortFlag);
o.setStringParser(e.parser);
return o;
}
}
public boolean isModified() {
return storage.isModified();
}
public void touch() {
storage.touch();
}
public void remove(String key) {
storage.remove(key);
}
@Override
public Set<String> getKeys() {
return storage.getAllKeys();
}
@Override
protected String setProperty(String key, String value) {
String old = getString(key, null);
storage.setString(key, value);
notifySettingsChanged(key, old, value);
return value;
}
}
private static Application application = null;
private String name, subname;
private SettingsManager settingsManager;
private Logger logger;
private ApplicationSettingsImpl settings;
private String[] arguments;
private TempDirectory temp = null;
/**
* Get the current application object
*
* @return current application object
*/
public static final Application getApplication() {
if (application == null)
throw new RuntimeException("No application object created.");
return application;
}
public static final Logger getApplicationLogger() {
return getApplication().getLogger();
}
public static final Settings getApplicationSettings() {
return getApplication().getSettings();
}
/**
* Constructs new application object
*
* @param name applicaton name (only literals and numerals are accepted)
* @param arguments command line arguments
*/
public Application(String name, String subname, String[] arguments) throws ArgumentsException {
if (application != null)
throw new RuntimeException("Only one application object allowed.");
application = this;
if (name.matches("[^A-Za-z0-9]"))
throw new IllegalArgumentException(
"Name of the application must contain only alphanumerical characters");
this.name = name;
this.subname = subname;
settingsManager = new SettingsManager(this);
processArguments(arguments);
initializeLogging();
}
public Application(String name, String[] arguments) throws ArgumentsException {
this(name, name, arguments);
}
/**
* Get applicaton name
*
* @return application name
*/
public String getName() {
return name;
}
public String getSubname() {
return subname;
}
/**
* Get application UNIX style name (lowercase)
*
* @return UNIX style name
*/
public final String getUnixName() {
return name.toLowerCase();
}
/**
* Get application settings manager
*
* @return settings manager
* @see SettingsManager
*/
public final SettingsManager getSettingsManager() {
return settingsManager;
}
/**
* Get application logger
*
* @return application logger
* @see Logger
*/
public Logger getLogger() {
if (logger == null)
logger = new Logger();
return logger;
}
public final String[] getArguments() {
return arguments;
}
public final Settings getSettings() {
return settings;
}
/**
* Get application short description
*
* @return short application description
*/
public abstract String getShortDescription();
protected abstract void defineDefaults(SettingsSetter setter);
private void processArguments(String[] arguments) throws ArgumentsException {
ApplicationSettingsImpl a = new ApplicationSettingsImpl(this);
defineDefaults(a);
this.arguments = a.parseArguments(arguments);
settings = a;
}
private void initializeLogging() {
int history = 0;
try {
history = Integer.parseInt(System.getProperty("coffeeshop.application.logging"));
} catch (NumberFormatException e) {}
if (history < 1)
return;
File logdir = new File(applicationStorageDirectory(getApplication()), "logs");
Files.makeDirectory(logdir);
File[] logs = logdir.listFiles();
if (logs.length > history - 1) {
Arrays.sort(logs, new Comparator<File>() {
@Override
public int compare(File f0, File f1) {
if (f0.lastModified() < f1.lastModified())
return -1;
if (f0.lastModified() > f1.lastModified())
return 1;
return 0;
}
});
for (int i = 0; i < logs.length - history + 1; i++) {
logs[i].delete();
}
}
try {
PrintStream log = new PrintStream(new File(logdir, String.format("log-%s.txt",
new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()))));
getApplicationLogger().addOutputStream(log);
} catch (FileNotFoundException e) { }
}
public TempDirectory getTempDirectory() {
if (temp == null)
temp = new TempDirectory(getUnixName());
return temp;
}
/**
* Get application long description
*
* @return long application description
*/
public abstract String getLongDescription();
@Override
public String toString() {
return "Application: " + getName();
}
}
| lukacu/coffeeshop | application/org/coffeeshop/application/Application.java | Java | lgpl-2.1 | 13,272 |
// Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Statistics.Distributions.Univariate
{
using Accord.Math;
using Accord.Math.Optimization;
using Accord.Statistics.Distributions;
using Accord.Statistics.Distributions.Fitting;
using AForge;
using System;
using System.ComponentModel;
/// <summary>
/// The 4-parameter Beta distribution.
/// </summary>
///
/// <remarks>
/// <para>
/// The generalized beta distribution is a family of continuous probability distributions defined
/// on any interval (min, max) parameterized by two positive shape parameters and two real location
/// parameters, typically denoted by α, β, a and b. The beta distribution can be suited to the
/// statistical modeling of proportions in applications where values of proportions equal to 0 or 1
/// do not occur. One theoretical case where the beta distribution arises is as the distribution of
/// the ratio formed by one random variable having a Gamma distribution divided by the sum of it and
/// another independent random variable also having a Gamma distribution with the same scale parameter
/// (but possibly different shape parameter).</para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description><a href="http://en.wikipedia.org/wiki/Beta_distribution">
/// Wikipedia, The Free Encyclopedia. Beta distribution.
/// Available from: http://en.wikipedia.org/wiki/Beta_distribution </a></description></item>
/// <item><description><a href="https://en.wikipedia.org/wiki/Three-point_estimation">
/// Wikipedia, The Free Encyclopedia. Three-point estimation.
/// Available from: https://en.wikipedia.org/wiki/Three-point_estimation </a></description></item>
/// <item><description><a href="http://broadleaf.com.au/resource-material/beta-pert-origins/">
/// Broadleaf Capital International Pty Ltd. Beta PERT origins.
/// Available from: http://broadleaf.com.au/resource-material/beta-pert-origins/ </a></description></item>
/// <item><description><a href="http://mech.vub.ac.be/teaching/info/Ontwerpmethodologie/Appendix%20les%202%20PERT.pdf">
/// Malcolm, D. G., Roseboom J. H., Clark C.E., and Fazar, W. Application of a technique of research
/// and development program evaluation, Operations Research, 7, 646-669, 1959. Available from:
/// http://mech.vub.ac.be/teaching/info/Ontwerpmethodologie/Appendix%20les%202%20PERT.pdf </a></description></item>
/// <item><description><a href="http://connection.ebscohost.com/c/articles/18246172/pert-model-distribution-activity-time">
/// Clark, C. E. The PERT model for the distribution of an activity time, Operations Research, 10, 405-406,
/// 1962. Available from: http://connection.ebscohost.com/c/articles/18246172/pert-model-distribution-activity-time </a></description></item>
/// </list></para>
/// </remarks>
///
/// <example>
/// <para>
/// Note: Simpler examples are also available at the <see cref="BetaDistribution"/> page.</para>
///
/// <para>
/// The following example shows how to create a 4-parameter Beta distribution and
/// compute some of its properties and measures.</para>
///
/// <code>
/// // Create a 4-parameter Beta distribution with the following parameters (α, β, a, b):
/// var beta = new GeneralizedBetaDistribution(alpha: 1.42, beta: 1.57, min: 1, max: 4.2);
///
/// double mean = beta.Mean; // 2.5197324414715716
/// double median = beta.Median; // 2.4997705845160225
/// double var = beta.Variance; // 0.19999664152943961
/// double mode = beta.Mode; // 2.3575757575757574
/// double h = beta.Entropy; // -0.050654548091478513
///
/// double cdf = beta.DistributionFunction(x: 2.27); // 0.40828630817664596
/// double pdf = beta.ProbabilityDensityFunction(x: 2.27); // 1.2766172921464953
/// double lpdf = beta.LogProbabilityDensityFunction(x: 2.27); // 0.2442138392176838
///
/// double chf = beta.CumulativeHazardFunction(x: 2.27); // 0.5247323897609667
/// double hf = beta.HazardFunction(x: 2.27); // 2.1574915534109484
///
/// double ccdf = beta.ComplementaryDistributionFunction(x: 2.27); // 0.59171369182335409
/// double icdf = beta.InverseDistributionFunction(p: cdf); // 2.27
///
/// string str = beta.ToString(); // B(x; α = 1.42, β = 1.57, min = 1, max = 4.2)
/// </code>
///
/// <para>
/// The following example shows how to create a 4-parameter Beta distribution
/// with a three-point estimate using PERT.</para>
///
/// <code>
/// // Create a Beta from a minimum, maximum and most likely value
/// var b = GeneralizedBetaDistribution.Pert(min: 1, max: 3, mode: 2);
///
/// double mean = b.Mean; // 2.5197324414715716
/// double median = b.Median; // 2.4997705845160225
/// double var = b.Variance; // 0.19999664152943961
/// double mode = b.Mode; // 2.3575757575757574
/// </code>
///
/// <para>
/// The following example shows how to create a 4-parameter Beta distribution
/// with a three-point estimate using Vose's modification for PERT.</para>
///
/// <code>
/// // Create a Beta from a minimum, maximum and most likely value
/// var b = GeneralizedBetaDistribution.Vose(min: 1, max: 3, mode: 1.42);
///
/// double mean = b.Mean; // 1.6133333333333333
/// double median = b.Median; // 1.5727889200146494
/// double mode = b.Mode; // 1.4471823077804513
/// double var = b.Variance; // 0.055555555555555546
/// </code>
///
/// <para>
/// The next example shows how to generate 1000 new samples from a Beta distribution:</para>
///
/// <code>
/// // Using the distribution's parameters
/// double[] samples = GeneralizedBetaDistribution
/// .Random(alpha: 2, beta: 3, min: 0, max: 1, samples: 1000);
///
/// // Using an existing distribution
/// var b = new GeneralizedBetaDistribution(alpha: 1, beta: 2);
/// double[] new_samples = b.Generate(1000);
/// </code>
///
/// <para>
/// And finally, how to estimate the parameters of a Beta distribution from
/// a set of observations, using either the Method-of-moments or the Maximum
/// Likelihood Estimate.</para>
///
/// <code>
/// // First we will be drawing 100000 observations from a 4-parameter
/// // Beta distribution with α = 2, β = 3, min = 10 and max = 15:
///
/// double[] samples = GeneralizedBetaDistribution
/// .Random(alpha: 2, beta: 3, min: 10, max: 15, samples: 100000);
///
/// // We can estimate a distribution with the known max and min
/// var B = GeneralizedBetaDistribution.Estimate(samples, 10, 15);
///
/// // We can explicitly ask for a Method-of-moments estimation
/// var mm = GeneralizedBetaDistribution.Estimate(samples, 10, 15,
/// new GeneralizedBetaOptions { Method = BetaEstimationMethod.Moments });
///
/// // or explicitly ask for the Maximum Likelihood estimation
/// var mle = GeneralizedBetaDistribution.Estimate(samples, 10, 15,
/// new GeneralizedBetaOptions { Method = BetaEstimationMethod.MaximumLikelihood });
/// </code>
/// </example>
///
/// <seealso cref="BetaDistribution"/>
///
[Serializable]
public class GeneralizedBetaDistribution : UnivariateContinuousDistribution,
ISampleableDistribution<double>, IFittableDistribution<double, GeneralizedBetaOptions>
{
// Distribution parameters
private double alpha; // α
private double beta; // β
private double min;
private double max;
double constant;
double? entropy;
/// <summary>
/// Constructs a Beta distribution defined in the
/// interval (0,1) with the given parameters α and β.
/// </summary>
///
/// <param name="alpha">The shape parameter α (alpha).</param>
/// <param name="beta">The shape parameter β (beta).</param>
///
public GeneralizedBetaDistribution([Positive] double alpha, [Positive] double beta)
: this(alpha, beta, 0, 1)
{
}
/// <summary>
/// Constructs a Beta distribution defined in the
/// interval (a, b) with parameters α, β, a and b.
/// </summary>
///
/// <param name="alpha">The shape parameter α (alpha).</param>
/// <param name="beta">The shape parameter β (beta).</param>
/// <param name="min">The minimum possible value a.</param>
/// <param name="max">The maximum possible value b.</param>
///
public GeneralizedBetaDistribution([Positive] double alpha, [Positive] double beta,
[Real, DefaultValue(0)] double min, [Real, DefaultValue(1)] double max)
{
if (min > max)
{
throw new ArgumentOutOfRangeException("max",
"The maximum value 'max' must be greater than the minimum value 'min'.");
}
if (alpha <= 0)
throw new ArgumentOutOfRangeException("alpha", "The shape parameter alpha must be positive.");
if (beta <= 0)
throw new ArgumentOutOfRangeException("beta", "The shape parameter beta must be positive.");
initialize(min, max, alpha, beta);
}
/// <summary>
/// Constructs a BetaPERT distribution defined in the interval (a, b)
/// using Vose's PERT estimation for the parameters a, b, mode and λ.
/// </summary>
///
/// <param name="min">The minimum possible value a.</param>
/// <param name="max">The maximum possible value b.</param>
/// <param name="mode">The most likely value m.</param>
///
/// <returns>
/// A Beta distribution initialized using the Vose's PERT method.
/// </returns>
///
public static GeneralizedBetaDistribution Vose(double min, double max, double mode)
{
return Vose(min, max, mode, 4);
}
/// <summary>
/// Constructs a BetaPERT distribution defined in the interval (a, b)
/// using Vose's PERT estimation for the parameters a, b, mode and λ.
/// </summary>
///
/// <param name="min">The minimum possible value a.</param>
/// <param name="max">The maximum possible value b.</param>
/// <param name="mode">The most likely value m.</param>
/// <param name="scale">The scale parameter λ (lambda). Default is 4.</param>
///
/// <returns>
/// A Beta distribution initialized using the Vose's PERT method.
/// </returns>
///
public static GeneralizedBetaDistribution Vose(double min, double max, double mode, double scale)
{
// http://pubsonline.informs.org/doi/pdf/10.1287/ited.1080.0013
double mu = (min + scale * mode + max) / (scale + 2);
double sd = (max - min) / (scale + 2);
// Vise's equations for the Beta distribution:
double alpha = ((mu - min) / (max - min)) * ((((mu - min) * (max - mu)) / (sd * sd)) - 1);
double beta = alpha * (max - mu) / (mu - min);
return new GeneralizedBetaDistribution(alpha, beta, min, max);
}
/// <summary>
/// Constructs a BetaPERT distribution defined in the interval (a, b)
/// using usual PERT estimation for the parameters a, b, mode and λ.
/// </summary>
///
/// <param name="min">The minimum possible value a.</param>
/// <param name="max">The maximum possible value b.</param>
/// <param name="mode">The most likely value m.</param>
///
/// <returns>
/// A Beta distribution initialized using the PERT method.
/// </returns>
///
public static GeneralizedBetaDistribution Pert(double min, double max, double mode)
{
return Pert(min, max, mode, 4);
}
/// <summary>
/// Constructs a BetaPERT distribution defined in the interval (a, b)
/// using usual PERT estimation for the parameters a, b, mode and λ.
/// </summary>
///
/// <param name="min">The minimum possible value a.</param>
/// <param name="max">The maximum possible value b.</param>
/// <param name="mode">The most likely value m.</param>
/// <param name="scale">The scale parameter λ (lambda). Default is 4.</param>
///
/// <returns>
/// A Beta distribution initialized using the PERT method.
/// </returns>
///
public static GeneralizedBetaDistribution Pert(double min, double max, double mode, double scale)
{
double mu = (min + scale * mode + max) / (scale + 2);
double alpha = 1 + scale / 2;
// Standard equations for the Beta distribution:
if (mu != mode)
alpha = ((mu - min) * (2 * mode - min - max)) / ((mode - mu) * (max - min));
double beta = alpha * (max - mu) / (mu - min);
return new GeneralizedBetaDistribution(alpha, beta, min, max);
}
/// <summary>
/// Constructs a BetaPERT distribution defined in the interval (a, b)
/// using Golenko-Ginzburg observation that the mode is often at 2/3
/// of the guessed interval.
/// </summary>
///
/// <param name="min">The minimum possible value a.</param>
/// <param name="max">The maximum possible value b.</param>
///
/// <returns>
/// A Beta distribution initialized using the Golenko-Ginzburg's method.
/// </returns>
///
public static GeneralizedBetaDistribution GolenkoGinzburg(double min, double max)
{
return new GeneralizedBetaDistribution(2, 3, min, max);
}
/// <summary>
/// Constructs a standard Beta distribution defined in the interval (0, 1)
/// based on the number of successed and trials for an experiment.
/// </summary>
///
/// <param name="successes">The number of success <c>r</c>. Default is 0.</param>
/// <param name="trials">The number of trials <c>n</c>. Default is 1.</param>
///
/// <returns>
/// A standard Beta distribution initialized using the given parameters.
/// </returns>
///
public static GeneralizedBetaDistribution Standard(int successes, int trials)
{
return new GeneralizedBetaDistribution(successes + 1, trials - successes + 1);
}
/// <summary>
/// Gets the minimum value A.
/// </summary>
///
public double Min { get { return min; } }
/// <summary>
/// Gets the maximum value B.
/// </summary>
///
public double Max { get { return max; } }
/// <summary>
/// Gets the shape parameter α (alpha)
/// </summary>
///
public double Alpha
{
get { return alpha; }
}
/// <summary>
/// Gets the shape parameter β (beta).
/// </summary>
///
public double Beta
{
get { return beta; }
}
/// <summary>
/// Gets the mean for this distribution,
/// defined as (a + 4 * m + 6 * b).
/// </summary>
///
/// <value>
/// The distribution's mean value.
/// </value>
///
public override double Mean
{
get
{
double mu = alpha / (alpha + beta);
return mu * (max - min) + min;
}
}
/// <summary>
/// Gets the variance for this distribution,
/// defined as ((b - a) / (k+2))²
/// </summary>
///
/// <value>
/// The distribution's variance.
/// </value>
///
public override double Variance
{
get
{
double var = (alpha * beta) / ((alpha + beta) * (alpha + beta) * (alpha + beta + 1));
return var * (max - min);
}
}
/// <summary>
/// Gets the mode for this distribution.
/// </summary>
///
/// <remarks>
/// The beta distribution's mode is given
/// by <c>(a - 1) / (a + b - 2).</c>
/// </remarks>
///
/// <value>
/// The distribution's mode value.
/// </value>
///
public override double Mode
{
get
{
double mode = (alpha - 1.0) / (alpha + beta - 2.0);
return mode * (max - min) + min;
}
}
/// <summary>
/// Gets the distribution support, defined as (<see cref="Min"/>, <see cref="Max"/>).
/// </summary>
///
public override DoubleRange Support
{
get { return new DoubleRange(min, max); }
}
/// <summary>
/// Gets the entropy for this distribution.
/// </summary>
///
/// <value>The distribution's entropy.</value>
///
public override double Entropy
{
get
{
if (entropy == null)
{
double lnBab = Math.Log(Accord.Math.Beta.Function(alpha, beta));
double da = Gamma.Digamma(alpha);
double db = Gamma.Digamma(beta);
double dab = Gamma.Digamma(alpha + beta);
entropy = lnBab - (alpha - 1) * da - (beta - 1) * db + (alpha + beta - 2) * dab;
}
return entropy.Value;
}
}
/// <summary>
/// Gets the cumulative distribution function (cdf) for
/// this distribution evaluated at point <c>x</c>.
/// </summary>
///
/// <param name="x">A single point in the distribution range.</param>
///
public override double DistributionFunction(double x)
{
if (x < min)
return 0;
if (x >= max)
return 1;
double z = (x - min) / (max - min);
return Accord.Math.Beta.Incomplete(alpha, beta, z);
}
/// <summary>
/// Gets the inverse of the cumulative distribution function (icdf) for
/// this distribution evaluated at probability <c>p</c>. This function
/// is also known as the Quantile function.
/// </summary>
///
/// <param name="p">A probability value between 0 and 1.</param>
///
/// <returns>A sample which could original the given probability
/// value when applied in the <see cref="DistributionFunction"/>.</returns>
///
public override double InverseDistributionFunction(double p)
{
if (p <= 0)
return min;
if (p >= 1)
return max;
double z = Accord.Math.Beta.IncompleteInverse(alpha, beta, p);
double x = z * (max - min) + min;
return x;
}
/// <summary>
/// Gets the probability density function (pdf) for
/// this distribution evaluated at point <c>x</c>.
/// </summary>
///
/// <param name="x">A single point in the distribution range.</param>
///
/// <returns>
/// The probability of <c>x</c> occurring in the current distribution.
/// </returns>
///
public override double ProbabilityDensityFunction(double x)
{
if (x <= min || x >= max)
return 0;
double z = (x - min) / (max - min);
return constant * Math.Pow(z, alpha - 1) * Math.Pow(1 - z, beta - 1);
}
/// <summary>
/// Gets the log-probability density function (pdf) for
/// this distribution evaluated at point <c>x</c>.
/// </summary>
///
/// <param name="x">A single point in the distribution range.</param>
///
/// <returns>
/// The logarithm of the probability of <c>x</c>
/// occurring in the current distribution.
/// </returns>
///
/// <remarks>
/// <para>
/// The Probability Density Function (PDF) describes the
/// probability that a given value <c>x</c> will occur.</para>
/// </remarks>
///
/// <seealso cref="ProbabilityDensityFunction"/>
///
public override double LogProbabilityDensityFunction(double x)
{
if (x <= min || x >= max)
return Double.NegativeInfinity;
double z = (x - min) / (max - min);
return Math.Log(constant) + (alpha - 1) * Math.Log(z) + (beta - 1) * Math.Log(1 - z);
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
///
public override object Clone()
{
return new GeneralizedBetaDistribution(alpha, beta, min, max);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
///
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
///
public override string ToString(string format, IFormatProvider formatProvider)
{
return String.Format(formatProvider, "B(x; α = {0}, β = {1}, min = {2}, max = {3})",
alpha.ToString(format, formatProvider),
beta.ToString(format, formatProvider),
min.ToString(format, formatProvider),
max.ToString(format, formatProvider));
}
private void initialize(double min, double max, double alpha, double beta)
{
this.alpha = alpha;
this.beta = beta;
this.min = min;
this.max = max;
this.constant = 1.0 / Accord.Math.Beta.Function(alpha, beta);
this.entropy = null;
}
private void fitMoments(double min, double max, double mean, double var)
{
double length = (max - min);
mean = (mean - min) / length;
var = var / (length * length);
if (var >= mean * (1.0 - mean))
throw new NotSupportedException();
double u = (mean * (1 - mean) / var) - 1.0;
double alpha = mean * u;
double beta = (1 - mean) * u;
initialize(min, max, alpha, beta);
}
/// <summary>
/// Fits the underlying distribution to a given set of observations.
/// </summary>
///
/// <param name="observations">
/// The array of observations to fit the model against. The array
/// elements can be either of type double (for univariate data) or
/// type double[] (for multivariate data).</param>
/// <param name="weights">The weight vector containing the weight for each of the samples.</param>
/// <param name="options">Optional arguments which may be used during fitting,
/// such as regularization constants and additional parameters.</param>
///
public override void Fit(double[] observations, double[] weights, IFittingOptions options)
{
Fit(observations, weights, options as GeneralizedBetaOptions);
}
/// <summary>
/// Fits the underlying distribution to a given set of observations.
/// </summary>
///
/// <param name="observations">
/// The array of observations to fit the model against. The array
/// elements can be either of type double (for univariate data) or
/// type double[] (for multivariate data).</param>
/// <param name="weights">The weight vector containing the weight for each of the samples.</param>
/// <param name="options">Optional arguments which may be used during fitting,
/// such as regularization constants and additional parameters.</param>
///
public override void Fit(double[] observations, int[] weights, IFittingOptions options)
{
Fit(observations, weights, options as GeneralizedBetaOptions);
}
/// <summary>
/// Fits the underlying distribution to a given set of observations.
/// </summary>
///
/// <param name="observations">The array of observations to fit the model against.
/// The array elements can be either of type double (for univariate data) or type
/// double[] (for multivariate data).
/// </param>
/// <param name="weights">The weight vector containing the weight for each of the samples.</param>
/// <param name="options">Optional arguments which may be used during fitting,
/// such as regularization constants and additional parameters.</param>
///
public void Fit(double[] observations, double[] weights, GeneralizedBetaOptions options)
{
bool fixMax = true;
bool fixMin = true;
bool sorted = false;
bool useMLE = false;
int imax = -1;
int imin = -1;
if (options != null)
{
fixMax = options.FixMax;
fixMin = options.FixMin;
sorted = options.IsSorted;
imin = options.MinIndex;
imax = options.MaxIndex;
useMLE = options.Method == BetaEstimationMethod.MaximumLikelihood;
}
if (!sorted)
Array.Sort(observations, weights);
if (!fixMin)
min = TriangularDistribution.GetMin(observations, weights, out imin);
if (!fixMax)
max = TriangularDistribution.GetMax(observations, weights, out imax);
if (imin == -1)
imin = TriangularDistribution.FindMin(observations, min);
if (imax == -1)
imax = TriangularDistribution.FindMax(observations, max);
double mean = GetMean(observations, weights, imin, imax);
double var = GetVariance(observations, weights, mean, imin, imax);
fitMoments(min, max, mean, var);
if (useMLE)
{
if (weights == null)
{
double sum1 = 0, sum2 = 0;
for (int i = imin; i <= imax; i++)
{
sum1 += Math.Log(observations[i]);
sum2 += Math.Log(1 - observations[i]);
}
fitMLE(sum1, sum2, observations.Length);
}
else
{
double sum1 = 0, sum2 = 0, sumw = 0;
for (int i = imin; i <= imax; i++)
{
sum1 += Math.Log(observations[i]) * weights[i];
sum2 += Math.Log(1 - observations[i]) * weights[i];
sumw += weights[i];
}
fitMLE(sum1, sum2, sumw);
}
}
}
/// <summary>
/// Fits the underlying distribution to a given set of observations.
/// </summary>
///
/// <param name="observations">The array of observations to fit the model against.
/// The array elements can be either of type double (for univariate data) or type
/// double[] (for multivariate data).
/// </param>
/// <param name="weights">The weight vector containing the weight for each of the samples.</param>
/// <param name="options">Optional arguments which may be used during fitting,
/// such as regularization constants and additional parameters.</param>
///
public void Fit(double[] observations, int[] weights, GeneralizedBetaOptions options)
{
bool fixMax = true;
bool fixMin = true;
bool sorted = false;
bool useMLE = false;
int imax = -1;
int imin = -1;
if (options != null)
{
fixMax = options.FixMax;
fixMin = options.FixMin;
sorted = options.IsSorted;
imin = options.MinIndex;
imax = options.MaxIndex;
useMLE = options.Method == BetaEstimationMethod.MaximumLikelihood;
}
if (!sorted)
Array.Sort(observations, weights);
if (!fixMin)
min = TriangularDistribution.GetMin(observations, weights, out imin);
if (!fixMax)
max = TriangularDistribution.GetMax(observations, weights, out imax);
if (imin == -1)
imin = TriangularDistribution.FindMin(observations, min);
if (imax == -1)
imax = TriangularDistribution.FindMax(observations, max);
double mean = GetMean(observations, weights, imin, imax);
double var = GetVariance(observations, weights, mean, imin, imax);
fitMoments(min, max, mean, var);
if (useMLE)
{
if (weights == null)
{
double sum1 = 0, sum2 = 0;
for (int i = imin; i <= imax; i++)
{
sum1 += Math.Log(observations[i]);
sum2 += Math.Log(1 - observations[i]);
}
fitMLE(sum1, sum2, observations.Length);
}
else
{
double sum1 = 0, sum2 = 0, sumw = 0;
for (int i = imin; i <= imax; i++)
{
sum1 += Math.Log(observations[i]) * weights[i];
sum2 += Math.Log(1 - observations[i]) * weights[i];
sumw += weights[i];
}
fitMLE(sum1, sum2, sumw);
}
}
}
private static double GetMean(double[] observations, double[] weights, int imin, int imax)
{
double mean;
if (weights == null)
{
double sum = 0;
for (int i = imin; i <= imax; i++)
sum += observations[i];
mean = sum / (imax - imin + 1);
}
else
{
double sum = 0;
double weightSum = 0;
for (int i = imin; i <= imax; i++)
{
sum += weights[i] * observations[i];
weightSum += weights[i];
}
mean = sum / weightSum;
}
return mean;
}
private void fitMLE(double sum1, double sum2, double n)
{
double[] gradient = new double[2];
var bfgs = new BoundedBroydenFletcherGoldfarbShanno(numberOfVariables: 2);
bfgs.LowerBounds[0] = 1e-100;
bfgs.LowerBounds[1] = 1e-100;
bfgs.Solution[0] = this.alpha;
bfgs.Solution[1] = this.beta;
bfgs.Function = (double[] parameters) =>
BetaDistribution.LogLikelihood(sum1, sum2, n, parameters[0], parameters[1]);
bfgs.Gradient = (double[] parameters) =>
BetaDistribution.Gradient(sum1, sum2, n, parameters[0], parameters[1], gradient);
if (!bfgs.Minimize())
throw new ConvergenceException();
this.alpha = bfgs.Solution[0];
this.beta = bfgs.Solution[1];
}
private static double GetVariance(double[] observations, double[] weights, double mean, int imin, int imax)
{
double variance;
if (weights == null)
{
double sum = 0;
for (int i = imin; i <= imax; i++)
sum += (observations[i] - mean) * (observations[i] - mean);
variance = sum / (imax - imin);
}
else
{
double sum = 0.0;
double squareSum = 0.0;
double weightSum = 0.0;
for (int i = 0; i < observations.Length; i++)
{
double z = observations[i] - mean;
double w = weights[i];
sum += w * (z * z);
weightSum += w;
squareSum += w * w;
}
// variance = sum / weightSum;
variance = sum / (weightSum - (squareSum / weightSum));
}
return variance;
}
private static double GetMean(double[] observations, int[] weights, int imin, int imax)
{
double mean;
if (weights == null)
{
double sum = 0;
for (int i = imin; i <= imax; i++)
sum += observations[i];
mean = sum / (imax - imin);
}
else
{
double sum = 0;
double weightSum = 0;
for (int i = imin; i <= imax; i++)
{
sum += weights[i] * observations[i];
weightSum += weights[i];
}
mean = sum / weightSum;
}
return mean;
}
private static double GetVariance(double[] observations, int[] weights, double mean, int imin, int imax)
{
double variance;
if (weights == null)
{
double sum = 0;
for (int i = imin; i <= imax; i++)
sum += (observations[i] - mean) * (observations[i] - mean);
variance = sum / (imax - imin - 1);
}
else
{
double sum = 0.0;
double squareSum = 0.0;
double weightSum = 0.0;
for (int i = 0; i < observations.Length; i++)
{
double z = observations[i] - mean;
double w = weights[i];
sum += w * (z * z);
weightSum += w;
squareSum += w * w;
}
variance = sum / (weightSum - 1);
}
return variance;
}
#region ISamplableDistribution<double> Members
/// <summary>
/// Generates a random vector of observations from the current distribution.
/// </summary>
///
/// <param name="samples">The number of samples to generate.</param>
///
/// <returns>A random vector of observations drawn from this distribution.</returns>
///
public override double[] Generate(int samples)
{
return Random(min, max, alpha, beta, samples);
}
/// <summary>
/// Generates a random observation from the current distribution.
/// </summary>
///
/// <returns>A random observations drawn from this distribution.</returns>
///
public override double Generate()
{
return Random(min, max, alpha, beta);
}
/// <summary>
/// Generates a random vector of observations from the
/// Beta distribution with the given parameters.
/// </summary>
///
/// <param name="alpha">The shape parameter α (alpha).</param>
/// <param name="beta">The shape parameter β (beta).</param>
/// <param name="min">The minimum possible value a.</param>
/// <param name="max">The maximum possible value b.</param>
/// <param name="samples">The number of samples to generate.</param>
///
/// <returns>An array of double values sampled from the specified Beta distribution.</returns>
///
public static double[] Random(double alpha, double beta, double min, double max, int samples)
{
double[] r = BetaDistribution.Random(alpha, beta, samples);
if (min != 0 || max != 1)
{
for (int i = 0; i < r.Length; i++)
r[i] = r[i] * (max - min) + min;
}
return r;
}
/// <summary>
/// Generates a random observation from a
/// Beta distribution with the given parameters.
/// </summary>
///
/// <param name="alpha">The shape parameter α (alpha).</param>
/// <param name="beta">The shape parameter β (beta).</param>
/// <param name="min">The minimum possible value a.</param>
/// <param name="max">The maximum possible value b.</param>
///
/// <returns>A random double value sampled from the specified Beta distribution.</returns>
///
public static double Random(double alpha, double beta, double min, double max)
{
double r = BetaDistribution.Random(alpha, beta);
return r * (max - min) + min;
}
#endregion
/// <summary>
/// Estimates a new Beta distribution from a set of observations.
/// </summary>
///
public static GeneralizedBetaDistribution Estimate(double[] samples, int min, int max)
{
var beta = new GeneralizedBetaDistribution(1, 1, min, max);
beta.Fit(samples);
return beta;
}
/// <summary>
/// Estimates a new Beta distribution from a set of weighted observations.
/// </summary>
///
public static GeneralizedBetaDistribution Estimate(double[] samples, int min, int max, double[] weights)
{
var beta = new GeneralizedBetaDistribution(1, 1, min, max);
beta.Fit(samples, weights, null);
return beta;
}
/// <summary>
/// Estimates a new Beta distribution from a set of weighted observations.
/// </summary>
///
public static GeneralizedBetaDistribution Estimate(double[] samples, int min, int max, double[] weights, GeneralizedBetaOptions options)
{
var beta = new GeneralizedBetaDistribution(1, 1, min, max);
beta.Fit(samples, weights, options);
return beta;
}
/// <summary>
/// Estimates a new Beta distribution from a set of observations.
/// </summary>
///
public static GeneralizedBetaDistribution Estimate(double[] samples, int min, int max, GeneralizedBetaOptions options)
{
var beta = new GeneralizedBetaDistribution(1, 1, min, max);
beta.Fit(samples, (double[])null, options);
return beta;
}
}
}
| NikolasMarkou/Accord-Framework | Sources/Accord.Statistics/Distributions/Univariate/Continuous/GeneralizedBetaDistribution.cs | C# | lgpl-2.1 | 42,003 |
package beast.app.beastapp;
import beagle.BeagleFlag;
import beagle.BeagleInfo;
import beast.app.BEASTVersion;
import beast.app.BeastMCMC;
import beast.app.util.Arguments;
import beast.app.util.ErrorLogHandler;
import beast.app.util.MessageLogHandler;
import beast.app.util.Utils;
import beast.app.util.Version;
import beast.util.Randomizer;
import beast.util.XMLParserException;
import jam.util.IconUtils;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.*;
import java.util.List;
import java.util.logging.*;
public class BeastMain {
private final static Version version = new BEASTVersion();
static class BeastConsoleApp extends jam.console.ConsoleApplication {
public BeastConsoleApp(final String nameString, final String aboutString, final javax.swing.Icon icon) throws IOException {
super(nameString, aboutString, icon, false);
getDefaultFrame().setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
}
public void doStop() {
// thread.stop is deprecated so need to send a message to running threads...
// Iterator iter = parser.getThreads();
// while (iter.hasNext()) {
// Thread thread = (Thread) iter.next();
// thread.stop(); // http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
// }
}
public void setTitle(final String title) {
getDefaultFrame().setTitle(title);
}
BeastMCMC beastMCMC;
}
public BeastMain(final BeastMCMC beastMCMC, final BeastConsoleApp consoleApp, final int maxErrorCount) {
final Logger infoLogger = Logger.getLogger("beast.app");
try {
if (consoleApp != null) {
consoleApp.beastMCMC = beastMCMC;
}
// Add a handler to handle warnings and errors. This is a ConsoleHandler
// so the messages will go to StdOut..
final Logger logger = Logger.getLogger("beast");
Handler handler = new MessageLogHandler();
handler.setFilter(new Filter() {
public boolean isLoggable(final LogRecord record) {
return record.getLevel().intValue() < Level.WARNING.intValue();
}
});
logger.addHandler(handler);
// // Add a handler to handle warnings and errors. This is a ConsoleHandler
// // so the messages will go to StdErr..
// handler = new ConsoleHandler();
// handler.setFilter(new Filter() {
// public boolean isLoggable(LogRecord record) {
// if (verbose) {
// return record.getLevel().intValue() >= Level.WARNING.intValue();
// } else {
// return record.getLevel().intValue() >= Level.SEVERE.intValue();
// }
// }
// });
// logger.addHandler(handler);
logger.setUseParentHandlers(false);
// infoLogger.info("Parsing XML file: " + fileName);
// infoLogger.info(" File encoding: " + fileReader.getEncoding());
// This is a special logger that is for logging numerical and statistical errors
// during the MCMC run. It will tolerate up to maxErrorCount before throwing a
// RuntimeException to shut down the run.
//Logger errorLogger = Logger.getLogger("error");
handler = new ErrorLogHandler(maxErrorCount);
handler.setLevel(Level.WARNING);
logger.addHandler(handler);
beastMCMC.run();
} catch (java.io.IOException ioe) {
infoLogger.severe("File error: " + ioe.getMessage());
/* Catch exceptions and report useful information
} catch (org.xml.sax.SAXParseException spe) {
if (spe.getMessage() != null && spe.getMessage().equals("Content is not allowed in prolog")) {
infoLogger.severe("Parsing error - the input file, " + fileName + ", is not a valid XML file.");
} else {
infoLogger.severe("Error running file: " + fileName);
infoLogger.severe("Parsing error - poorly formed XML (possibly not an XML file):\n" +
spe.getMessage());
}
} catch (org.w3c.dom.DOMException dome) {
infoLogger.severe("Error running file: " + fileName);
infoLogger.severe("Parsing error - poorly formed XML:\n" +
dome.getMessage());
} catch (dr.xml.XMLParseException pxe) {
if (pxe.getMessage() != null && pxe.getMessage().equals("Unknown root document element, beauti")) {
infoLogger.severe("Error running file: " + fileName);
infoLogger.severe(
"The file you just tried to run in BEAST is actually a BEAUti document.\n" +
"Although this uses XML, it is not a format that BEAST understands.\n" +
"These files are used by BEAUti to save and load your settings so that\n" +
"you can go back and alter them. To generate a BEAST file you must\n" +
"select the 'Generate BEAST File' option, either from the File menu or\n" +
"the button at the bottom right of the window.");
} else {
infoLogger.severe("Parsing error - poorly formed BEAST file, " + fileName + ":\n" +
pxe.getMessage());
}
} catch (RuntimeException rex) {
if (rex.getMessage() != null && rex.getMessage().startsWith("The initial posterior is zero")) {
infoLogger.warning("Error running file: " + fileName);
infoLogger.severe(
"The initial model is invalid because state has a zero probability.\n\n" +
"If the log likelihood of the tree is -Inf, his may be because the\n" +
"initial, random tree is so large that it has an extremely bad\n" +
"likelihood which is being rounded to zero.\n\n" +
"Alternatively, it may be that the product of starting mutation rate\n" +
"and tree height is extremely small or extremely large. \n\n" +
"Finally, it may be that the initial state is incompatible with\n" +
"one or more 'hard' constraints (on monophyly or bounds on parameter\n" +
"values. This will result in Priors with zero probability.\n\n" +
"The individual components of the posterior are as follows:\n" +
rex.getMessage() + "\n" +
"For more information go to <http://beast.bio.ed.ac.uk/>.");
} else {
// This call never returns as another RuntimeException exception is raised by
// the error log handler???
infoLogger.warning("Error running file: " + fileName);
System.err.println("Fatal exception: " + rex.getMessage());
rex.printStackTrace(System.err);
}
*/
} catch (XMLParserException e) {
System.out.println(e.getMessage());
//e.printStackTrace();
} catch (Exception e) {
e.printStackTrace(System.err);
}
// infoLogger.warning("Error running file: " + fileName);
// infoLogger.severe("Fatal exception: " + ex.getMessage());
// System.err.println("Fatal exception: " + ex.getMessage());
// ex.printStackTrace(System.err);
// }
}
static String getFileNameByDialog(final String title) {
final JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));
fc.addChoosableFileFilter(new FileFilter() {
public boolean accept(final File f) {
if (f.isDirectory()) {
return true;
}
final String name = f.getName().toLowerCase();
if (name.endsWith(".xml")) {
return true;
}
return false;
}
// The description of this filter
public String getDescription() {
return "xml files";
}
});
fc.setDialogTitle(title);
final int rval = fc.showOpenDialog(null);
if (rval == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile().toString();
}
return null;
} // getFileNameByDialog
public static void centreLine(final String line, final int pageWidth) {
final int n = pageWidth - line.length();
final int n1 = n / 2;
for (int i = 0; i < n1; i++) {
System.out.print(" ");
}
System.out.println(line);
}
public static void printTitle() {
System.out.println();
centreLine("BEAST " + version.getVersionString() + ", " + version.getDateString(), 60);
centreLine("Bayesian Evolutionary Analysis Sampling Trees", 60);
for (final String creditLine : version.getCredits()) {
centreLine(creditLine, 60);
}
System.out.println();
}
public static void printUsage(final Arguments arguments) {
arguments.printUsage("beast", "[<input-file-name>]");
System.out.println();
System.out.println(" Example: beast test.xml");
System.out.println(" Example: beast -window test.xml");
System.out.println(" Example: beast -help");
System.out.println();
}
//Main method
public static void main(final String[] args) throws java.io.IOException {
final List<String> MCMCargs = new ArrayList<String>();
// Utils.loadUIManager();
final Arguments arguments = new Arguments(
new Arguments.Option[]{
// new Arguments.Option("verbose", "Give verbose XML parsing messages"),
// new Arguments.Option("warnings", "Show warning messages about BEAST XML file"),
// new Arguments.Option("strict", "Fail on non-conforming BEAST XML file"),
new Arguments.Option("window", "Provide a console window"),
new Arguments.Option("options", "Display an options dialog"),
new Arguments.Option("working", "Change working directory to input file's directory"),
new Arguments.LongOption("seed", "Specify a random number generator seed"),
new Arguments.StringOption("prefix", "PREFIX", "Specify a prefix for all output log filenames"),
new Arguments.StringOption("statefile", "STATEFILE", "Specify the filename for storing/restoring the state"),
new Arguments.Option("overwrite", "Allow overwriting of log files"),
new Arguments.Option("resume", "Allow appending of log files"),
// RRB: not sure what effect this option has
new Arguments.IntegerOption("errors", "Specify maximum number of numerical errors before stopping"),
new Arguments.IntegerOption("threads", "The number of computational threads to use (default auto)"),
new Arguments.Option("java", "Use Java only, no native implementations"),
new Arguments.Option("noerr", "Suppress all output to standard error"),
new Arguments.Option("beagle", "Use beagle library if available"),
new Arguments.Option("beagle_info", "BEAGLE: show information on available resources"),
new Arguments.StringOption("beagle_order", "order", "BEAGLE: set order of resource use"),
new Arguments.IntegerOption("beagle_instances", "BEAGLE: divide site patterns amongst instances"),
new Arguments.Option("beagle_CPU", "BEAGLE: use CPU instance"),
new Arguments.Option("beagle_GPU", "BEAGLE: use GPU instance if available"),
new Arguments.Option("beagle_SSE", "BEAGLE: use SSE extensions if available"),
new Arguments.Option("beagle_single", "BEAGLE: use single precision if available"),
new Arguments.Option("beagle_double", "BEAGLE: use double precision if available"),
new Arguments.StringOption("beagle_scaling", new String[]{"default", "none", "dynamic", "always"},
false, "BEAGLE: specify scaling scheme to use"),
new Arguments.Option("help", "Print this information and stop"),
});
try {
arguments.parseArguments(args);
} catch (Arguments.ArgumentException ae) {
System.out.println();
System.out.println(ae.getMessage());
System.out.println();
printUsage(arguments);
System.exit(1);
}
if (arguments.hasOption("help")) {
printUsage(arguments);
System.exit(0);
}
// final boolean verbose = arguments.hasOption("verbose");
// final boolean parserWarning = arguments.hasOption("warnings"); // if dev, then auto turn on, otherwise default to turn off
// final boolean strictXML = arguments.hasOption("strict");
final boolean window = arguments.hasOption("window");
final boolean options = arguments.hasOption("options");
final boolean working = arguments.hasOption("working");
String fileNamePrefix = null;
String stateFileName = null;
//boolean allowOverwrite = arguments.hasOption("overwrite");
long seed = Randomizer.getSeed();
boolean useJava = false;
int threadCount = 0;
if (arguments.hasOption("java")) {
useJava = true;
}
if (arguments.hasOption("prefix")) {
fileNamePrefix = arguments.getStringOption("prefix");
}
if (arguments.hasOption("statefile")) {
stateFileName = arguments.getStringOption("statefile");
}
long beagleFlags = 0;
boolean useBeagle = arguments.hasOption("beagle") ||
arguments.hasOption("beagle_CPU") ||
arguments.hasOption("beagle_GPU") ||
arguments.hasOption("beagle_SSE") ||
arguments.hasOption("beagle_double") ||
arguments.hasOption("beagle_single") ||
arguments.hasOption("beagle_order") ||
arguments.hasOption("beagle_instances");
if (arguments.hasOption("beagle_scaling")) {
System.setProperty("beagle.scaling", arguments.getStringOption("beagle_scaling"));
}
boolean beagleShowInfo = arguments.hasOption("beagle_info");
if (arguments.hasOption("beagle_CPU")) {
beagleFlags |= BeagleFlag.PROCESSOR_CPU.getMask();
}
if (arguments.hasOption("beagle_GPU")) {
beagleFlags |= BeagleFlag.PROCESSOR_GPU.getMask();
}
if (arguments.hasOption("beagle_SSE")) {
beagleFlags |= BeagleFlag.PROCESSOR_CPU.getMask();
beagleFlags |= BeagleFlag.VECTOR_SSE.getMask();
}
if (arguments.hasOption("beagle_double")) {
beagleFlags |= BeagleFlag.PRECISION_DOUBLE.getMask();
}
if (arguments.hasOption("beagle_single")) {
beagleFlags |= BeagleFlag.PRECISION_SINGLE.getMask();
}
if (arguments.hasOption("noerr")) {
System.setErr(new PrintStream(new OutputStream() {
public void write(int b) {
}
}));
}
if (arguments.hasOption("beagle_order")) {
System.setProperty("beagle.resource.order", arguments.getStringOption("beagle_order"));
}
if (arguments.hasOption("beagle_instances")) {
System.setProperty("beagle.instance.count", Integer.toString(arguments.getIntegerOption("beagle_instances")));
}
if (arguments.hasOption("beagle_scaling")) {
System.setProperty("beagle.scaling", arguments.getStringOption("beagle_scaling"));
}
if (arguments.hasOption("threads")) {
threadCount = arguments.getIntegerOption("threads");
if (threadCount < 0) {
printTitle();
System.err.println("The the number of threads should be >= 0");
System.exit(1);
}
}
if (arguments.hasOption("seed")) {
seed = arguments.getLongOption("seed");
if (seed <= 0) {
printTitle();
System.err.println("The random number seed should be > 0");
System.exit(1);
}
}
int maxErrorCount = 0;
if (arguments.hasOption("errors")) {
maxErrorCount = arguments.getIntegerOption("errors");
if (maxErrorCount < 0) {
maxErrorCount = 0;
}
}
BeastConsoleApp consoleApp = null;
final String nameString = "BEAST " + version.getVersionString();
if (window) {
Utils.loadUIManager();
System.setProperty("com.apple.macos.useScreenMenuBar", "true");
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("apple.awt.showGrowBox", "true");
System.setProperty("beast.useWindow", "true");
final javax.swing.Icon icon = IconUtils.getIcon(BeastMain.class, "images/beast.png");
final String aboutString = "<html><div style=\"font-family:sans-serif;\"><center>" +
"<div style=\"font-size:12;\"><p>Bayesian Evolutionary Analysis Sampling Trees<br>" +
"Version " + version.getVersionString() + ", " + version.getDateString() + "</p>" +
version.getHTMLCredits() +
"</div></center></div></html>";
consoleApp = new BeastConsoleApp(nameString, aboutString, icon);
}
printTitle();
File inputFile = null;
if (options) {
final String titleString = "<html><center><p>Bayesian Evolutionary Analysis Sampling Trees<br>" +
"Version " + version.getVersionString() + ", " + version.getDateString() + "</p></center></html>";
final javax.swing.Icon icon = IconUtils.getIcon(BeastMain.class, "images/beast.png");
final BeastDialog dialog = new BeastDialog(new JFrame(), titleString, icon);
if (!dialog.showDialog(nameString, seed)) {
System.exit(0);
}
// if (dialog.allowOverwrite()) {
// allowOverwrite = true;
// }
switch (dialog.getLogginMode()) {
case 0:/* do not ovewrite */
break;
case 1:
MCMCargs.add("-overwrite");
break;
case 2:
MCMCargs.add("-resume");
break;
}
seed = dialog.getSeed();
threadCount = dialog.getThreadPoolSize();
useBeagle = dialog.useBeagle();
if (useBeagle) {
beagleShowInfo = dialog.showBeagleInfo();
if (dialog.preferBeagleCPU()) {
beagleFlags |= BeagleFlag.PROCESSOR_CPU.getMask();
}
if (dialog.preferBeagleSSE()) {
beagleFlags |= BeagleFlag.VECTOR_SSE.getMask();
}
if (dialog.preferBeagleGPU()) {
beagleFlags |= BeagleFlag.PROCESSOR_GPU.getMask();
}
if (dialog.preferBeagleDouble()) {
beagleFlags |= BeagleFlag.PRECISION_DOUBLE.getMask();
}
if (dialog.preferBeagleSingle()) {
beagleFlags |= BeagleFlag.PRECISION_SINGLE.getMask();
}
}
inputFile = dialog.getInputFile();
if (!beagleShowInfo && inputFile == null) {
System.err.println("No input file specified");
return;
}
} else {
if (arguments.hasOption("overwrite")) {
MCMCargs.add("-overwrite");
}
if (arguments.hasOption("resume")) {
MCMCargs.add("-resume");
}
}
if (beagleShowInfo) {
BeagleInfo.printResourceList();
return;
}
if (inputFile == null) {
final String[] args2 = arguments.getLeftoverArguments();
if (args2.length > 1) {
System.err.println("Unknown option: " + args2[1]);
System.err.println();
printUsage(arguments);
return;
}
String inputFileName = null;
if (args2.length > 0) {
inputFileName = args2[0];
inputFile = new File(inputFileName);
}
if (inputFileName == null) {
// No input file name was given so throw up a dialog box...
String fileName = getFileNameByDialog("BEAST " + version.getVersionString() + " - Select XML input file");
if (fileName == null) {
System.exit(0);
}
inputFile = new File(fileName);
}
}
if (inputFile != null && inputFile.getParent() != null && working) {
System.setProperty("file.name.prefix", inputFile.getParentFile().getAbsolutePath());
}
if (window) {
if (inputFile == null) {
consoleApp.setTitle("null");
} else {
consoleApp.setTitle(inputFile.getName());
}
}
if (useJava) {
System.setProperty("java.only", "true");
}
if (fileNamePrefix != null && fileNamePrefix.trim().length() > 0) {
System.setProperty("file.name.prefix", fileNamePrefix.trim());
}
if (stateFileName!= null && stateFileName.trim().length() > 0) {
System.setProperty("state.file.name", stateFileName.trim());
System.out.println("Writing state to file " + stateFileName);
}
// if (allowOverwrite) {
// System.setProperty("log.allow.overwrite", "true");
// }
if (beagleFlags != 0) {
System.setProperty("beagle.preferred.flags", Long.toString(beagleFlags));
}
if (threadCount > 0) {
System.setProperty("thread.count", String.valueOf(threadCount));
MCMCargs.add("-threads");
MCMCargs.add(threadCount + "");
}
MCMCargs.add("-seed");
MCMCargs.add(seed + "");
Randomizer.setSeed(seed);
System.out.println();
System.out.println("Random number seed: " + seed);
System.out.println();
// Construct the beast object
final BeastMCMC beastMCMC = new BeastMCMC();
try {
// set all the settings...
MCMCargs.add(inputFile.getAbsolutePath());
beastMCMC.parseArgs(MCMCargs.toArray(new String[0]));
new BeastMain(beastMCMC, consoleApp, maxErrorCount);
} catch (RuntimeException rte) {
if (window) {
// This sleep for 2 seconds is to ensure that the final message
// appears at the end of the console.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println();
System.out.println("BEAST has terminated with an error. Please select QUIT from the menu.");
}
// logger.severe will throw a RTE but we want to keep the console visible
} catch (XMLParserException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
if (!window) {
System.exit(0);
}
}
}
| learking/beast2-2.1.3 | src/beast/app/beastapp/BeastMain.java | Java | lgpl-2.1 | 24,787 |
package org.pentaho.reporting.platform.plugin.output;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
public interface ReportOutputHandlerFactory {
Set<Map.Entry<String, String>> getSupportedOutputTypes();
ReportOutputHandler createOutputHandlerForOutputType( final ReportOutputHandlerSelector selector ) throws IOException;
String getMimeType( final ReportOutputHandlerSelector selector );
}
| mbatchelor/pentaho-platform-plugin-reporting | core/src/main/java/org/pentaho/reporting/platform/plugin/output/ReportOutputHandlerFactory.java | Java | lgpl-2.1 | 427 |
/* Copyright (C) LinBox
*
* Copyright (C) 2007 b d saunders
*
*
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
/*! @file tests/test-block-ring.C
* @ingroup tests
* @brief no doc
* @test NO DOC
*/
#include "linbox/linbox-config.h"
#include <iostream>
#include <fstream>
#include "linbox/ring/modular.h"
#include "linbox/field/block-ring.h"
#include "test-common.h"
#include "test-field.h"
using namespace LinBox;
int main (int argc, char **argv)
{
static size_t n = 10;
static integer q = 10733;
static int iterations = 2;
static Argument args[] = {
{ 'n', "-n N", "Set dimension of blocks to N.", TYPE_INT, &n },
{ 'q', "-q Q", "Operate over the \"field\" GF(Q) [1].", TYPE_INTEGER, &q },
{ 'i', "-i I", "Perform each test for I iterations.", TYPE_INT, &iterations },
END_OF_ARGUMENTS
};
parseArguments (argc, argv, args);
commentator().start("block-ring test suite", "block-ring");
bool pass = true;
typedef Givaro::Modular<int> Field1;
typedef Givaro::Modular<double> Field2;
Field1 F1(q, 1);
BlockRing<Field1> R1(F1, n);
Field2 F2(q, 1);
BlockRing<Field2> R2(F2, n);
// Make sure some more detailed messages get printed
//commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (3);
commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (4);
commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDetailLevel (Commentator::LEVEL_UNIMPORTANT);
if (!runBasicRingTests(R1, "BlockRing of Givaro::Modular<int>", (unsigned int)iterations)) pass = false;
if (!runBasicRingTests(R2, "BlockRing of Givaro::Modular<double>", (unsigned int)iterations)) pass = false;
commentator().stop("block-ring test suite");
return pass ? 0 : -1;
}
// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
| linbox-team/linbox | tests/test-block-ring.C | C++ | lgpl-2.1 | 2,689 |
<?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
function prefs_sitead_list()
{
return array(
'sitead_publish' => array(
'name' => tra('Publish'),
'type' => 'flag',
'dependencies' => array(
'feature_sitead',
),
'default' => 'n',
),
);
}
| oregional/tiki | lib/prefs/sitead.php | PHP | lgpl-2.1 | 482 |
/*******************************************************************************
* Copyright (c) 2000, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.gef.tools;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartListener;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.SharedCursors;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.requests.CreateConnectionRequest;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.gef.requests.CreationFactory;
/**
* The base implementation for tools which create a connection. A connection is
* a link between two existing GraphicalEditParts.
* <P>
* A connection creation tool uses a {@link CreateConnectionRequest} to perform
* the creation. This request is sent to both graphical editparts which serve as
* the "nodes" at each end of the connection. The first node clicked on is the
* source. The source is asked for a <code>Command</code> that represents
* creating the first half of the connection. This command is then passed to the
* target editpart, which is reponsible for creating the final Command that is
* executed.
*
* @author hudsonr
*/
public class AbstractConnectionCreationTool extends TargetingTool {
/**
* The state which indicates that the connection creation has begun. This
* means that the source of the connection has been identified, and the user
* is still to determine the target.
*/
protected static final int STATE_CONNECTION_STARTED = TargetingTool.MAX_STATE << 1;
/**
* The max state.
*/
protected static final int MAX_STATE = STATE_CONNECTION_STARTED;
private static final int FLAG_SOURCE_FEEDBACK = TargetingTool.MAX_FLAG << 1;
/**
* The max flag.
*/
protected static final int MAX_FLAG = FLAG_SOURCE_FEEDBACK;
private EditPart connectionSource;
private CreationFactory factory;
private EditPartViewer viewer;
private EditPartListener.Stub deactivationListener = new EditPartListener.Stub() {
public void partDeactivated(EditPart editpart) {
handleSourceDeactivated();
}
};
/**
* The default constructor
*/
public AbstractConnectionCreationTool() {
setDefaultCursor(SharedCursors.CURSOR_PLUG);
setDisabledCursor(SharedCursors.CURSOR_PLUG_NOT);
}
/**
* Constructs a new abstract creation tool with the given creation factory.
*
* @param factory
* the creation factory
*/
public AbstractConnectionCreationTool(CreationFactory factory) {
this();
setFactory(factory);
}
/**
* @see org.eclipse.gef.tools.AbstractTool#calculateCursor()
*/
protected Cursor calculateCursor() {
if (isInState(STATE_INITIAL)) {
if (getCurrentCommand() != null)
return getDefaultCursor();
}
return super.calculateCursor();
}
/**
* @see org.eclipse.gef.tools.TargetingTool#createTargetRequest()
*/
protected Request createTargetRequest() {
CreateRequest req = new CreateConnectionRequest();
req.setFactory(getFactory());
return req;
}
/**
* Erases feedback and sets fields to <code>null</code>.
*
* @see org.eclipse.gef.Tool#deactivate()
*/
public void deactivate() {
eraseSourceFeedback();
setConnectionSource(null);
super.deactivate();
setState(STATE_TERMINAL);
viewer = null;
}
/**
* Asks the source editpart to erase connection creation feedback.
*/
protected void eraseSourceFeedback() {
if (!isShowingSourceFeedback())
return;
setFlag(FLAG_SOURCE_FEEDBACK, false);
if (connectionSource != null) {
connectionSource.eraseSourceFeedback(getSourceRequest());
}
}
/**
* @see org.eclipse.gef.tools.AbstractTool#getCommandName()
*/
protected String getCommandName() {
if (isInState(STATE_CONNECTION_STARTED
| STATE_ACCESSIBLE_DRAG_IN_PROGRESS))
return REQ_CONNECTION_END;
else
return REQ_CONNECTION_START;
}
/**
* @see org.eclipse.gef.tools.AbstractTool#getDebugName()
*/
protected String getDebugName() {
return "Connection Creation Tool";//$NON-NLS-1$
}
/**
* @see org.eclipse.gef.tools.AbstractTool#getDebugNameForState(int)
*/
protected String getDebugNameForState(int s) {
if (s == STATE_CONNECTION_STARTED
|| s == STATE_ACCESSIBLE_DRAG_IN_PROGRESS)
return "Connection Started";//$NON-NLS-1$
return super.getDebugNameForState(s);
}
/**
* Returns the creation factory that will be used with the create connection
* request.
*
* @return the creation factory
*/
protected CreationFactory getFactory() {
return factory;
}
/**
* Returns the request sent to the source node. The source node receives the
* same request that is used with the target node. The only difference is
* that at that time the request will be typed as
* {@link RequestConstants#REQ_CONNECTION_START}.
*
* @return the request used with the source node editpart
*/
protected Request getSourceRequest() {
return getTargetRequest();
}
/**
* When the button is first pressed, the source node and its command
* contribution are determined and locked in. After that time, the tool will
* be looking for the target node to complete the connection
*
* @see org.eclipse.gef.tools.AbstractTool#handleButtonDown(int)
* @param button
* which button is pressed
* @return <code>true</code> if the button down was processed
*/
protected boolean handleButtonDown(int button) {
if (isInState(STATE_INITIAL) && button == 1) {
updateTargetRequest();
updateTargetUnderMouse();
setConnectionSource(getTargetEditPart());
Command command = getCommand();
((CreateConnectionRequest) getTargetRequest())
.setSourceEditPart(getTargetEditPart());
if (command != null) {
setState(STATE_CONNECTION_STARTED);
setCurrentCommand(command);
viewer = getCurrentViewer();
}
}
if (isInState(STATE_INITIAL) && button != 1) {
setState(STATE_INVALID);
handleInvalidInput();
}
return true;
}
/**
* Unloads or resets the tool if the state is in the terminal or invalid
* state.
*
* @see org.eclipse.gef.tools.AbstractTool#handleButtonUp(int)
*/
protected boolean handleButtonUp(int button) {
if (isInState(STATE_TERMINAL | STATE_INVALID))
handleFinished();
return true;
}
/**
* @see org.eclipse.gef.tools.AbstractTool#handleCommandStackChanged()
*/
protected boolean handleCommandStackChanged() {
if (!isInState(STATE_INITIAL)) {
if (getCurrentInput().isMouseButtonDown(1))
setState(STATE_INVALID);
else
setState(STATE_INITIAL);
handleInvalidInput();
return true;
}
return false;
}
/**
* Method that is called when the gesture to create the connection has been
* received. Subclasses may extend or override this method to do additional
* creation setup, such as prompting the user to choose an option about the
* connection being created. Returns <code>true</code> to indicate that the
* connection creation succeeded.
*
* @return <code>true</code> if the connection creation was performed
*/
protected boolean handleCreateConnection() {
eraseSourceFeedback();
Command endCommand = getCommand();
setCurrentCommand(endCommand);
executeCurrentCommand();
return true;
}
/**
* @see org.eclipse.gef.tools.AbstractTool#handleDrag()
*/
protected boolean handleDrag() {
if (isInState(STATE_CONNECTION_STARTED))
return handleMove();
return false;
}
/**
* @see org.eclipse.gef.tools.AbstractTool#handleDragInProgress()
*/
protected boolean handleDragInProgress() {
if (isInState(STATE_ACCESSIBLE_DRAG_IN_PROGRESS))
return handleMove();
return false;
}
/**
* @see org.eclipse.gef.tools.AbstractTool#handleFocusLost()
*/
protected boolean handleFocusLost() {
if (isInState(STATE_CONNECTION_STARTED)) {
eraseSourceFeedback();
eraseTargetFeedback();
setState(STATE_INVALID);
handleFinished();
}
return super.handleFocusLost();
}
/**
* @see org.eclipse.gef.tools.TargetingTool#handleHover()
*/
protected boolean handleHover() {
if (isInState(STATE_CONNECTION_STARTED))
updateAutoexposeHelper();
return true;
}
/**
* @see org.eclipse.gef.tools.TargetingTool#handleInvalidInput()
*/
protected boolean handleInvalidInput() {
eraseSourceFeedback();
setConnectionSource(null);
return super.handleInvalidInput();
}
/**
* @see org.eclipse.gef.tools.AbstractTool#handleMove()
*/
protected boolean handleMove() {
if (isInState(STATE_CONNECTION_STARTED) && viewer != getCurrentViewer())
return false;
if (isInState(STATE_CONNECTION_STARTED | STATE_INITIAL
| STATE_ACCESSIBLE_DRAG_IN_PROGRESS)) {
updateTargetRequest();
updateTargetUnderMouse();
showSourceFeedback();
showTargetFeedback();
setCurrentCommand(getCommand());
}
return true;
}
/**
* Called if the source editpart is deactivated for some reason during the
* creation process. For example, the user performs an Undo while in the
* middle of creating a connection, which undoes a prior command which
* created the source.
*/
protected void handleSourceDeactivated() {
setState(STATE_INVALID);
handleInvalidInput();
handleFinished();
}
/**
* Returns <code>true</code> if feedback is being shown.
*
* @return <code>true</code> if showing source feedback
*/
protected boolean isShowingSourceFeedback() {
return getFlag(FLAG_SOURCE_FEEDBACK);
}
/**
* Sets the source editpart for the creation
*
* @param source
* the source editpart node
*/
protected void setConnectionSource(EditPart source) {
if (connectionSource != null)
connectionSource.removeEditPartListener(deactivationListener);
connectionSource = source;
if (connectionSource != null)
connectionSource.addEditPartListener(deactivationListener);
}
/**
* Sets the creation factory used in the request.
*
* @param factory
* the factory
*/
public void setFactory(CreationFactory factory) {
this.factory = factory;
}
/**
* Sends a show feedback request to the source editpart and sets the
* feedback flag.
*/
protected void showSourceFeedback() {
if (connectionSource != null) {
connectionSource.showSourceFeedback(getSourceRequest());
}
setFlag(FLAG_SOURCE_FEEDBACK, true);
}
/**
* @see org.eclipse.gef.tools.TargetingTool#updateTargetRequest()
*/
protected void updateTargetRequest() {
CreateConnectionRequest request = (CreateConnectionRequest) getTargetRequest();
request.setType(getCommandName());
request.setLocation(getLocation());
}
}
| opensagres/xdocreport.eclipse | rap/org.eclipse.gef/src/org/eclipse/gef/tools/AbstractConnectionCreationTool.java | Java | lgpl-2.1 | 11,375 |
#ifdef PARALLEL
#include <meshing.hpp>
#include "paralleltop.hpp"
namespace netgen
{
void ParallelMeshTopology :: Reset ()
{
*testout << "ParallelMeshTopology::Reset" << endl;
if ( ntasks == 1 ) return;
PrintMessage ( 4, "RESET");
int nvold = nv;
int nedold = ned;
int nfaold = nfa;
ne = mesh.GetNE();
nv = mesh.GetNV();
nseg = mesh.GetNSeg();
nsurfel = mesh.GetNSE();
ned = mesh.GetTopology().GetNEdges();
nfa = mesh.GetTopology().GetNFaces();
loc2distedge.ChangeSize (ned);
for (int i = 0; i < ned; i++)
if (loc2distedge[i].Size() == 0)
loc2distedge.Add (i, -1); // will be the global nr
loc2distface.ChangeSize (nfa);
for (int i = 0; i < nfa; i++)
if (loc2distface[i].Size() == 0)
loc2distface.Add (i, -1); // will be the global nr
if ( !isexchangevert )
{
isexchangevert = new BitArray (nv * ( ntasks+1 ));
isexchangevert->Clear();
}
if ( !isexchangeedge )
{
isexchangeedge = new BitArray (ned*(ntasks+1) );
isexchangeedge->Clear();
}
if ( !isexchangeface )
{
isexchangeface = new BitArray (nfa*(ntasks+1) );
isexchangeface->Clear();
}
if ( !isexchangeel )
{
isexchangeel = new BitArray (ne*(ntasks+1) );
isexchangeel->Clear();
}
// if the number of vertices did not change, return
if ( nvold == nv ) return;
// faces and edges get new numbers -> delete
isexchangeface -> SetSize(nfa*(ntasks+1) );
isexchangeedge -> SetSize(ned*(ntasks+1) );
isexchangeface -> Clear();
isexchangeedge -> Clear();
SetNV(nv);
SetNE(ne);
if ( !isghostedge.Size() )
{
isghostedge.SetSize(ned);
isghostedge.Clear();
}
if ( !isghostface.Size() )
{
isghostface.SetSize(nfa);
isghostface.Clear();
}
}
ParallelMeshTopology :: ~ParallelMeshTopology ()
{
delete isexchangeface;
delete isexchangevert;
delete isexchangeedge;
delete isexchangeel;
}
ParallelMeshTopology :: ParallelMeshTopology ( const netgen::Mesh & amesh )
: mesh(amesh)
{
ned = 0; //mesh.GetTopology().GetNEdges();
nfa = 0; //mesh.GetTopology().GetNFaces();
nv = 0;
ne = 0;
np = 0;
nseg = 0;
nsurfel = 0;
neglob = 0;
nvglob = 0;
nparel = 0;
isexchangeface = 0;
isexchangevert = 0;
isexchangeel = 0;
isexchangeedge = 0;
coarseupdate = 0;
isghostedge.SetSize(0);
isghostface.SetSize(0);
overlap = 0;
}
int ParallelMeshTopology :: Glob2Loc_Vert (int globnum )
{
for (int i = 1; i <= nv; i++)
if ( globnum == loc2distvert[i][0] )
return i;
return -1;
}
int ParallelMeshTopology :: Glob2Loc_VolEl (int globnum )
{
int locnum = -1;
for (int i = 0; i < ne; i++)
{
if ( globnum == loc2distel[i][0] )
{
locnum = i+1;
}
}
return locnum;
}
int ParallelMeshTopology :: Glob2Loc_SurfEl (int globnum )
{
int locnum = -1;
for (int i = 0; i < nsurfel; i++)
{
if ( globnum == loc2distsurfel[i][0] )
{
locnum = i+1;
}
}
return locnum;
}
int ParallelMeshTopology :: Glob2Loc_Segm (int globnum )
{
int locnum = -1;
for (int i = 0; i < nseg; i++)
{
if ( globnum == loc2distsegm[i][0] )
{
locnum = i+1;
}
}
return locnum;
}
void ParallelMeshTopology :: Print() const
{
(*testout) << endl << "TOPOLOGY FOR PARALLEL MESHES" << endl << endl;
for ( int i = 1; i <= nv; i++ )
if ( IsExchangeVert (i) )
{
(*testout) << "exchange point " << i << ": global " << GetLoc2Glob_Vert(i) << endl;
for ( int dest = 0; dest < ntasks; dest ++)
if ( dest != id )
if ( GetDistantPNum( dest, i ) > 0 )
(*testout) << " p" << dest << ": " << GetDistantPNum ( dest, i ) << endl;
}
for ( int i = 1; i <= ned; i++ )
if ( IsExchangeEdge ( i ) )
{
int v1, v2;
mesh . GetTopology().GetEdgeVertices(i, v1, v2);
(*testout) << "exchange edge " << i << ": global vertices " << GetLoc2Glob_Vert(v1) << " "
<< GetLoc2Glob_Vert(v2) << endl;
for ( int dest = 0; dest < ntasks; dest++)
if ( GetDistantEdgeNum ( dest, i ) > 0 )
if ( dest != id )
{
(*testout) << " p" << dest << ": " << GetDistantEdgeNum ( dest, i ) << endl;
}
}
for ( int i = 1; i <= nfa; i++ )
if ( IsExchangeFace(i) )
{
Array<int> facevert;
mesh . GetTopology().GetFaceVertices(i, facevert);
(*testout) << "exchange face " << i << ": global vertices " ;
for ( int fi=0; fi < facevert.Size(); fi++)
(*testout) << GetLoc2Glob_Vert(facevert[fi]) << " ";
(*testout) << endl;
for ( int dest = 0; dest < ntasks; dest++)
if ( dest != id )
{
if ( GetDistantFaceNum ( dest, i ) >= 0 )
(*testout) << " p" << dest << ": " << GetDistantFaceNum ( dest, i ) << endl;
}
}
for ( int i = 1; i < mesh.GetNE(); i++)
{
if ( !IsExchangeElement(i) ) continue;
Array<int> vert;
const Element & el = mesh.VolumeElement(i);
(*testout) << "parallel local element " << i << endl;
(*testout) << "vertices " ;
for ( int j = 0; j < el.GetNV(); j++)
(*testout) << el.PNum(j+1) << " ";
(*testout) << "is ghost " << IsGhostEl(i) << endl;
(*testout) << endl;
}
}
int ParallelMeshTopology :: GetDistantPNum ( int proc, int locpnum ) const
{
if ( proc == 0 )
return loc2distvert[locpnum][0];
for (int i = 1; i < loc2distvert[locpnum].Size(); i += 2)
if ( loc2distvert[locpnum][i] == proc )
return loc2distvert[locpnum][i+1];
return -1;
}
int ParallelMeshTopology :: GetDistantFaceNum ( int proc, int locfacenum ) const
{
if ( proc == 0 )
return loc2distface[locfacenum-1][0];
for ( int i = 1; i < loc2distface[locfacenum-1].Size(); i+=2 )
if ( loc2distface[locfacenum-1][i] == proc )
return loc2distface[locfacenum-1][i+1];
return -1;
}
int ParallelMeshTopology :: GetDistantEdgeNum ( int proc, int locedgenum ) const
{
if ( proc == 0 )
return loc2distedge[locedgenum-1][0];
for ( int i = 1; i < loc2distedge[locedgenum-1].Size(); i+=2 )
if ( loc2distedge[locedgenum-1][i] == proc )
return loc2distedge[locedgenum-1][i+1];
return -1;
}
int ParallelMeshTopology :: GetDistantElNum ( int proc, int locelnum ) const
{
if ( proc == 0 )
return loc2distel[locelnum-1][0];
for ( int i = 1; i < loc2distel[locelnum-1].Size(); i+=2 )
if ( loc2distel[locelnum-1][i] == proc )
return loc2distel[locelnum-1][i+1];
return -1;
}
/*
//
// gibt anzahl an distant pnums zurueck
int ParallelMeshTopology :: GetNDistantPNums ( int locpnum ) const
{
return loc2distvert[locpnum].Size() / 2 + 1;
}
int ParallelMeshTopology :: GetNDistantFaceNums ( int locfacenum ) const
{
int size = loc2distface[locfacenum-1].Size() / 2 + 1;
return size;
}
int ParallelMeshTopology :: GetNDistantEdgeNums ( int locedgenum ) const
{
int size = loc2distedge[locedgenum-1].Size() / 2 + 1;
return size;
}
int ParallelMeshTopology :: GetNDistantElNums ( int locelnum ) const
{
int size = loc2distel[locelnum-1].Size() / 2 + 1;
return size;
}
*/
// gibt anzahl an distant pnums zurueck
// * pnums entspricht Array<int[2] >
int ParallelMeshTopology :: GetDistantPNums ( int locpnum, int * distpnums ) const
{
// distpnums[0] = loc2distvert[locpnum][0];
// for (int i = 1; i < loc2distvert[locpnum].Size(); i += 2)
// distpnums[ loc2distvert[locpnum][i] ] = loc2distvert[locpnum][i+1];
distpnums[0] = 0;
distpnums[1] = loc2distvert[locpnum][0];
for ( int i = 1; i < loc2distvert[locpnum].Size(); i++ )
distpnums[i+1] = loc2distvert[locpnum][i];
int size = loc2distvert[locpnum].Size() / 2 + 1;
return size;
}
int ParallelMeshTopology :: GetDistantFaceNums ( int locfacenum, int * distfacenums ) const
{
// distfacenums[0] = loc2distface[locfacenum-1][0];
// for ( int i = 1; i < loc2distface[locfacenum-1].Size(); i+=2 )
// distfacenums[loc2distface[locfacenum-1][i]] = loc2distface[locfacenum-1][i+1];
distfacenums[0] = 0;
distfacenums[1] = loc2distface[locfacenum-1][0];
for ( int i = 1; i < loc2distface[locfacenum-1].Size(); i++ )
distfacenums[i+1] = loc2distface[locfacenum-1][i];
int size = loc2distface[locfacenum-1].Size() / 2 + 1;
return size;
}
int ParallelMeshTopology :: GetDistantEdgeNums ( int locedgenum, int * distedgenums ) const
{
// distedgenums[0] = loc2distedge[locedgenum-1][0];
// for ( int i = 1; i < loc2distedge[locedgenum-1].Size(); i+=2 )
// distedgenums[loc2distedge[locedgenum-1][i]] = loc2distedge[locedgenum-1][i+1];
distedgenums[0] = 0;
distedgenums[1] = loc2distedge[locedgenum-1][0];
for ( int i = 1; i < loc2distedge[locedgenum-1].Size(); i++ )
distedgenums[i+1] = loc2distedge[locedgenum-1][i];
int size = loc2distedge[locedgenum-1].Size() / 2 + 1;
return size;
}
int ParallelMeshTopology :: GetDistantElNums ( int locelnum, int * distelnums ) const
{
// distelnums[0] = loc2distel[locelnum-1][0];
// for ( int i = 1; i < loc2distel[locelnum-1].Size(); i+=2 )
// distelnums[loc2distel[locelnum-1][i]] = loc2distel[locelnum-1][i+1];
distelnums[0] = 0;
distelnums[1] = loc2distel[locelnum-1][0];
for ( int i = 1; i < loc2distel[locelnum-1].Size(); i++ )
distelnums[i+1] = loc2distel[locelnum-1][i];
int size = loc2distel[locelnum-1].Size() / 2 + 1;
return size;
}
void ParallelMeshTopology :: SetDistantFaceNum ( int dest, int locnum, int distnum )
{
if ( dest == 0 )
{
loc2distface[locnum-1][0] = distnum;
return;
}
for ( int i = 1; i < loc2distface[locnum-1].Size(); i+=2 )
if ( loc2distface[locnum-1][i] == dest )
{
loc2distface[locnum-1][i+1] = distnum;
return;
}
loc2distface.Add(locnum-1, dest);
loc2distface.Add(locnum-1, distnum);
}
void ParallelMeshTopology :: SetDistantPNum ( int dest, int locnum, int distnum )
{
if ( dest == 0 )
{
loc2distvert[locnum][0] = distnum; // HERE
return;
}
for ( int i = 1; i < loc2distvert[locnum].Size(); i+=2 )
if ( loc2distvert[locnum][i] == dest )
{
loc2distvert[locnum][i+1] = distnum;
return;
}
loc2distvert.Add (locnum, dest);
loc2distvert.Add (locnum, distnum);
}
void ParallelMeshTopology :: SetDistantEdgeNum ( int dest, int locnum, int distnum )
{
if ( dest == 0 )
{
loc2distedge[locnum-1][0] = distnum;
return;
}
for ( int i = 1; i < loc2distedge[locnum-1].Size(); i+=2 )
if ( loc2distedge[locnum-1][i] == dest )
{
loc2distedge[locnum-1][i+1] = distnum;
return;
}
loc2distedge.Add (locnum-1, dest);
loc2distedge.Add (locnum-1, distnum);
}
void ParallelMeshTopology :: SetDistantEl ( int dest, int locnum, int distnum )
{
if ( dest == 0 )
{
loc2distel[locnum-1][0] = distnum;
return;
}
for ( int i = 1; i < loc2distel[locnum-1].Size(); i+=2 )
if ( loc2distel[locnum-1][i] == dest )
{
loc2distel[locnum-1][i+1] = distnum;
return;
}
loc2distel.Add (locnum-1, dest);
loc2distel.Add (locnum-1, distnum);
}
void ParallelMeshTopology :: SetDistantSurfEl ( int dest, int locnum, int distnum )
{
if ( dest == 0 )
{
loc2distsurfel[locnum-1][0] = distnum;
return;
}
for ( int i = 1; i < loc2distsurfel[locnum-1].Size(); i+=2 )
if ( loc2distsurfel[locnum-1][i] == dest )
{
loc2distsurfel[locnum-1][i+1] = distnum;
return;
}
loc2distsurfel.Add (locnum-1, dest);
loc2distsurfel.Add (locnum-1, distnum);
}
void ParallelMeshTopology :: SetDistantSegm ( int dest, int locnum, int distnum )
{
if ( dest == 0 )
{
loc2distsegm[locnum-1][0] = distnum;
return;
}
for (int i = 1; i < loc2distsegm[locnum-1].Size(); i+=2 )
if ( loc2distsegm[locnum-1][i] == dest )
{
loc2distsegm[locnum-1][i+1] = distnum;
return;
}
loc2distsegm.Add (locnum-1, dest);
loc2distsegm.Add (locnum-1, distnum);
}
void ParallelMeshTopology :: GetVertNeighbours ( int vnum, Array<int> & dests ) const
{
dests.SetSize(0);
int i = 1;
while ( i < loc2distvert[vnum].Size() )
{
dests.Append ( loc2distvert[vnum][i] );
i+=2;
}
}
void ParallelMeshTopology :: Update ()
{
ne = mesh.GetNE();
nv = mesh.GetNV();
nseg = mesh.GetNSeg();
nsurfel = mesh.GetNSE();
ned = mesh.GetTopology().GetNEdges();
nfa = mesh.GetTopology().GetNFaces();
}
void ParallelMeshTopology :: UpdateRefinement ()
{
;
}
void ParallelMeshTopology :: UpdateCoarseGridGlobal ()
{
PrintMessage ( 1, "UPDATE GLOBAL COARSEGRID STARTS" ); // JS
// MPI_Barrier (MPI_COMM_WORLD);
// PrintMessage ( 1, "all friends are here " ); // JS
// MPI_Barrier (MPI_COMM_WORLD);
int timer = NgProfiler::CreateTimer ("UpdateCoarseGridGlobal");
NgProfiler::RegionTimer reg(timer);
*testout << "ParallelMeshTopology :: UpdateCoarseGridGlobal" << endl;
const MeshTopology & topology = mesh.GetTopology();
Array<int> sendarray, recvarray;
nfa = topology . GetNFaces();
ned = topology . GetNEdges();
np = mesh . GetNP();
nv = mesh . GetNV();
ne = mesh . GetNE();
nseg = mesh.GetNSeg();
nsurfel = mesh.GetNSE();
// low order processor - save mesh partition
if ( id == 0 )
{
if ( !isexchangeel )
{
isexchangeel = new BitArray ( (ntasks+1) * ne );
isexchangeel -> Clear();
}
for ( int eli = 1; eli <= ne; eli++ )
{
loc2distel[eli-1][0] = eli;
SetExchangeElement ( eli );
const Element & el = mesh . VolumeElement ( eli );
int dest = el . GetPartition ( );
SetExchangeElement ( dest, eli );
for ( int i = 0; i < el.GetNP(); i++ )
{
SetExchangeVert ( dest, el.PNum(i+1) );
SetExchangeVert ( el.PNum(i+1) );
}
Array<int> edges;
topology . GetElementEdges ( eli, edges );
for ( int i = 0; i < edges.Size(); i++ )
{
SetExchangeEdge ( dest, edges[i] );
SetExchangeEdge ( edges[i] );
}
topology . GetElementFaces ( eli, edges );
for ( int i = 0; i < edges.Size(); i++ )
{
SetExchangeFace ( dest, edges[i] );
SetExchangeFace ( edges[i] );
}
}
// HERE
for ( int i = 1; i <= mesh .GetNV(); i++)
loc2distvert[i][0] = i;
for ( int i = 0; i < mesh . GetNSeg(); i++)
loc2distsegm[i][0] = i+1;
for ( int i = 0; i < mesh . GetNSE(); i++)
loc2distsurfel[i][0] = i+1;
for ( int i = 0; i < topology .GetNEdges(); i++)
loc2distedge[i][0] = i+1;
for ( int i = 0; i < topology .GetNFaces(); i++)
loc2distface[i][0] = i+1;
}
if ( id == 0 )
sendarray.Append (nfa);
BitArray recvface(nfa);
recvface.Clear();
/*
Array<int> edges, pnums, faces;
for ( int el = 1; el <= ne; el++ )
{
topology.GetElementFaces (el, faces);
int globeli = GetLoc2Glob_VolEl(el);
for ( int fai = 0; fai < faces.Size(); fai++)
{
int fa = faces[fai];
topology.GetElementEdges ( el, edges );
topology.GetFaceVertices ( fa, pnums );
// send :
// localfacenum
// np
// ned
// globalpnums
// localpnums
// localedgenums mit globalv1, globalv2
sendarray. Append ( fa );
sendarray. Append ( globeli );
sendarray. Append ( pnums.Size() );
sendarray. Append ( edges.Size() );
if (id == 0)
for ( int i = 0; i < pnums.Size(); i++ )
sendarray. Append( pnums[i] );
else
for ( int i = 0; i < pnums.Size(); i++ )
sendarray. Append( GetLoc2Glob_Vert(pnums[i]) );
for ( int i = 0; i < pnums.Size(); i++ )
sendarray. Append(pnums[i] );
for ( int i = 0; i < edges.Size(); i++ )
{
sendarray. Append(edges[i] );
int v1, v2;
topology . GetEdgeVertices ( edges[i], v1, v2 );
int dv1 = GetLoc2Glob_Vert ( v1 );
int dv2 = GetLoc2Glob_Vert ( v2 );
if (id > 0) if ( dv1 > dv2 ) swap ( dv1, dv2 );
sendarray . Append ( dv1 );
sendarray . Append ( dv2 );
}
}
}
*/
// new version
Array<int> edges, pnums, faces, elpnums;
sendarray.Append (ne);
for ( int el = 1; el <= ne; el++ )
{
topology.GetElementFaces (el, faces);
topology.GetElementEdges ( el, edges );
const Element & volel = mesh.VolumeElement (el);
int globeli = GetLoc2Glob_VolEl(el);
sendarray. Append ( globeli );
sendarray. Append ( faces.Size() );
sendarray. Append ( edges.Size() );
sendarray. Append ( volel.GetNP() );
for ( int i = 0; i < faces.Size(); i++ )
sendarray. Append(faces[i] );
for ( int i = 0; i < edges.Size(); i++ )
sendarray. Append(edges[i] );
for ( int i = 0; i < volel.GetNP(); i++ )
if (id == 0)
sendarray. Append(volel[i] );
else
sendarray. Append(GetLoc2Glob_Vert (volel[i]));
}
// end new version
BitArray edgeisinit(ned), vertisinit(np);
edgeisinit.Clear();
vertisinit.Clear();
// Array for temporary use, to find local from global element fast
Array<int,1> glob2loc_el;
if ( id != 0 )
{
glob2loc_el.SetSize (neglob);
glob2loc_el = -1;
for ( int locel = 1; locel <= mesh.GetNE(); locel++)
glob2loc_el[GetLoc2Glob_VolEl(locel)] = locel;
}
// MPI_Barrier (MPI_COMM_WORLD);
MPI_Request sendrequest;
if (id == 0)
{
PrintMessage (4, "UpdateCoarseGridGlobal : bcast, size = ", int (sendarray.Size()*sizeof(int)) );
MyMPI_Bcast ( sendarray );
}
else
MyMPI_ISend ( sendarray, 0, sendrequest );
int nloops = (id == 0) ? ntasks-1 : 1;
for (int hi = 0; hi < nloops; hi++)
{
int sender;
if (id == 0)
{
sender = MyMPI_Recv ( recvarray );
PrintMessage (4, "have received from ", sender);
}
else
{
MyMPI_Bcast ( recvarray );
sender = 0;
}
// compare received vertices with own ones
int ii = 0;
int cntel = 0;
int volel = 1;
if ( id != 0 )
nfaglob = recvarray[ii++];
Array<int> faces, edges;
Array<int> pnums, globalpnums;
int recv_ne = recvarray[ii++];
for (int hi = 0; hi < recv_ne; hi++)
{
int globvolel = recvarray[ii++];
int distnfa = recvarray[ii++];
int distned = recvarray[ii++];
int distnp = recvarray[ii++];
if ( id > 0 )
volel = glob2loc_el[globvolel];
else
volel = globvolel;
if (volel != -1)
{
topology.GetElementFaces( volel, faces);
topology.GetElementEdges ( volel, edges);
const Element & volelement = mesh.VolumeElement (volel);
for ( int i = 0; i < faces.Size(); i++)
SetDistantFaceNum ( sender, faces[i], recvarray[ii++]);
for ( int i = 0; i < edges.Size(); i++)
SetDistantEdgeNum ( sender, edges[i], recvarray[ii++]);
for ( int i = 0; i < distnp; i++)
SetDistantPNum ( sender, volelement[i], recvarray[ii++]);
}
else
ii += distnfa + distned + distnp;
}
}
coarseupdate = 1;
if (id != 0)
{
MPI_Status status;
MPI_Wait (&sendrequest, &status);
}
#ifdef SCALASCA
#pragma pomp inst end(updatecoarsegrid)
#endif
}
void ParallelMeshTopology :: UpdateCoarseGrid ()
{
int timer = NgProfiler::CreateTimer ("UpdateCoarseGrid");
NgProfiler::RegionTimer reg(timer);
#ifdef SCALASCA
#pragma pomp inst begin(updatecoarsegrid)
#endif
(*testout) << "UPDATE COARSE GRID PARALLEL TOPOLOGY " << endl;
PrintMessage (1, "UPDATE COARSE GRID PARALLEL TOPOLOGY ");
// find exchange edges - first send exchangeedges locnum, v1, v2
// receive distant distnum, v1, v2
// find matching
const MeshTopology & topology = mesh.GetTopology();
UpdateCoarseGridGlobal();
if ( id == 0 ) return;
Array<int> sendarray, recvarray;
nfa = topology . GetNFaces();
ned = topology . GetNEdges();
np = mesh . GetNP();
nv = mesh . GetNV();
ne = mesh . GetNE();
nseg = mesh.GetNSeg();
nsurfel = mesh.GetNSE();
// exchange vertices
for (int vertex = 1; vertex <= nv; vertex++)
if (IsExchangeVert (vertex) )
{
sendarray.Append (GetLoc2Glob_Vert (vertex));
sendarray.Append (vertex);
}
Array<int,1> glob2loc;
glob2loc.SetSize (nvglob);
glob2loc = -1;
for (int locv = 1; locv <= nv; locv++)
if (IsExchangeVert (locv) )
glob2loc[GetDistantPNum(0, locv)] = locv;
for (int sender = 1; sender < ntasks; sender ++)
{
if (id == sender)
MyMPI_Bcast (sendarray, sender-1, MPI_HIGHORDER_COMM);
else
{
MyMPI_Bcast (recvarray, sender-1, MPI_HIGHORDER_COMM);
for (int ii = 0; ii < recvarray.Size(); )
{
int globv = recvarray[ii++];
int distv = recvarray[ii++];
int locv = glob2loc[globv];
if (locv != -1)
SetDistantPNum (sender, locv, distv);
}
}
}
sendarray.SetSize (0);
recvarray.SetSize (0);
// exchange edges
int maxedge = 0;
for (int edge = 1; edge <= ned; edge++)
if (IsExchangeEdge (edge) )
{
sendarray.Append (GetDistantEdgeNum (0, edge));
sendarray.Append (edge);
maxedge = max (maxedge, GetDistantEdgeNum (0, edge));
}
glob2loc.SetSize (maxedge+1);
glob2loc = -1;
for (int loc = 1; loc <= ned; loc++)
if (IsExchangeEdge (loc) )
glob2loc[GetDistantEdgeNum(0, loc)] = loc;
for (int sender = 1; sender < ntasks; sender ++)
{
if (id == sender)
MyMPI_Bcast (sendarray, sender-1, MPI_HIGHORDER_COMM);
else
{
MyMPI_Bcast (recvarray, sender-1, MPI_HIGHORDER_COMM);
for (int ii = 0; ii < recvarray.Size(); )
{
int globe = recvarray[ii++];
int diste = recvarray[ii++];
if (globe > maxedge) continue;
int loce = glob2loc[globe];
if (loce != -1)
SetDistantEdgeNum (sender, loce, diste);
}
}
}
sendarray.SetSize (0);
recvarray.SetSize (0);
// exchange faces
for (int face = 1; face <= nfa; face++)
if (IsExchangeFace (face) )
{
sendarray.Append (GetDistantFaceNum (0, face));
sendarray.Append (face);
}
glob2loc.SetSize (nfaglob);
glob2loc = -1;
for (int loc = 1; loc <= nfa; loc++)
if (IsExchangeFace (loc) )
glob2loc[GetDistantFaceNum(0, loc)] = loc;
for (int sender = 1; sender < ntasks; sender ++)
{
if (id == sender)
MyMPI_Bcast (sendarray, sender-1, MPI_HIGHORDER_COMM);
else
{
MyMPI_Bcast (recvarray, sender-1, MPI_HIGHORDER_COMM);
for (int ii = 0; ii < recvarray.Size(); )
{
int globf = recvarray[ii++];
int distf = recvarray[ii++];
int locf = glob2loc[globf];
if (locf != -1)
SetDistantFaceNum (sender, locf, distf);
}
}
}
#ifdef OLD
// BitArray recvface(nfa);
// recvface.Clear();
for (int fa = 1; fa <= nfa; fa++ )
{
if ( !IsExchangeFace ( fa ) ) continue;
Array<int> edges, pnums;
int globfa = GetDistantFaceNum (0, fa);
topology.GetFaceEdges (fa, edges);
topology.GetFaceVertices (fa, pnums);
// send :
// localfacenum globalfacenum np ned globalpnums localpnums
// localedgenums mit globalv1, globalv2
sendarray.Append ( fa );
sendarray.Append ( globfa );
sendarray.Append ( pnums.Size() );
sendarray.Append ( edges.Size() );
for (int i = 0; i < pnums.Size(); i++ )
sendarray.Append( GetLoc2Glob_Vert(pnums[i]) );
for ( int i = 0; i < pnums.Size(); i++ )
sendarray.Append(pnums[i]);
for ( int i = 0; i < edges.Size(); i++ )
{
sendarray.Append(edges[i]);
int v1, v2;
topology.GetEdgeVertices ( edges[i], v1, v2 );
int dv1 = GetLoc2Glob_Vert ( v1 );
int dv2 = GetLoc2Glob_Vert ( v2 );
sendarray.Append ( dv1 );
sendarray.Append ( dv2 );
}
}
BitArray edgeisinit(ned), vertisinit(np);
edgeisinit.Clear();
vertisinit.Clear();
// Array for temporary use, to find local from global element fast
// only for not too big meshes
// seems ok, as low-order space is treated on one proc
Array<int,1> glob2locfa (nfaglob);
glob2locfa = -1;
for (int locfa = 1; locfa <= nfa; locfa++)
if (IsExchangeFace (locfa) )
glob2locfa[GetDistantFaceNum(0, locfa)] = locfa;
for (int sender = 1; sender < ntasks; sender ++)
{
if (id == sender)
MyMPI_Bcast (sendarray, sender-1, MPI_HIGHORDER_COMM);
else
{
MyMPI_Bcast ( recvarray, sender-1, MPI_HIGHORDER_COMM);
// compare received vertices with own ones
int ii = 0;
int cntel = 0;
int locfa = 1;
while (ii < recvarray.Size())
{
// receive list :
// distant_facenum global_facenum np ned globalpnums distant_pnums
// distant edgenums mit globalv1, globalv2
int distfa = recvarray[ii++];
int globfa = recvarray[ii++];
int distnp = recvarray[ii++];
int distned =recvarray[ii++];
int locfa = (glob2locfa) [globfa];
if ( locfa == -1 )
{
ii += 2*distnp + 3*distned;
locfa = 1;
continue;
}
Array<int> edges;
int fa = locfa;
Array<int> pnums, globalpnums;
topology.GetFaceEdges ( fa, edges );
topology.GetFaceVertices ( fa, pnums );
globalpnums.SetSize ( distnp );
for ( int i = 0; i < distnp; i++)
globalpnums[i] = GetLoc2Glob_Vert ( pnums[i] );
SetDistantFaceNum ( sender, fa, distfa );
// find exchange points
for ( int i = 0; i < distnp; i++)
{
int distglobalpnum = recvarray[ii+i];
for ( int j = 0; j < distnp; j++ )
if ( globalpnums[j] == distglobalpnum )
{
// set sender -- distpnum ---- locpnum
int distpnum = recvarray[ii + i +distnp];
// SetDistantPNum ( sender, pnums[j], distpnum );
}
}
Array<int> distedgenums(distned);
// find exchange edges
for ( int i = 0; i < edges.Size(); i++)
{
int v1, v2;
topology . GetEdgeVertices ( edges[i], v1, v2 );
int dv1 = GetLoc2Glob_Vert ( v1 );
int dv2 = GetLoc2Glob_Vert ( v2 );
if ( dv1 > dv2 ) swap ( dv1, dv2 );
for ( int ed = 0; ed < distned; ed++)
{
distedgenums[ed] = recvarray[ii + 2*distnp + 3*ed];
int ddv1 = recvarray[ii + 2*distnp + 3*ed + 1];
int ddv2 = recvarray[ii + 2*distnp + 3*ed + 2];
if ( ddv1 > ddv2 ) swap ( ddv1, ddv2 );
if ( dv1 == ddv1 && dv2 == ddv2 )
{
// set sender -- distednum -- locednum
SetDistantEdgeNum ( sender, edges[i], distedgenums[ed] );
}
}
}
ii += 2*distnp + 3*distned;
}
}
}
#endif
// set which elements are where for the master processor
coarseupdate = 1;
#ifdef SCALASCA
#pragma pomp inst end(updatecoarsegrid)
#endif
}
void ParallelMeshTopology :: UpdateCoarseGridOverlap ()
{
UpdateCoarseGridGlobal();
#ifdef SCALASCA
#pragma pomp inst begin(updatecoarsegrid)
#endif
(*testout) << "UPDATE COARSE GRID PARALLEL TOPOLOGY, OVERLAP " << endl;
PrintMessage ( 1, "UPDATE COARSE GRID PARALLEL TOPOLOGY, OVERLAP " );
const MeshTopology & topology = mesh.GetTopology();
nfa = topology . GetNFaces();
ned = topology . GetNEdges();
np = mesh . GetNP();
nv = mesh . GetNV();
ne = mesh . GetNE();
nseg = mesh.GetNSeg();
nsurfel = mesh.GetNSE();
if ( id != 0 )
{
// find exchange edges - first send exchangeedges locnum, v1, v2
// receive distant distnum, v1, v2
// find matching
Array<int> * sendarray, *recvarray;
sendarray = new Array<int> (0);
recvarray = new Array<int>;
sendarray -> SetSize (0);
BitArray recvface(nfa);
recvface.Clear();
for ( int el = 1; el <= ne; el++ )
{
Array<int> edges, pnums, faces;
topology.GetElementFaces (el, faces);
int globeli = GetLoc2Glob_VolEl(el);
for ( int fai = 0; fai < faces.Size(); fai++)
{
int fa = faces[fai];
topology.GetFaceEdges ( fa, edges );
topology.GetFaceVertices ( fa, pnums );
if ( !IsExchangeElement ( el ) ) continue;
int globfa = GetDistantFaceNum(0, fa) ;
// send :
// localfacenum
// globalfacenum
// globalelnum
// np
// ned
// globalpnums
// localpnums
// localedgenums mit globalelnums mit globalv1, globalv2
//
sendarray -> Append ( fa );
sendarray -> Append ( globfa );
sendarray -> Append ( globeli );
sendarray -> Append ( pnums.Size() );
sendarray -> Append ( edges.Size() );
for ( int i = 0; i < pnums.Size(); i++ )
{
sendarray -> Append( GetLoc2Glob_Vert(pnums[i]) );
}
for ( int i = 0; i < pnums.Size(); i++ )
{
sendarray -> Append(pnums[i] );
}
for ( int i = 0; i < edges.Size(); i++ )
{
int globedge = GetDistantEdgeNum(0, edges[i] );
int v1, v2;
topology . GetEdgeVertices ( edges[i], v1, v2 );
int dv1 = GetLoc2Glob_Vert ( v1 );
int dv2 = GetLoc2Glob_Vert ( v2 );
sendarray -> Append(edges[i] );
sendarray -> Append (globedge);
sendarray -> Append ( dv1 );
sendarray -> Append ( dv2 );
}
}
}
BitArray edgeisinit(ned), vertisinit(np);
edgeisinit.Clear();
vertisinit.Clear();
// Array for temporary use, to find local from global element fast
// only for not too big meshes
// seems ok, as low-order space is treated on one proc
Array<int,1> * glob2loc_el;
glob2loc_el = new Array<int,1> ( neglob );
(*glob2loc_el) = -1;
for ( int locel = 1; locel <= mesh.GetNE(); locel++)
(*glob2loc_el)[GetLoc2Glob_VolEl(locel)] = locel;
for ( int sender = 1; sender < ntasks; sender ++ )
{
if ( id == sender )
MyMPI_Bcast (*sendarray, sender-1, MPI_HIGHORDER_COMM);
// {
// for ( int dest = 1; dest < ntasks; dest ++ )
// if ( dest != id)
// {
// MyMPI_Send (*sendarray, dest);
// }
// }
if ( id != sender )
{
// MyMPI_Recv ( *recvarray, sender);
MyMPI_Bcast (*recvarray, sender-1, MPI_HIGHORDER_COMM);
// compare received vertices with own ones
int ii = 0;
int cntel = 0;
int volel = 1;
while ( ii< recvarray -> Size() )
{
// receive list :
// distant facenum
// np
// ned
// globalpnums
// distant pnums
// distant edgenums mit globalv1, globalv2
int distfa = (*recvarray)[ii++];
int globfa = (*recvarray)[ii++];
int globvolel = (*recvarray)[ii++];
int distnp = (*recvarray)[ii++];
int distned =(*recvarray)[ii++];
if ( id > 0 ) // GetLoc2Glob_VolEl ( volel ) != globvolel )
volel = (*glob2loc_el)[globvolel]; //Glob2Loc_VolEl ( globvolel );
else
volel = globvolel;
if ( volel == -1 )
{
ii += 2*distnp + 4*distned;
volel = 1;
continue;
}
Array<int> faces, edges;
topology.GetElementFaces( volel, faces);
topology.GetElementEdges ( volel, edges);
for ( int fai= 0; fai < faces.Size(); fai++ )
{
int fa = faces[fai];
if ( !IsExchangeFace ( fa ) && sender != 0 ) continue;
// if ( recvface.Test ( fa-1 ) ) continue;
Array<int> pnums, globalpnums;
//topology.GetFaceEdges ( fa, edges );
topology.GetFaceVertices ( fa, pnums );
// find exchange faces ...
// have to be of same type
if ( pnums.Size () != distnp ) continue;
globalpnums.SetSize ( distnp );
for ( int i = 0; i < distnp; i++)
globalpnums[i] = GetLoc2Glob_Vert ( pnums[i] );
// test if 3 vertices match
bool match = 1;
for ( int i = 0; i < distnp; i++)
if ( !globalpnums.Contains ( (*recvarray)[ii+i] ) )
match = 0;
if ( !match ) continue;
// recvface.Set(fa-1);
SetDistantFaceNum ( sender, fa, distfa );
SetDistantFaceNum ( 0, fa, globfa );
// find exchange points
for ( int i = 0; i < distnp; i++)
{
int distglobalpnum = (*recvarray)[ii+i];
for ( int j = 0; j < distnp; j++ )
if ( globalpnums[j] == distglobalpnum )
{
// set sender -- distpnum ---- locpnum
int distpnum = (*recvarray)[ii + i +distnp];
SetDistantPNum ( sender, pnums[j], distpnum );
}
}
int * distedgenums = new int [distned];
// find exchange edges
for ( int i = 0; i < edges.Size(); i++)
{
int v1, v2;
topology . GetEdgeVertices ( edges[i], v1, v2 );
int dv1 = GetLoc2Glob_Vert ( v1 );
int dv2 = GetLoc2Glob_Vert ( v2 );
if ( dv1 > dv2 ) swap ( dv1, dv2 );
for ( int ed = 0; ed < distned; ed++)
{
distedgenums[ed] = (*recvarray)[ii + 2*distnp + 4*ed];
int globedgenum = (*recvarray)[ii + 2*distnp + 4*ed + 1];
int ddv1 = (*recvarray)[ii + 2*distnp + 4*ed + 2];
int ddv2 = (*recvarray)[ii + 2*distnp + 4*ed + 3];
if ( ddv1 > ddv2 ) swap ( ddv1, ddv2 );
if ( dv1 == ddv1 && dv2 == ddv2 )
{
// set sender -- distednum -- locednum
SetDistantEdgeNum ( sender, edges[i], distedgenums[ed] );
SetDistantEdgeNum ( 0, edges[i], globedgenum );
}
}
}
delete [] distedgenums;
}
ii += 2*distnp + 4*distned;
}
}
}
// set which elements are where for the master processor
delete sendarray; delete recvarray;
if ( id > 0 )
delete glob2loc_el;
coarseupdate = 1;
}
// send global-local el/face/edge/vert-info to id 0
// nfa = topology . GetNFaces();
// ned = topology . GetNEdges();
// np = mesh . GetNP();
// nv = mesh . GetNV();
// ne = mesh . GetNE();
// nseg = mesh.GetNSeg();
// nsurfel = mesh.GetNSE();
if ( id != 0 )
{
Array<int> * sendarray;
sendarray = new Array<int> (4);
int sendnfa = 0, sendned = 0;
(*sendarray)[0] = ne;
(*sendarray)[1] = nfa;
(*sendarray)[2] = ned;
(*sendarray)[3] = np;
int ii = 4;
for ( int el = 1; el <= ne; el++ )
(*sendarray).Append ( GetLoc2Glob_VolEl (el ) );
for ( int fa = 1; fa <= nfa; fa++ )
{
if ( !IsExchangeFace (fa) ) continue;
sendnfa++;
(*sendarray).Append ( fa );
(*sendarray).Append ( GetDistantFaceNum (0, fa) );
}
for ( int ed = 1; ed <= ned; ed++ )
{
if ( !IsExchangeEdge (ed) ) continue;
sendned++;
sendarray->Append ( ed );
sendarray->Append ( GetDistantEdgeNum(0, ed) );
}
for ( int vnum = 1; vnum <= np; vnum++ )
sendarray->Append ( GetLoc2Glob_Vert(vnum) );
(*sendarray)[1] = sendnfa;
(*sendarray)[2] = sendned;
MyMPI_Send (*sendarray, 0);
delete sendarray;
}
else
{
Array<int> * recvarray = new Array<int>;
for ( int sender = 1; sender < ntasks; sender++ )
{
MyMPI_Recv ( *recvarray, sender);
int distnel = (*recvarray)[0];
int distnfa = (*recvarray)[1];
int distned = (*recvarray)[2];
int distnp = (*recvarray)[3];
int ii = 4;
for ( int el = 1; el <= distnel; el++ )
SetDistantEl ( sender, (*recvarray)[ii++], el );
for ( int fa = 1; fa <= distnfa; fa++ )
{
int distfa = (*recvarray)[ii++];
SetDistantFaceNum ( sender, (*recvarray)[ii++], distfa );
}
for ( int ed = 1; ed <= distned; ed++ )
{
int disted = (*recvarray)[ii++];
SetDistantEdgeNum ( sender, (*recvarray)[ii++], disted );
}
for ( int vnum = 1; vnum <= distnp; vnum++ )
SetDistantPNum ( sender, (*recvarray)[ii++], vnum );
}
delete recvarray;
}
#ifdef SCALASCA
#pragma pomp inst end(updatecoarsegrid)
#endif
}
void ParallelMeshTopology :: UpdateTopology ()
{
// loop over parallel faces and edges, find new local face/edge number,
const MeshTopology & topology = mesh.GetTopology();
int nfa = topology.GetNFaces();
int ned = topology.GetNEdges();
isghostedge.SetSize(ned);
isghostface.SetSize(nfa);
isghostedge.Clear();
isghostface.Clear();
for ( int ed = 1; ed <= ned; ed++)
{
int v1, v2;
topology.GetEdgeVertices ( ed, v1, v2 );
if ( IsGhostVert(v1) || IsGhostVert(v2) )
SetGhostEdge ( ed );
}
Array<int> pnums;
for ( int fa = 1; fa <= nfa; fa++)
{
topology.GetFaceVertices ( fa, pnums );
for ( int i = 0; i < pnums.Size(); i++)
if ( IsGhostVert( pnums[i] ) )
{
SetGhostFace ( fa );
break;
}
}
}
void ParallelMeshTopology :: UpdateExchangeElements()
{
(*testout) << "UPDATE EXCHANGE ELEMENTS " << endl;
const MeshTopology & topology = mesh.GetTopology();
isexchangeedge->SetSize ( (ntasks+1) * topology.GetNEdges() );
isexchangeface->SetSize ( (ntasks+1) * topology.GetNFaces() );
isexchangeedge->Clear();
isexchangeface->Clear();
for ( int eli = 1; eli <= mesh.GetNE(); eli++)
{
if ( ! IsExchangeElement ( eli ) ) continue;
const Element & el = mesh.VolumeElement(eli);
Array<int> faces, edges;
int np = el.NP();
topology.GetElementEdges ( eli, edges );
topology.GetElementFaces ( eli, faces );
for ( int i = 0; i < edges.Size(); i++)
{
SetExchangeEdge ( edges[i] );
}
for ( int i = 0; i < faces.Size(); i++)
{
SetExchangeFace ( faces[i] );
}
for ( int i = 0; i < np; i++)
{
SetExchangeVert ( el[i] );
}
}
if ( id == 0 ) return;
Array<int> ** elementonproc, ** recvelonproc;
elementonproc = new Array<int>*[ntasks];
recvelonproc = new Array<int>*[ntasks];
for ( int i = 1; i < ntasks; i++ )
{
elementonproc[i] = new Array<int>(0);
recvelonproc[i] = new Array<int>(0);
}
for ( int eli = 1; eli <= mesh.GetNE(); eli++ )
{
if ( !IsExchangeElement(eli) ) continue;
for ( int i = 1; i < ntasks; i++ )
if ( GetDistantElNum(i, eli) != -1 && i != id )
{
elementonproc[i] -> Append(eli);
elementonproc[i] -> Append(GetDistantElNum(i, eli));
}
}
for ( int sender = 1; sender < ntasks; sender ++ )
{
if ( id == sender )
for ( int dest = 1; dest < ntasks; dest ++ )
if ( dest != id)
{
MyMPI_Send ( *(elementonproc[dest]), dest);
elementonproc[dest] -> SetSize(0);
}
if ( id != sender )
{
MyMPI_Recv (*( recvelonproc[sender]), sender);
}
}
int ii = 0;
for ( int sender = 1; sender < ntasks; sender++ )
{
if ( sender == id ) continue;
ii = 0;
while ( recvelonproc[sender]->Size() > ii )
{
int distelnum = (*recvelonproc[sender])[ii++];
int locelnum = (*recvelonproc[sender])[ii++];
SetDistantEl ( sender, locelnum, distelnum);
}
recvelonproc[sender]->SetSize(0);
}
BitArray procs(ntasks);
procs.Clear();
for ( int eli = 1; eli <= mesh.GetNE(); eli++)
{
if ( IsGhostEl(eli) ) continue;
if ( !IsExchangeElement(eli) ) continue;
procs.Clear();
int sumprocs = 0;
for ( int i = 1; i < ntasks; i++ )
if ( GetDistantElNum(i, eli) != -1 && i != id )
{
procs.Set(i);
sumprocs++;
}
for ( int dest = 1; dest < ntasks; dest++)
{
if ( !procs.Test(dest) ) continue;
elementonproc[dest]->Append(GetDistantElNum(dest, eli));
elementonproc[dest]->Append(sumprocs);
for ( int i = 1; i < ntasks; i++ )
if ( procs.Test(i) )
{
elementonproc[dest]->Append(i);
elementonproc[dest]->Append(GetDistantElNum(i, eli));
}
}
}
for ( int sender = 1; sender < ntasks; sender ++ )
{
if ( id == sender )
for ( int dest = 1; dest < ntasks; dest ++ )
if ( dest != id)
{
MyMPI_Send ( *(elementonproc[dest]), dest);
delete elementonproc[dest];
}
if ( id != sender )
{
MyMPI_Recv (*( recvelonproc[sender]), sender);
}
}
for ( int sender = 1; sender < ntasks; sender++ )
{
if ( sender == id ) continue;
ii = 0;
while ( recvelonproc[sender]->Size() > ii )
{
int locelnum = (*recvelonproc[sender])[ii++];
int nprocs = (*recvelonproc[sender])[ii++];
for ( int iproc = 0; iproc < nprocs; iproc++)
{
int proc = (*recvelonproc[sender])[ii++];
int distelnum = (*recvelonproc[sender])[ii++];
if ( id == proc ) continue;
SetExchangeElement (locelnum, proc);
SetDistantEl( proc, locelnum, distelnum );
}
}
delete recvelonproc[sender];
}
delete [] elementonproc;
delete [] recvelonproc;
}
void ParallelMeshTopology :: SetNV ( const int anv )
{
*testout << "called setnv" << endl
<< "old size: " << loc2distvert.Size() << endl
<< "new size: " << anv << endl;
loc2distvert.ChangeSize (anv);
for (int i = 1; i <= anv; i++)
if (loc2distvert.EntrySize(i) == 0)
loc2distvert.Add (i, -1); // will be the global nr
BitArray * isexchangevert2 = new BitArray( (ntasks+1) * anv );
isexchangevert2->Clear();
if ( isexchangevert )
{
for ( int i = 0; i < min2( isexchangevert->Size(), isexchangevert2->Size() ); i++ )
if ( isexchangevert->Test(i) ) isexchangevert2->Set(i);
delete isexchangevert;
}
isexchangevert = isexchangevert2;
nv = anv;
}
void ParallelMeshTopology :: SetNE ( const int ane )
{
loc2distel.ChangeSize (ane);
for (int i = 0; i < ane; i++)
{
if (loc2distel[i].Size() == 0)
loc2distel.Add (i, -1); // will be the global nr
}
BitArray * isexchangeel2 = new BitArray ( (ntasks+1) * ane );
isexchangeel2->Clear();
if ( isexchangeel )
{
for ( int i = 0; i < min2(isexchangeel->Size(), isexchangeel2->Size() ) ; i++ )
if ( isexchangeel->Test(i) ) isexchangeel2->Set(i);
delete isexchangeel;
}
ne = ane;
isexchangeel = isexchangeel2;
}
void ParallelMeshTopology :: SetNSE ( int anse )
{
loc2distsurfel.ChangeSize (anse);
for (int i = 0; i < anse; i++)
if (loc2distsurfel[i].Size() == 0)
loc2distsurfel.Add (i, -1); // will be the global nr
nsurfel = anse;
}
void ParallelMeshTopology :: SetNSegm ( int anseg )
{
loc2distsegm.ChangeSize (anseg);
for (int i = 0; i < anseg; i++)
if (loc2distsegm[i].Size() == 0)
loc2distsegm.Add (i, -1); // will be the global nr
nseg = anseg;
}
}
#endif
| JSchoeberl/netgen-test | libsrc/meshing/paralleltop.cpp | C++ | lgpl-2.1 | 42,485 |
/****************************************************************************
** Meta object code from reading C++ file 'qtdocinstaller.h'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../qtdocinstaller.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'qtdocinstaller.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_QtDocInstaller[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
3, // signalCount
// signals: signature, parameters, type, tag, flags
26, 16, 15, 15, 0x05,
73, 51, 15, 15, 0x05,
129, 112, 15, 15, 0x05,
0 // eod
};
static const char qt_meta_stringdata_QtDocInstaller[] = {
"QtDocInstaller\0\0component\0"
"qchFileNotFound(QString)\0component,absFileName\0"
"registerDocumentation(QString,QString)\0"
"newDocsInstalled\0docsInstalled(bool)\0"
};
void QtDocInstaller::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
QtDocInstaller *_t = static_cast<QtDocInstaller *>(_o);
switch (_id) {
case 0: _t->qchFileNotFound((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 1: _t->registerDocumentation((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break;
case 2: _t->docsInstalled((*reinterpret_cast< bool(*)>(_a[1]))); break;
default: ;
}
}
}
const QMetaObjectExtraData QtDocInstaller::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject QtDocInstaller::staticMetaObject = {
{ &QThread::staticMetaObject, qt_meta_stringdata_QtDocInstaller,
qt_meta_data_QtDocInstaller, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &QtDocInstaller::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *QtDocInstaller::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *QtDocInstaller::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_QtDocInstaller))
return static_cast<void*>(const_cast< QtDocInstaller*>(this));
return QThread::qt_metacast(_clname);
}
int QtDocInstaller::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QThread::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
}
return _id;
}
// SIGNAL 0
void QtDocInstaller::qchFileNotFound(const QString & _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void QtDocInstaller::registerDocumentation(const QString & _t1, const QString & _t2)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
// SIGNAL 2
void QtDocInstaller::docsInstalled(bool _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 2, _a);
}
QT_END_MOC_NAMESPACE
| nonrational/qt-everywhere-opensource-src-4.8.6 | tools/assistant/tools/assistant/.moc/release-shared/moc_qtdocinstaller.cpp | C++ | lgpl-2.1 | 4,016 |
#ifndef SILL_GRAPH_TRAVERSAL_HPP
#define SILL_GRAPH_TRAVERSAL_HPP
#include <deque>
#include <vector>
#include <iterator>
#include <map>
#include <sill/global.hpp>
#include <sill/graph/algorithm/output_edge_visitor.hpp>
#include <sill/range/reversed.hpp>
#include <sill/macros_def.hpp>
namespace sill {
/**
* Visits each vertex of a directed acyclic graph once in a traversal
* such that each \f$v\f$ is visited after all nodes \f$u\f$ with
* \f$u \rightarrow v\f$ are visited.
*
* \ingroup graph_algorithms
*/
template <typename Graph>
std::vector<typename Graph::vertex>
directed_partial_vertex_order(const Graph& g) {
typedef typename Graph::edge edge;
typedef typename Graph::vertex vertex;
if (g.num_vertices() == 0)
return std::vector<vertex>();
// Find all vertices without parents
// Maintain a set of 'remaining_edges' which still need to be traversed,
// the sources of which are in 'vertices' and the targets of which
// may be in 'vertices' or 'remaining_vertices.'
std::list<edge> remaining_edges;
std::vector<vertex> vertices;
// Contains remaining vertices, plus a count of the number of in-edges
// in remaining_edges.
std::map<vertex, size_t> remaining_vertices;
foreach(vertex v, g.vertices()) {
typename Graph::neighbor_iterator parents_it, parents_end;
boost::tie(parents_it, parents_end) = g.parents(v);
if (parents_it == parents_end) {
vertices.push_back(v);
foreach(edge e, g.out_edges(v))
remaining_edges.push_back(e);
} else
remaining_vertices[v] = g.in_degree(v);
}
assert(vertices.size() > 0);
// Add in the remaining vertices in partial order
while(remaining_edges.size() > 0) {
edge e(remaining_edges.front());
remaining_edges.pop_front();
vertex v(e.target());
if (remaining_vertices.count(v)) {
size_t in_d(remaining_vertices[v]);
if (in_d == 1) {
remaining_vertices.erase(v);
vertices.push_back(v);
foreach(edge e2, g.out_edges(v))
remaining_edges.push_back(e2);
} else
remaining_vertices[v] = in_d - 1;
}
}
return vertices;
}
} // namespace sill
#include <sill/macros_undef.hpp>
#endif // #ifndef SILL_GRAPH_TRAVERSAL_HPP
| Matt3164/sill | src/sill/graph/algorithm/graph_traversal.hpp | C++ | lgpl-2.1 | 2,347 |
#include "EngineObjects.h"
#include "Engine.h"
#include "SaveStateProvider.h"
#include "Inventory.h"
#include "ScriptFunc.h"
#include "Sound.h"
#include "SoundPlayer.h"
#include <system/allocation.h>
using namespace adv;
TR_CHANNEL_LVL(ADV_Character, TRACE_INFO);
TR_CHANNEL(ADV_Room);
BlitGroup::BlitGroup(std::vector<std::string> textures, const Vec2i& size, std::vector<Vec2i> offsets, int depth){
for (unsigned l = (unsigned)textures.size(); l > 0; --l){
BlitObject* obj = new BlitObject(textures[l-1], size, depth, offsets[l-1]);
mBlits.push_back(obj);
}
}
BlitGroup::BlitGroup(const std::string& texture, const Vec2i& size, const Vec2i& offset, int depth){
BlitObject* obj = new BlitObject(texture, size, depth, offset);
mBlits.push_back(obj);
}
BlitGroup::~BlitGroup(){
for (unsigned i = 0; i < mBlits.size(); ++i){
delete mBlits[i];
}
}
void BlitGroup::render(const Vec2i& pos, const Vec2f& scale, const Vec2i& parentsize, const Color& color, float rotation){
for (unsigned i = 0; i < mBlits.size(); ++i){
mBlits[i]->setColor(color);
mBlits[i]->setRotation(rotation);
mBlits[i]->render(pos, scale, parentsize);
}
}
void BlitGroup::setDepth(int depth){
for (unsigned i = 0; i < mBlits.size(); ++i){
mBlits[i]->setDepth(depth);
}
}
void BlitGroup::setBlendMode(BlitObject::BlendMode mode){
for (unsigned i = 0; i < mBlits.size(); ++i){
mBlits[i]->setBlendMode(mode);
}
}
BlitGroup* BlitGroup::clone(){
BlitGroup* bltgrp = new BlitGroup();
for (unsigned i = 0; i < mBlits.size(); ++i){
BlitObject* bltobj = mBlits[i]->clone();
bltgrp->mBlits.push_back(bltobj);
}
return bltgrp;
}
void BlitGroup::realize(){
for (unsigned i = 0; i < mBlits.size(); ++i){
mBlits[i]->realize();
}
}
TR_CHANNEL(ADV_Animation);
Animation::Animation(float fps) : mInterval((unsigned)(1000.0f/fps)), mCurrFrame(0), mTimeAccu(0), mHandler(NULL){
}
Animation::Animation(ExtendedFrames& frames, float fps, int depth, const Vec2i& cropSize) : mInterval((unsigned)(1000.0f/fps)), mTimeAccu(0),
mCurrFrame(0), mHandler(NULL){
for (unsigned k = 0; k < frames.size(); ++k){
BlitGroup* group = new BlitGroup(frames[k].names, cropSize, frames[k].offsets, depth);
mBlits.push_back(group);
if (!frames[k].script.empty()){
ExecutionContext* scr = Engine::instance()->getInterpreter()->parseProgram(frames[k].script);
mScripts.push_back(scr);
}
else{
mScripts.push_back(NULL);
}
}
}
Animation::Animation(Frames& frames, float fps, Vec2i offset, int depth, const Vec2i& cropSize) : mInterval((unsigned)(1000.0f/fps)),
mTimeAccu(0), mCurrFrame(0), mHandler(NULL){
for (unsigned k = 0; k < frames.size(); ++k){
BlitGroup* group = new BlitGroup(frames[k].name, cropSize, offset, depth);
mBlits.push_back(group);
if (!frames[k].script.empty()){
ExecutionContext* scr = Engine::instance()->getInterpreter()->parseProgram(frames[k].script);
mScripts.push_back(scr);
}
else{
mScripts.push_back(NULL);
}
}
}
Animation::Animation(SimpleFrames& frames, float fps, Vec2i offset, int depth, const Vec2i& cropSize) : mInterval((unsigned)(1000.0f/fps)),
mTimeAccu(0), mCurrFrame(0), mHandler(NULL){
for (unsigned k = 0; k < frames.size(); ++k){
BlitGroup* group = new BlitGroup(frames[k], cropSize, offset, depth);
mBlits.push_back(group);
mScripts.push_back(NULL);
}
}
Animation::~Animation(){
for (unsigned k = 0; k < mBlits.size(); ++k){
delete mBlits[k];
if (mScripts.size() > k && mScripts[k] != NULL)
Engine::instance()->getInterpreter()->remove(mScripts[k]);
}
}
void Animation::render(const Vec2i& pos, const Vec2f& scale, const Vec2i& parentsize, const Color& color, float rotation){
if (mBlits.size() > mCurrFrame)
mBlits[mCurrFrame]->render(pos, scale, parentsize, color, rotation);
}
void Animation::setDepth(int depth){
for (unsigned k = 0; k < mBlits.size(); ++k){
mBlits[k]->setDepth(depth);
}
}
void Animation::start(){
mCurrFrame = 0;
mTimeAccu = 0;
}
void Animation::update(unsigned interval){
mTimeAccu += interval;
while(mTimeAccu >= mInterval){
mTimeAccu -= mInterval;
++mCurrFrame;
if (mCurrFrame >= mBlits.size()){
if (mHandler){
if (mHandler->animationEnded(this))
mHandler = NULL;
}
mCurrFrame = 0;
}
executeScript();
}
}
Animation* Animation::clone(){
Animation* anim = new Animation(1000.0f/mInterval);
for (unsigned i = 0; i < mBlits.size(); ++i){
BlitGroup* bltgrp = mBlits[i]->clone();
anim->mBlits.push_back(bltgrp);
}
return anim;
}
void Animation::setBlendMode(BlitObject::BlendMode mode){
for (unsigned k = 0; k < mBlits.size(); ++k){
mBlits[k]->setBlendMode(mode);
}
}
void Animation::executeScript(){
if (mCurrFrame >= mScripts.size())
return;
ExecutionContext* ctx = mScripts[mCurrFrame];
if (ctx == NULL)
return;
if (!Engine::instance()->getInterpreter()->executeImmediately(ctx)){
TR_USE(ADV_Animation);
TR_BREAK("Animation::executeScript script contains blocking commands");
}
}
void Animation::realize(){
for (unsigned k = 0; k < mBlits.size(); ++k){
mBlits[k]->realize();
}
}
Object2D::Object2D(int state, const Vec2i& pos, const Vec2i& size, const std::string& name)
: mState(state), mPos(pos), mSize(size), mScript(NULL), mSuspensionScript(NULL), mName(name),
mLightingColor(), mScale(1.0f), mUserScale(1.0f), mRotAngle(0.0f), mDepth(0){
}
Object2D::~Object2D(){
Engine::instance()->remove(this);
Engine::instance()->getAnimator()->remove(this);
Engine::instance()->getInterpreter()->remove(this);
for (unsigned i = 0; i < mAnimations.size(); ++i){
delete mAnimations[i];
}
}
void Object2D::render(){
if (mState <= 0 || (unsigned)mState > mAnimations.size())
return;
mAnimations[mState-1]->render(mPos+mScrollOffset, Vec2f(mScale*mUserScale,mScale*mUserScale), mSize, mLightingColor, mRotAngle);
}
Animation* Object2D::getAnimation(){
return getAnimation(mState);
}
Animation* Object2D::getAnimation(int state){
if (state <= 0 || (unsigned)state > mAnimations.size())
return NULL;
return mAnimations[state-1];
}
bool Object2D::isHit(const Vec2i& point){
if (mScript == NULL || mState == 0)
return false;
//Vec2i scaleoffset;
//scaleoffset.x = (int)((1.0f-abs(mScale))*(getSize().x-getSize().x*abs(mScale)));
//scaleoffset.y = (int)(getSize().y-getSize().y*mScale);
if (point.x >= mPos.x/*+scaleoffset.x*/ && point.x <= mPos.x+/*scaleoffset.x*/+getSize().x){
if (point.y >= mPos.y/*+scaleoffset.y*/ && point.y <= mPos.y+/*scaleoffset.y*/+getSize().y)
return true;
}
return false;
}
void Object2D::animationEnd(const Vec2i& prev, bool aborted){
if (mSuspensionScript){
mSuspensionScript->resume();
if (aborted)
mSuspensionScript->reset(true, true);
mSuspensionScript->unref();
mSuspensionScript = NULL;
}
}
void Object2D::setSuspensionScript(ExecutionContext* script){
if (mSuspensionScript != NULL){
mSuspensionScript->reset(true,true);
mSuspensionScript->unref();
}
script->ref();
mSuspensionScript = script;
}
void Object2D::save(SaveStateProvider::SaveRoom* room){
SaveStateProvider::SaveObject* save = Engine::instance()->getSaver()->getOrAddObject(room, mName);
if (save){
Vec2i pos = Engine::instance()->getAnimator()->getTargetPoisition(this);
save->position = pos;
save->state = mState;
save->lighting = mLightingColor;
save->name = mName;
}
}
int Object2D::getDepth(){
//return mPos.y/Engine::instance()->getWalkGridSize();
return mDepth;
}
void Object2D::setDepth(int depth){
mDepth = depth;
for (unsigned i = 0; i < mAnimations.size(); ++i){
mAnimations[i]->setDepth(depth);
}
}
bool Object2D::animationEnded(Animation* anim){
activateNextState();
return mNextStates.empty() || getAnimation() != anim;
}
int Object2D::removeLastNextState(){
int ret;
if (!mNextStates.empty()){
ret = mNextStates.back();
mNextStates.pop_back();
}
else
ret = getState();
return ret;
}
void Object2D::activateNextState(){
if (mNextStates.empty())
return;
mState = mNextStates.front();
mNextStates.pop_front();
if (mState > 0 && mAnimations[mState-1]->exists())
mAnimations[mState-1]->registerAnimationEndHandler(this);
}
Object2D* Object2D::clone(){
Object2D* ret = new Object2D(mState, mPos, mSize, mName);
for (unsigned i = 0; i < mAnimations.size(); ++i){
Animation* anim = mAnimations[i]->clone();
ret->addAnimation(anim);
}
ret->mRotAngle = mRotAngle;
return ret;
}
unsigned Object2D::getNumDefinedStates(){
for (unsigned i = 0; i < mAnimations.size(); ++i){
if (!mAnimations[i]->exists())
return i;
}
return (unsigned)mAnimations.size();
}
void Object2D::setLighten(bool lighten){
for (unsigned i = 0; i < mAnimations.size(); ++i){
mAnimations[i]->setBlendMode(lighten ? BlitObject::BLEND_ADDITIVE : BlitObject::BLEND_ALPHA);
}
}
void Object2D::update(unsigned interval){
Animation* anim = getAnimation();
if (anim != NULL)
anim->update(interval);
}
void Object2D::realize(){
for (unsigned i = 0; i < mAnimations.size(); ++i){
mAnimations[i]->realize();
}
if (mScript)
Engine::instance()->getInterpreter()->execute(mScript, false);
}
ButtonObject::ButtonObject(const Vec2i& pos, const Vec2i& size, const std::string& text, int id) : Object2D(1, pos, size, "!button"),
BlitObject(Engine::instance()->getSettings()->tsbackground, Vec2i(), DEPTH_BUTTON, Vec2i()), mText(text){
BlitObject::realize();
char tmp[2048];
sprintf(tmp, "%i", id);
mName += tmp;
mState = Engine::instance()->getInterpreter()->getVariable(mName.c_str()).getInt();
if (mState == 0)
mState = 1;
Engine::instance()->getInterpreter()->setVariable(mName.c_str(), 1);
BaseBlitObject::mPos = pos;
BaseBlitObject::mSize = size;
mBackgroundColor = Engine::instance()->getSettings()->tsareacolor;
mBorderColor = Engine::instance()->getSettings()->tsbordercolor;
mHighlightColor = Engine::instance()->getSettings()->tsselectioncolor;
mTextColor = Engine::instance()->getSettings()->tstextcolor;
if (Engine::instance()->getSettings()->tsstyle == TS_TRANSPARENT){
mBackgroundColor.a = 127;
mHighlightColor.a = 127;
}
sprintf(tmp,
"on(click)\n"
" setnum(!button; %i)\n"
"\n"
"on(mouse){\n"
" setnum(%s; 2)\n"
" setobj(%s; 2)\n"
"}\n"
"\n"
"on(mouseout){\n"
" setnum(%s; 1)\n"
" setobj(%s; 1)\n"
"}\n",
id, mName.c_str(), mName.c_str(), mName.c_str(), mName.c_str()
);
mScript = Engine::instance()->getInterpreter()->parseProgram(tmp, PCDK_SCRIPT);
mFont = Engine::instance()->getFontID();
mHighlightText = mTex != 0;
mOldHighlighting = true;
}
ButtonObject::~ButtonObject(){
}
void ButtonObject::setColors(const Color& background, const Color& border, const Color& highlight, const Color& text){
mBackgroundColor = background;
mBorderColor = border;
mHighlightColor = highlight;
mTextColor = text;
}
void ButtonObject::render(){
String labelVar = String(mName.c_str())+"Label";
if (Engine::instance()->getInterpreter()->isVariable(labelVar)){
mText = Engine::instance()->getInterpreter()->getVariable(labelVar.c_str()).getString();
Engine::instance()->getInterpreter()->deleteVariable(labelVar);
}
std::vector<Vec2i> breakinfo;
breakinfo.push_back(Vec2i((int)mText.size(), 0)); //fake break
//Engine::instance()->getFontRenderer()->getTextExtent(mText, 1, breakinfo);
Color textcol = mTextColor;
if (mHighlightText && mOldHighlighting){
if (mState == 2){
Color tmp = textcol;
textcol *= mHighlightColor;
textcol += tmp;
}
}
else if (mHighlightText){
if (mState == 2)
textcol = mHighlightColor;
}
textcol.a = textcol.a*mLightingColor.a/255;
FontRenderer::String* str = Engine::instance()->getFontRenderer()->render(Object2D::mPos.x, Object2D::mPos.y, mText, DEPTH_UI_FONT, mFont, breakinfo, textcol, 0, true, ALGN_LEFT);
Engine::instance()->insertToBlit(this);
}
void ButtonObject::blit(){
if (mTex != 0){
mColor.a = mLightingColor.a;
BlitObject::blit();
return;
}
CGE::Renderer* rend = CGE::Engine::instance()->getRenderer();
rend->pushMatrix();
rend->enableTexturing(false);
if (mState == 1 || mHighlightText)
rend->setColor(mBackgroundColor.r / 255.0f, mBackgroundColor.g / 255.0f, mBackgroundColor.b / 255.0f, mBackgroundColor.a*mLightingColor.a / 255 / 255.0f);
else if (mState == 2)
rend->setColor(mHighlightColor.r / 255.0f, mHighlightColor.g / 255.0f, mHighlightColor.b / 255.0f, mHighlightColor.a*mLightingColor.a / 255 / 255.0f);
rend->translate((float)BaseBlitObject::mPos.x,(float)BaseBlitObject::mPos.y,0.0f);
rend->scale((float)BaseBlitObject::mSize.x,(float)BaseBlitObject::mSize.y,1.0f);
Engine::instance()->drawQuad();
rend->setColor(mBorderColor.r / 255.0f, mBorderColor.g / 255.0f, mBorderColor.b / 255.0f, mBorderColor.a*mLightingColor.a / 255 / 255.0f);
Engine::instance()->drawQuadLines();
rend->enableTexturing(true);
rend->setColor(1.0f, 1.0f, 1.0f, 1.0f);
rend->popMatrix();
}
CursorObject::CursorObject(const Vec2i& pos, int rightclick) : Object2D(1, pos, Vec2i(32,32), "xxx"), mSavedState(0), mRightclick(rightclick) {
}
CursorObject::~CursorObject(){
}
void CursorObject::addAnimation(Animation* anim, int command, const Vec2i& itemoffset){
Object2D::addAnimation(anim);
mCommands.push_back(command);
mItemOffsets.push_back(itemoffset);
}
int CursorObject::getNextCommand(bool& leftClickRequired, const Vec2i& pos){
if (mState == 0)
return 0;
//right click does nothing
if (mRightclick == 2){
leftClickRequired = false;
}
//right click changes to icon 1
else if (mRightclick == 1){
if (2-1 >= (int)mAnimations.size()-1 || !mAnimations[2-1]->exists()){ //no command bound
mState = 1;
leftClickRequired = true;
return mCommands[2] != 0 ? mCommands[2] : 2; //take the next action
}
else{
if (Engine::instance()->getObjectAt(pos) != NULL){
Engine::instance()->resetCursor(false, true);
mState = 2;
Engine::instance()->getInterpreter()->setPrevState(this, this);
}
else
Engine::instance()->resetCursor(true, true);
leftClickRequired = false;
}
}
//classic mode
else{
++mState;
if (mState-1 >= (int)mAnimations.size()-1 || !mAnimations[mState-1]->exists()){ //no command bound
if (mState == 2){
mState = 1;
leftClickRequired = true;
return mCommands[mState] != 0 ? mCommands[mState] : 2; //take the next action
}
else
mState = 1;
}
leftClickRequired = false;
}
return mCommands[mState-1];
}
int CursorObject::getCurrentCommand(){
if (mState == 0)
return 0;
return mCommands[mState-1];
}
void CursorObject::setCommand(int command){
int& state = mState == 10 ? mSavedState : mState;
for (unsigned i = 0; i < mCommands.size(); ++i){
if (mCommands[i] == command){
state = i+1;
if (state - 1 >= (int)mAnimations.size() - 1 || !mAnimations[state - 1]->exists()){
state = 1;
}
break;
}
}
}
void CursorObject::showLoading(bool loading){
if (loading && mSavedState == 0){
mSavedState = mState;
mState = 10;
}
else if (!loading && mSavedState != 0){
mState = mSavedState;
mSavedState = 0;
}
}
Vec2i CursorObject::getItemOffset(){
if (mState == 0)
return Vec2i();
return mItemOffsets[mState - 1];
}
RoomObject::RoomObject(int state, const Vec2i& pos, const Vec2i& size, const std::string& name, const Vec2i& depthmap, bool doublewalkmap) :
Object2D(state, pos, size, name), mInventroy(NULL), mDepthMap(), mFadeout(0), mDoubleWalkmap(doublewalkmap){
mLighting = new LightingBlitObject(DEPTH_LIGHTING, size);
mParallaxBackground = NULL;
mDepthMap.init(depthmap, (int)Engine::instance()->getWalkGridSize(false));
}
RoomObject::~RoomObject(){
Engine::instance()->getAnimator()->remove(this);
for (unsigned i = 0; i < mMirrors.size(); ++i){
delete mMirrors[i];
}
for (unsigned i = 0; i < mObjects.size(); ++i){
if (mObjects[i]->getType() == Object2D::CHARACTER){
CharacterObject* chr = (CharacterObject*)mObjects[i];
Engine::instance()->disposeCharacter(chr);
}
else
delete mObjects[i];
}
delete mLighting;
for (std::map<Vec2i,ExecutionContext*>::iterator iter = mWalkmapScripts.begin(); iter != mWalkmapScripts.end(); ++iter){
Engine::instance()->getInterpreter()->remove(iter->second);
}
delete mInventroy;
delete mParallaxBackground;
}
void RoomObject::render(){
//render the mirror objects offscreen before they are inserted into normal blit queue
if (Engine::instance()->areFXShapesEnabled()){
for (unsigned i = 0; i < mMirrors.size(); ++i){
mMirrors[i]->update(0);
}
}
if (mParallaxBackground)
mParallaxBackground->render(Vec2i(), Vec2f(mScale*mUserScale,mScale*mUserScale), mSize, mLightingColor, mRotAngle);
Object2D::render();
for (int i = (int)mObjects.size()-1; i >= 0; --i){
if (mObjects[i]->getType() != CHARACTER)
mObjects[i]->render();
}
for (int i = (int)mObjects.size()-1; i >= 0; --i){
if (mObjects[i]->getType() == CHARACTER)
mObjects[i]->render();
}
CharacterObject* currChar = Engine::instance()->getCharacter("self");
if (mInventroy && currChar && Engine::instance()->getMainRoom() != this){
mInventroy->render(currChar->getInventory());
}
mLighting->render(Vec2i());
if (Engine::instance()->areFXShapesEnabled()){
for (unsigned i = 0; i < mMirrors.size(); ++i){
mMirrors[i]->render(Vec2i(), Vec2f(1.0f,1.0f), Vec2i());
}
}
}
void RoomObject::setBackground(std::string bg, int depth){
if (bg.empty())
return;
SimpleFrames f;
f.push_back(bg);
Animation* anim = new Animation(f, 2.5f, Vec2i(0,0), depth, mSize);
addAnimation(anim);
}
void RoomObject::setParallaxBackground(const std::string& bg, int depth){
if (bg.empty())
return;
SimpleFrames f;
f.push_back(bg);
mParallaxBackground = new Animation(f, 2.5f, Vec2i(), depth, mSize);
}
void RoomObject::addObject(Object2D* obj){
obj->setPosition(obj->getPosition()+mPos);
obj->setScrollOffset(mScrollOffset);
//obj->setScale(getDepthScale(obj->getPosition()));
mObjects.push_back(obj);
}
Object2D* RoomObject::getObjectAt(const Vec2i& pos){
Object2D* curr = NULL;
CharacterObject* currChar = Engine::instance()->getCharacter("self");
if (mInventroy && currChar){
curr = mInventroy->getObjectAt(pos, currChar->getInventory());
}
if (curr)
return curr;
int currdepth = -10000;
for (unsigned i = 0; i < mObjects.size(); ++i){
if(mObjects[i]->isHit(pos-mScrollOffset)){
if ((mObjects[i]->getType() != Object2D::CHARACTER && mObjects[i]->getDepth() >= currdepth) ||
(mObjects[i]->getType() == Object2D::CHARACTER && mObjects[i]->getDepth() > currdepth)){
curr = mObjects[i];
currdepth = curr->getDepth();
}
}
}
return curr;
}
Object2D* RoomObject::getObject(const std::string& name){
for (unsigned i = 0; i < mObjects.size(); ++i){
if (mObjects[i]->getType() != Object2D::OBJECT) //find only 'real' objects
continue;
String comparename(mObjects[i]->getName());
comparename = comparename.removeAll(' ');
if(_stricmp(comparename.c_str(), name.c_str()) == 0)
return mObjects[i];
}
return NULL;
}
CharacterObject* RoomObject::extractCharacter(const std::string& name){
for (std::vector<Object2D*>::iterator iter = mObjects.begin(); iter != mObjects.end(); ++iter){
if ((*iter)->getType() == Object2D::CHARACTER){
CharacterObject* ch = static_cast<CharacterObject*>((*iter));
if (_stricmp(ch->getName().c_str(), name.c_str()) == 0){
mObjects.erase(iter);
SaveStateProvider::SaveRoom* sr = Engine::instance()->getSaver()->getRoom(mName);
Engine::instance()->getSaver()->removeCharacter(sr, name);
return ch;
}
}
}
return NULL;
}
CharacterObject* RoomObject::findCharacter(const std::string& name){
for (std::vector<Object2D*>::iterator iter = mObjects.begin(); iter != mObjects.end(); ++iter){
if ((*iter)->getType() == Object2D::CHARACTER){
CharacterObject* ch = static_cast<CharacterObject*>((*iter));
if (_stricmp(ch->getName().c_str(), name.c_str()) == 0){
return ch;
}
}
}
return NULL;
}
bool RoomObject::isWalkable(CharacterObject* walker, const Vec2i& pos){
if (pos.x < 0 || pos.x >= mWalkmap.size() || pos.y < 0 || pos.y >= mWalkmap[0].size()){
return false;
}
WMField field = mWalkmap[pos.x][pos.y];
if (!field.walkable)
return false;
Vec2i walkerpos = walker->getPosition() / walker->getWalkGridSize();
for (unsigned i = 0; i < mObjects.size(); ++i){
if (mObjects[i]->getType() != CHARACTER)
continue;
CharacterObject* chr = (CharacterObject*)mObjects[i];
if (chr == walker)
continue;
if (chr->isStandingAt(pos) && !chr->isStandingAt(walkerpos))
return false;
}
CharacterObject* chr = Engine::instance()->getCharacter("self");
if (chr && chr != walker){
if (chr->isStandingAt(pos) && !chr->isStandingAt(walkerpos))
return false;
}
return true;
}
void RoomObject::update(unsigned interval){
for (unsigned i = 0; i < mObjects.size(); ++i){
mObjects[i]->update(interval);
}
}
void RoomObject::walkTo(CharacterObject* chr, const Vec2i& pos){
std::map<Vec2i,ExecutionContext*>::iterator iter = mWalkmapScripts.find(pos);
if (iter == mWalkmapScripts.end())
return;
ExecutionContext* scr = iter->second;
scr->setSelf(chr->getName());
Engine::instance()->getInterpreter()->execute(scr, true);
}
void RoomObject::setScrollOffset(const Vec2i& offset){
mScrollOffset=offset;
if (mScrollOffset.x > 0)
mScrollOffset.x = 0;
if (mScrollOffset.y > 0)
mScrollOffset.y = 0;
if (mScrollOffset.x < Engine::instance()->getResolution().x-mSize.x)
mScrollOffset.x = Engine::instance()->getResolution().x-mSize.x;
if (mScrollOffset.y < Engine::instance()->getResolution().y-mSize.y)
mScrollOffset.y = Engine::instance()->getResolution().y-mSize.y;
for (std::vector<Object2D*>::iterator iter = mObjects.begin(); iter != mObjects.end(); ++iter){
(*iter)->setScrollOffset(mScrollOffset);
}
if (Engine::instance()->getRoom("") == this){
CharacterObject* chr = Engine::instance()->getCharacter("self");
if (chr)
chr->setScrollOffset(mScrollOffset);
}
}
void RoomObject::save(SaveStateProvider::SaveRoom* containingRoom){
SaveStateProvider::SaveRoom* save = Engine::instance()->getSaver()->getRoom(mName);
if (!save)
return;
save->base.position = mPos;
save->base.state = mState;
save->base.lighting = mLightingColor;
save->overlaylighting = mLighting->getColor();
save->scrolloffset = mScrollOffset;
save->walkmap = mModifiedWalkmap;
for (unsigned i = 0; i < mObjects.size(); ++i){
mObjects[i]->save(save);
}
}
void RoomObject::setPosition(const Vec2i& pos){
if (pos.x < -1000 || pos.x > 1000){
TR_USE(ADV_Room);
TR_BREAK("Invalid room position %i/%i", pos.x, pos.y);
}
Vec2i move = pos - mPos;
for (std::vector<Object2D*>::iterator iter = mObjects.begin(); iter != mObjects.end(); ++iter){
(*iter)->setPosition((*iter)->getPosition()+move);
//(*iter)->setScale(getDepthScale((*iter)->getPosition()));
}
mPos += move;
if (mInventroy)
mInventroy->setPosition(mInventroy->getPosition()+move);
}
bool RoomObject::containsObject(Object2D* object){
for (std::vector<Object2D*>::iterator iter = mObjects.begin(); iter != mObjects.end(); ++iter){
if ((*iter) == object)
return true;
}
return false;
}
void RoomObject::setInventory(InventoryDisplay* disp){
mInventroy = disp;
mInventroy->setPosition(mInventroy->getPosition()+mPos);
}
bool RoomObject::isScriptRunning(){
if (mFadeout > 0)
return true;
for (std::vector<Object2D*>::iterator iter = mObjects.begin(); iter != mObjects.end(); ++iter){
if ((*iter)->getScript() != NULL && (*iter)->getScript()->isRunning())
return true;
}
if (mScript != NULL && mScript->isRunning())
return true;
return false;
}
Vec2i RoomObject::getScriptPosition(ExecutionContext* wmscript){
for (std::map<Vec2i,ExecutionContext*>::iterator iter = mWalkmapScripts.begin(); iter != mWalkmapScripts.end(); ++iter){
if (iter->second == wmscript)
return iter->first;
}
return Vec2i(-1,-1);
}
void RoomObject::finishScripts(bool execute){
for (std::vector<Object2D*>::iterator iter = mObjects.begin(); iter != mObjects.end(); ++iter){
if ((*iter)->getScript() != NULL){
(*iter)->getScript()->finish();
if (execute && (*iter)->getScript()->isRunning()){
//(*iter)->getScript()->resume();
Engine::instance()->getInterpreter()->executeImmediately((*iter)->getScript());
}
}
Engine::instance()->getInterpreter()->applyPrevState(*iter);
}
if (mScript != NULL/* && mScript->isRunning()*/){
//mScript->resetEvent(EVT_LOOP1);
//mScript->resetEvent(EVT_LOOP2);
mScript->finish();
if (execute && mScript->isRunning()){
//mScript->resume();
Engine::instance()->getInterpreter()->executeImmediately(mScript);
}
}
}
bool RoomObject::unbindScript(ExecutionContext* ctx){
ExecutionContext* script = NULL;
for (std::vector<Object2D*>::iterator iter = mObjects.begin(); iter != mObjects.end(); ++iter){
if ((*iter)->getScript() == ctx){
(*iter)->setScript(NULL);
script = ctx;
break;
}
}
if (script != NULL){
script->setOwner(NULL);
script->setExecuteOnce();
return true;
}
return false;
}
float RoomObject::getDepthScale(const Vec2i& pos){
float factor = (pos.y-mDepthMap.scaleStart)/(float)(mDepthMap.scaleStop-mDepthMap.scaleStart);
factor = factor < 0 ? 0 : factor;
factor = factor > 1.0f ? 1.0f : factor;
float ret = (1-factor)*1+(factor)*mDepthMap.minVal;
return ret;
}
float RoomObject::getDepthScale(const Vec2i& pos, int depthStart, int depthEnd, int zoomfactor){
float minVal = (float)(1.0f-(depthStart-depthEnd)/((float)Engine::instance()->getSettings()->resolution.y)*zoomfactor*0.3f);
float factor = (pos.y-depthStart)/(float)(depthEnd-depthStart);
factor = factor < 0 ? 0 : factor;
factor = factor > 1.0f ? 1.0f : factor;
float ret = (1-factor)*1+(factor)*minVal;
return ret;
}
RoomObject::DepthMap::DepthMap(){}
void RoomObject::DepthMap::init(Vec2i depthmap, int walkgridsize){
scaleStart = depthmap.y*walkgridsize;
scaleStop = depthmap.x*walkgridsize;
setZoomFactor(3);
}
void RoomObject::DepthMap::setZoomFactor(int factor){
minVal = (float)(1.0f-(scaleStart-scaleStop)/((float)Engine::instance()->getSettings()->resolution.y)*factor*0.3f);
//minVal = (float)(1.0f-(depthmap.y-depthmap.x)/((float)Engine::instance()->getSettings()->resolution.y/Engine::instance()->getWalkGridSize())*zoomfactor);
}
void RoomObject::setOpacity(unsigned char opacity){
mLightingColor.a = opacity;
for (std::vector<Object2D*>::iterator iter = mObjects.begin(); iter != mObjects.end(); ++iter){
Color c = (*iter)->getLightingColor();
c.a = opacity;
(*iter)->setLightingColor(c);
}
}
bool RoomObject::hitsBarriers(const ParticleEngine::Particle& particle){
for (unsigned i = 0; i < mBarriers.size(); ++i){
if (mBarriers[i].isHit(particle, mScrollOffset))
return true;
}
return false;
}
void RoomObject::modifyWalkmap(const Vec2i& pos, bool walkable){
mWalkmap[pos.x-1][pos.y-1].walkable = walkable;
mModifiedWalkmap[pos] = walkable;
}
void RoomObject::setDepth(int depth){
mDepth = depth;
}
float RoomObject::getWalkGridSize(){
return Engine::instance()->getWalkGridSize(mDoubleWalkmap);
}
void RoomObject::realize(){
Object2D::realize();
for (unsigned i = 0; i < mObjects.size(); ++i){
mObjects[i]->realize();
}
if (mParallaxBackground)
mParallaxBackground->realize();
for (unsigned i = 0; i < mMirrors.size(); ++i){
mMirrors[i]->realize();
}
}
void RoomObject::getBBox(Vec2i& min, Vec2i& max){
min.x = INT_MAX; min.y = INT_MAX;
max.x = INT_MIN; max.y = INT_MIN;
for (unsigned i = 0; i < mObjects.size(); ++i){
if (!mObjects[i]->getAnimation()->exists())
continue;
Vec2i minpos = mObjects[i]->getPosition();
Vec2i maxpos = minpos+mObjects[i]->getSize();
if (minpos.x < min.x)
min.x = minpos.x;
if (minpos.y < min.y)
min.y = minpos.y;
if (maxpos.x > max.x)
max.x = maxpos.x;
if (maxpos.y > max.y)
max.y = maxpos.y;
}
min -= mPos;
max -= mPos;
}
CharacterObject::CharacterObject(Character* chrclass, int state, bool mirror, Vec2i pos, const std::string& name)
: Object2D(state, pos, Vec2i(0,0), name), mMirror(mirror), mTextColor(),
mFontID(0), mLinkObject(NULL), mNoZooming(false), mFrozenScale(1.0f), mIdleTime(0),
mWalkSound(NULL), mClass(chrclass), mWalking(false), mTalking(false), mRealized(false)
{
TR_USE(ADV_Character);
mInventory = new Inventory();
mIdleTimeout = (int(rand()/(float)RAND_MAX*10)+10)*1000;
mLookDir = (LookDir)((mState-1)%3);
switch(state){
case 1:
mLookDir = FRONT;
break;
case 2:
mLookDir = BACK;
break;
case 3:
if (mMirror)
mLookDir = LEFT;
else
mLookDir = RIGHT;
break;
default:
TR_BREAK("Unexpected state: %i", mState);
}
}
CharacterObject::~CharacterObject(){
Engine::instance()->getFontRenderer()->removeText(this, true);
SoundEngine::instance()->removeSpeaker(this);
if (mWalkSound)
SoundEngine::instance()->removeSoundPlayer(mWalkSound);
delete mInventory;
}
void CharacterObject::realize(){
mInventory->realize(); //has its own check if realization is necessary
if (mRealized){
if (mScript)
mScript->cancelFinish();
return;
}
Object2D::realize();
if (mWalkSound)
mWalkSound->realize();
Engine::instance()->getFontRenderer()->loadFont(mFontID);
mRealized = true;
}
void CharacterObject::setPosition(const Vec2i& pos){
Vec2i offset;
if (mState != 0)
offset = mBasePoints[mState-1];
Object2D::setPosition(pos-offset);
RoomObject* room = Engine::instance()->getRoom(mRoom);
if (room){
float scale = room->getDepthScale(pos);
setScale(scale);
}
}
Vec2i CharacterObject::getPosition(){
if (mState < 1 || mState >= (int)mAnimations.size())
return Vec2i();
return mPos+mBasePoints[mState-1];
}
void CharacterObject::setDepth(int depth){
for (unsigned i = 0; i < mAnimations.size(); ++i){
mAnimations[i]->setDepth(depth);
}
}
void CharacterObject::animationBegin(const Vec2i& next){
Vec2i dir = next-getPosition();
setLookDir(dir);
setWalking(true);
if (mWalkSound)
mWalkSound->play(true);
}
void CharacterObject::animationWaypoint(const Vec2i& prev, const Vec2i& next){
int ycoord = getPosition().y;
if (prev.y-ycoord != 0){
setDepth((int)(ycoord/Engine::instance()->getWalkGridSize(true)));
}
Vec2i dir = next-getPosition();
setLookDir(dir);
//trigger walkmap scripts
RoomObject* room = Engine::instance()->getRoom(mRoom);
if (room){
Vec2f pos = ((Vec2f)getPosition())/room->getWalkGridSize();
room->walkTo(this, (Vec2i)pos);
}
}
void CharacterObject::animationEnd(const Vec2i& prev, bool aborted){
int ycoord = getPosition().y;
if (prev.y-ycoord != 0){
setDepth((int)(ycoord/Engine::instance()->getWalkGridSize(true)));
}
if (mDesiredDir != UNSPECIFIED){
setLookDir(mDesiredDir);
mDesiredDir = UNSPECIFIED;
}
setWalking(false);
Object2D::animationEnd(prev, aborted);
if (mWalkSound){
mWalkSound->stop();
mWalkSound->seek(0);
}
//trigger walkmap scripts
RoomObject* room = Engine::instance()->getRoom(mRoom);
if (room){
Vec2f pos = ((Vec2f)getPosition())/room->getWalkGridSize();
room->walkTo(this, (Vec2i)pos);
}
}
int CharacterObject::calculateState(LookDir dir, bool& mirror){
int state = 0;
if (dir == FRONT){
state = 1;
mirror = false;
}
else if (dir == BACK){
state = 2;
mirror = false;
}
else if (dir == LEFT){
state = 3;
mirror = true;
}
else if (dir == RIGHT){
state = 3;
mirror = false;
}
return state;
}
void CharacterObject::setLookDir(LookDir dir){
mLookDir = dir;
updateState(false, false);
}
void CharacterObject::setLookDir(const Vec2i& dir){
if (abs(dir.x) >= abs(dir.y) && dir.x >= 0){
setLookDir(RIGHT);
}
else if (abs(dir.x) >= abs(dir.y) && dir.x <= 0){
setLookDir(LEFT);
}
else if (abs(dir.x) <= abs(dir.y) && dir.y <= 0){
setLookDir(BACK);
}
else if (abs(dir.x) <= abs(dir.y) && dir.y >= 0){
setLookDir(FRONT);
}
}
LookDir CharacterObject::getLookDir(){
return mLookDir;
}
void CharacterObject::render(bool mirrorY){
if (mState <= 0 || (unsigned)mState > mAnimations.size())
return;
Vec2f scale(getScaleFactor(), getScaleFactor());
if (mMirror)
scale.x *= -1;
if (mirrorY)
scale.y *= -1;
Vec2i renderPos = mPos + mBasePoints[mState-1]-mBasePoints[mState-1]*getScaleFactor();
if (mMirror)
renderPos.x += (int)((-mSizes[mState-1].x+2*mBasePoints[mState-1].x)*getScaleFactor());
if (mirrorY)
renderPos.y += (int)(mBasePoints[mState-1].y*getScaleFactor()-2);
mAnimations[mState-1]->render(mScrollOffset+renderPos, scale, mSizes[mState-1], mLightingColor, mRotAngle);
}
Vec2i CharacterObject::getOverheadPos(){
return mPos+mScrollOffset+Vec2i(mSizes[mState-1].x/2, (int)((1-getScaleFactor())*mSizes[mState-1].y));
}
void CharacterObject::updateState(bool mirror, bool force){
if (mState > 12 && !force)
return;
int state = calculateState(mLookDir, mMirror);
state = calculateState(state, mWalking, mTalking, mirror);
setState(state);
}
int CharacterObject::calculateState(int currState, bool shouldWalk, bool shouldTalk, bool mirror){
int stateoffset = 0;
if (currState <= 12) //take offset only from 'normal' states
stateoffset = (currState-1)%3;
else
return currState;
//TODO handle real left anims and special states like pickup
if (mirror){
//swap looking front and back
if (stateoffset == 0)
stateoffset = 1;
else if (stateoffset == 1)
stateoffset = 0;
}
if (shouldWalk && shouldTalk){
return stateoffset+10;
}
if (shouldWalk && !shouldTalk){
return stateoffset+4;
}
if (!shouldWalk && shouldTalk){
return stateoffset+7;
}
if (!shouldWalk && !shouldTalk){
return stateoffset+1;
}
return stateoffset;
}
bool CharacterObject::isWalking(){
//return (mState >= 4 && mState <= 6) || (mState >= 10 && mState <= 12);
return mWalking;
}
bool CharacterObject::isTalking(){
//return (mState >= 7 && mState <= 12);
return mTalking;
}
Vec2i CharacterObject::getSize(){
return mSizes[mState-1]*mScale*mUserScale;
}
void CharacterObject::save(SaveStateProvider::SaveRoom* containingRoom){
SaveStateProvider::CharSaveObject* save = Engine::instance()->getSaver()->getOrAddCharacter(containingRoom, mName);
if (save){
save->base.position = mPos;
/*if (isWalking() || isTalking()) //do not save walking or talking states as they are temorary only
save->base.state = calculateState(mState, false, false, false);
else if (mState > 12)
save->base.state = 1; //no special states
else
save->base.state = mState;*/
save->base.state = calculateState(mLookDir, save->mirrored);
save->base.name = mName;
//save->mirrored = mMirror;
save->inventory.items.clear();
if (mInventory){
mInventory->save(save->inventory);
}
save->fontid = mFontID;
save->scale = mUserScale;
save->nozooming = mNoZooming;
if (mWalkSound == NULL)
save->walksound = "";
else
save->walksound = mWalkSound->getName();
if (mLinkObject == NULL)
save->linkedObject = "";
else
save->linkedObject = mLinkObject->getName();
}
}
bool CharacterObject::isHit(const Vec2i& point){
if (mScript == NULL || mState == 0)
return false;
//Vec2i scaleoffset;
//scaleoffset.x = (int)((1.0f-abs(mScale))*(getSize().x-getSize().x*abs(mScale)));
//scaleoffset.y = (int)(getSize().y-getSize().y*mScale);
Vec2i startPos = mPos+mBasePoints[mState-1]-mBasePoints[mState-1]*getScaleFactor();
if (point.x >= startPos.x/*+scaleoffset.x*/ && point.x <= startPos.x+/*scaleoffset.x*/+getSize().x){
if (point.y >= startPos.y/*+scaleoffset.y*/ && point.y <= startPos.y+/*scaleoffset.y*/+getSize().y)
return true;
}
return false;
}
void CharacterObject::setState(int state){
TR_USE(ADV_Character);
Vec2i oldoffset;
int oldstate = mState;
if (mState > 0){
oldoffset = mBasePoints[mState-1];
}
mState = state;
//mNextStates.clear();
//fallback to lower states when they not exist (walk,talk back => walk back)
if (!getAnimation()->exists()){
if (mState > 3)
mState = calculateState(mState, isWalking(), false, false);
if (!getAnimation()->exists())
mState = oldstate;
}
Vec2i newoffset;
if (mState > 0){
newoffset = mBasePoints[mState-1];
}
Object2D::setPosition(mPos+oldoffset-newoffset);
mIdleTime = 0; //reset idle timer
TR_DEBUG("%s state %i", mClass->name.c_str(), mState);
}
void CharacterObject::update(unsigned interval){
Object2D::update(interval);
if (mLinkObject != NULL){
Vec2i pos = mLinkObject->getPosition()+mLinkObject->getSize()/2;
setPosition(pos-mLinkOffset);
}
else{
mIdleTime += interval;
//trigger idle animation
if (mIdleTime >= mIdleTimeout && mNextStates.empty()){
//int oldstate = getState();
float rnd = rand()/(float)RAND_MAX;
int nextbored = (int)(rnd+0.5f);
if (!mAnimations[13-1+nextbored]->exists()){
nextbored = 1 - nextbored;
}
if (mAnimations[13-1+nextbored]->exists()){
setState(13+nextbored);
getAnimation()->registerAnimationEndHandler(this);
addNextState(0);
}
mIdleTime = 0;
mIdleTimeout = (int(rand()/(float)RAND_MAX*10)+10)*1000;
}
if (isWalking() || isTalking() || Engine::instance()->getInterpreter()->isBlockingScriptRunning()) //also not idle when taking or walking and no state change occurs
mIdleTime = 0;
}
}
float CharacterObject::getScaleFactor(){
if (mNoZooming)
return mFrozenScale*mUserScale;
return mScale*mUserScale;
}
void CharacterObject::setNoZooming(bool nozooming, bool force){
if (nozooming){
mNoZooming = nozooming;
mFrozenScale = mScale;
}
else{
if (force)
mNoZooming = nozooming;
else
Engine::instance()->getAnimator()->add(this, mFrozenScale, mScale, false);
}
}
void CharacterObject::setLinkObject(Object2D* link){
mLinkObject = link;
if (link){
mLinkOffset = mLinkObject->getPosition()+mLinkObject->getSize()/2-getPosition();
}
}
int CharacterObject::getDepth(){
return (int)(getPosition().y/Engine::instance()->getWalkGridSize(true));
}
void CharacterObject::setWalkSound(SoundPlayer* plyr){
if (mWalkSound != NULL)
SoundEngine::instance()->removeSoundPlayer(mWalkSound);
mWalkSound = plyr;
}
void CharacterObject::abortClick(){
if (mSuspensionScript != NULL){
if (!mSuspensionScript->getEvents().empty() && mSuspensionScript->getEvents().front() == EVT_CLICK){
mSuspensionScript->getEvents().pop_front();
Object2D::animationEnd(Vec2i(), false);
}
}
Engine::instance()->getAnimator()->remove(this);
}
/*bool CharacterObject::animationEnded(Animation* anim){
bool ret = Object2D::animationEnded(anim);
if (mState == 0){
updateState(false, false);
}
return ret;
}*/
void CharacterObject::activateNextState(){
if (mNextStates.empty())
return;
if (mNextStates.front() == 0)
updateState(false, true);
else{
setState(mNextStates.front());
if (mState > 0 && mAnimations[mState-1]->exists())
mAnimations[mState-1]->registerAnimationEndHandler(this);
}
mNextStates.pop_front();
}
float CharacterObject::getWalkGridSize(){
float walkgridsize;
RoomObject* room = Engine::instance()->getRoom(mRoom);
if (room)
walkgridsize = room->getWalkGridSize();
else{
SaveStateProvider::SaveRoom* sr = Engine::instance()->getSaver()->getRoom(mRoom);
walkgridsize = sr->getWalkGridSize();
}
return walkgridsize;
}
bool CharacterObject::isStandingAt(const Vec2i& pos){
if (mClass->ghost)
return false;
Room* room = Engine::instance()->getData()->getRoom(mRoom);
float gridsize = Engine::instance()->getWalkGridSize(room->doublewalkmap);
int myY = (int)(getPosition().y/gridsize);
if (!(myY == pos.y || (room->doublewalkmap && (myY == pos.y - 1 || myY == pos.y + 1))))
return false;
float posx = mPos.x+mBasePoints[mState-1].x-mBasePoints[mState-1].x*getScaleFactor();
int myX = (int)(posx/gridsize);
int range = (int)(getSize().x/gridsize)+1;
if (pos.x >= myX && pos.x <= myX+range)
return true;
return false;
}
| captain-mayhem/captainsengine | Adventure/AdvEngine/Engine/EngineObjects.cpp | C++ | lgpl-2.1 | 42,521 |
function extension_runAudits(callback)
{
evaluateOnFrontend("InspectorTest.startExtensionAudits(reply);", callback);
}
// runs in front-end
var initialize_ExtensionsAuditsTest = function()
{
InspectorTest.startExtensionAudits = function(callback)
{
const launcherView = WebInspector.panels.audits._launcherView;
launcherView._selectAllClicked(false);
launcherView._auditPresentStateElement.checked = true;
var extensionCategories = document.evaluate("label[starts-with(.,'Extension ')]/input[@type='checkbox']",
WebInspector.panels.audits._launcherView._categoriesElement, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0; i < extensionCategories.snapshotLength; ++i)
extensionCategories.snapshotItem(i).click();
function onAuditsDone()
{
InspectorTest.runAfterPendingDispatches(function() {
InspectorTest.collectAuditResults();
callback();
});
}
InspectorTest.addSniffer(WebInspector.panels.audits, "_auditFinishedCallback", onAuditsDone, true);
launcherView._launchButtonClicked();
}
}
| youfoh/webkit-efl | LayoutTests/inspector/extensions/extensions-audits-tests.js | JavaScript | lgpl-2.1 | 1,188 |
/*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* info@exist-db.org
* http://www.exist-db.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.indexing.lucene;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.*;
import org.apache.lucene.facet.DrillDownQuery;
import org.apache.lucene.facet.Facets;
import org.apache.lucene.facet.FacetsCollector;
import org.apache.lucene.facet.FacetsConfig;
import org.apache.lucene.facet.taxonomy.FastTaxonomyFacetCounts;
import org.apache.lucene.facet.taxonomy.SearcherTaxonomyManager;
import org.apache.lucene.facet.taxonomy.directory.DirectoryTaxonomyReader;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.*;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.NumericUtils;
import org.exist.collections.Collection;
import org.exist.dom.QName;
import org.exist.dom.memtree.MemTreeBuilder;
import org.exist.dom.memtree.NodeImpl;
import org.exist.dom.persistent.*;
import org.exist.indexing.*;
import org.exist.indexing.StreamListener.ReindexMode;
import org.exist.indexing.lucene.PlainTextHighlighter.Offset;
import org.exist.indexing.lucene.PlainTextIndexConfig.PlainTextField;
import org.exist.numbering.NodeId;
import org.exist.security.PermissionDeniedException;
import org.exist.storage.*;
import org.exist.storage.btree.DBException;
import org.exist.storage.lock.Lock.LockMode;
import org.exist.storage.txn.Txn;
import org.exist.util.ByteConversion;
import org.exist.util.DatabaseConfigurationException;
import org.exist.util.LockException;
import org.exist.util.Occurrences;
import org.exist.util.pool.NodePool;
import org.exist.xmldb.XmldbURI;
import org.exist.xquery.*;
import org.exist.xquery.modules.lucene.QueryOptions;
import org.exist.xquery.value.*;
import org.w3c.dom.*;
import org.xml.sax.helpers.AttributesImpl;
import javax.annotation.Nullable;
import javax.xml.XMLConstants;
import java.io.IOException;
import java.util.*;
/**
* Class for handling all Lucene operations.
*
* @author <a href="mailto:wolfgang@exist-db.org">Wolfgang Meier</a>
* @author <a href="mailto:dannes@exist-db.org">Dannes Wessels</a>
* @author <a href="mailto:ljo@exist-db.org">Leif-Jöran Olsson</a>
*/
public class LuceneIndexWorker implements OrderedValuesIndex, QNamedKeysIndex {
public static final org.apache.lucene.document.FieldType TYPE_NODE_ID = new org.apache.lucene.document.FieldType();
static {
TYPE_NODE_ID.setIndexed(true);
TYPE_NODE_ID.setStored(false);
TYPE_NODE_ID.setOmitNorms(true);
TYPE_NODE_ID.setStoreTermVectors(false);
TYPE_NODE_ID.setTokenized(true);
}
static final Logger LOG = LogManager.getLogger(LuceneIndexWorker.class);
protected LuceneIndex index;
private LuceneMatchListener matchListener = null;
private XMLToQuery queryTranslator;
private DBBroker broker;
private DocumentImpl currentDoc = null;
private ReindexMode mode = ReindexMode.STORE;
private LuceneConfig config;
private Deque<TextExtractor> contentStack = null;
private Set<NodeId> nodesToRemove = null;
private List<PendingDoc> nodesToWrite = null;
private Document pendingDoc = null;
private boolean canFlush = false;
private int cachedNodesSize = 0;
private int maxCachedNodesSize = 4096 * 1024;
private Analyzer analyzer;
public static final String FIELD_DOC_ID = "docId";
public static final String FIELD_DOC_URI = "docUri";
private final StreamListener listener = new LuceneStreamListener();
public LuceneIndexWorker(LuceneIndex parent, DBBroker broker) {
this.index = parent;
this.broker = broker;
this.queryTranslator = new XMLToQuery(index);
}
public String getIndexId() {
return LuceneIndex.ID;
}
public String getIndexName() {
return index.getIndexName();
}
public QueryRewriter getQueryRewriter(XQueryContext context) {
return null;
}
public Object configure(IndexController controller, NodeList configNodes, Map<String, String> namespaces) throws DatabaseConfigurationException {
LOG.debug("Configuring lucene index...");
config = new LuceneConfig(configNodes, namespaces);
return config;
}
public void flush() {
switch (mode) {
case STORE:
write();
break;
case REMOVE_ALL_NODES:
removeDocument(currentDoc.getDocId());
break;
case REMOVE_SOME_NODES:
removeNodes();
break;
case REMOVE_BINARY:
removePlainTextIndexes();
break;
}
}
@Override
public void setDocument(DocumentImpl document) {
setDocument(document, ReindexMode.UNKNOWN);
}
@Override
public void setDocument(DocumentImpl document, ReindexMode newMode) {
currentDoc = document;
//config = null;
contentStack = null;
IndexSpec indexConf = document.getCollection().getIndexConfiguration(broker);
if (indexConf != null) {
config = (LuceneConfig) indexConf.getCustomIndexSpec(LuceneIndex.ID);
if (config != null)
// Create a copy of the original LuceneConfig (there's only one per db instance),
// so we can safely work with it.
config = new LuceneConfig(config);
} else {
config = LuceneConfig.DEFAULT_CONFIG;
}
mode = newMode;
}
@Override
public void setMode(ReindexMode mode) {
this.mode = mode;
switch (mode) {
case STORE:
if (nodesToWrite == null)
nodesToWrite = new ArrayList<>();
else
nodesToWrite.clear();
cachedNodesSize = 0;
break;
case REMOVE_SOME_NODES:
nodesToRemove = new TreeSet<>();
break;
}
}
@Override
public DocumentImpl getDocument() {
return currentDoc;
}
@Override
public ReindexMode getMode() {
return this.mode;
}
@Override
public <T extends IStoredNode> IStoredNode getReindexRoot(IStoredNode<T> node, NodePath path, boolean insert, boolean includeSelf) {
if (config == null) {
return null;
}
if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
// check if sibling attributes or parent element need reindexing
IStoredNode parentStoredNode = node.getParentStoredNode();
Iterator<LuceneIndexConfig> configIt = config.getConfig(parentStoredNode.getPath());
while (configIt.hasNext()) {
LuceneIndexConfig idxConfig = configIt.next();
if (idxConfig.shouldReindexOnAttributeChange() && idxConfig.match(path)) {
// reindex from attribute parent
return parentStoredNode;
}
}
NamedNodeMap attributes = parentStoredNode.getAttributes();
for (int i = 0; i < attributes.getLength(); ++i) {
IStoredNode<?> attr = (IStoredNode<?>) attributes.item(i);
if (attr.getPrefix() != null && XMLConstants.XMLNS_ATTRIBUTE.equals(attr.getPrefix())) {
continue;
}
configIt = config.getConfig(attr.getPath());
while (configIt.hasNext()) {
LuceneIndexConfig idxConfig = configIt.next();
if (idxConfig.shouldReindexOnAttributeChange() && idxConfig.match(path)) {
// reindex from attribute parent
return parentStoredNode;
}
}
}
// found no reason to reindex
return null;
}
NodePath2 p = new NodePath2((NodePath2)path);
boolean reindexRequired = false;
if (node.getNodeType() == Node.ELEMENT_NODE && !includeSelf)
p.removeLastNode();
for (int i = 0; i < p.length(); i++) {
if (config.matches(p)) {
reindexRequired = true;
break;
}
p.removeLastNode();
}
if (reindexRequired) {
p = new NodePath2((NodePath2)path);
IStoredNode topMost = null;
IStoredNode currentNode = node;
if (currentNode.getNodeType() != Node.ELEMENT_NODE)
currentNode = currentNode.getParentStoredNode();
while (currentNode != null) {
if (config.matches(p))
topMost = currentNode;
currentNode = currentNode.getParentStoredNode();
p.removeLastNode();
}
return topMost;
}
return null;
}
@Override
public StreamListener getListener() {
return listener;
}
@Override
public MatchListener getMatchListener(DBBroker broker, NodeProxy proxy) {
boolean needToFilter = false;
Match nextMatch = proxy.getMatches();
while (nextMatch != null) {
if (nextMatch.getIndexId().equals(LuceneIndex.ID)) {
needToFilter = true;
break;
}
nextMatch = nextMatch.getNextMatch();
}
if (!needToFilter)
return null;
if (matchListener == null)
matchListener = new LuceneMatchListener(index, broker, proxy);
else
matchListener.reset(broker, proxy);
return matchListener;
}
protected void removeDocument(int docId) {
IndexWriter writer = null;
try {
writer = index.getWriter();
final BytesRefBuilder bytes = new BytesRefBuilder();
NumericUtils.intToPrefixCoded(docId, 0, bytes);
Term dt = new Term(FIELD_DOC_ID, bytes.toBytesRef());
writer.deleteDocuments(dt);
} catch (IOException e) {
LOG.warn("Error while removing lucene index: " + e.getMessage(), e);
} finally {
index.releaseWriter(writer);
mode = ReindexMode.STORE;
}
}
protected void removePlainTextIndexes() {
IndexWriter writer = null;
try {
writer = index.getWriter();
String uri = currentDoc.getURI().toString();
Term dt = new Term(FIELD_DOC_URI, uri);
writer.deleteDocuments(dt);
} catch (IOException e) {
LOG.warn("Error while removing lucene index: " + e.getMessage(), e);
} finally {
index.releaseWriter(writer);
mode = ReindexMode.STORE;
}
}
@Override
public void removeCollection(Collection collection, DBBroker broker, boolean reindex) {
if (LOG.isDebugEnabled())
LOG.debug("Removing collection " + collection.getURI());
IndexWriter writer = null;
try {
writer = index.getWriter();
for (Iterator<DocumentImpl> i = collection.iterator(broker); i.hasNext(); ) {
DocumentImpl doc = i.next();
final BytesRefBuilder bytes = new BytesRefBuilder();
NumericUtils.intToPrefixCoded(doc.getDocId(), 0, bytes);
Term dt = new Term(FIELD_DOC_ID, bytes.toBytesRef());
writer.deleteDocuments(dt);
}
} catch (IOException | PermissionDeniedException | LockException e) {
LOG.error("Error while removing lucene index: " + e.getMessage(), e);
} finally {
index.releaseWriter(writer);
if (reindex) {
try {
index.sync();
} catch (DBException e) {
LOG.warn("Exception during reindex: " + e.getMessage(), e);
}
}
mode = ReindexMode.STORE;
}
if (LOG.isDebugEnabled())
LOG.debug("Collection removed.");
}
/**
* Remove specific nodes from the index. This method is used for node updates
* and called from flush() if the worker is in {@link ReindexMode#REMOVE_SOME_NODES}
* mode.
*/
protected void removeNodes() {
if (nodesToRemove == null)
return;
IndexWriter writer = null;
try {
writer = index.getWriter();
final BytesRefBuilder bytes = new BytesRefBuilder();
NumericUtils.intToPrefixCoded(currentDoc.getDocId(), 0, bytes);
Term dt = new Term(FIELD_DOC_ID, bytes.toBytesRef());
TermQuery tq = new TermQuery(dt);
for (NodeId nodeId : nodesToRemove) {
// store the node id
int nodeIdLen = nodeId.size();
byte[] data = new byte[nodeIdLen + 2];
ByteConversion.shortToByte((short) nodeId.units(), data, 0);
nodeId.serialize(data, 2);
Term it = new Term(LuceneUtil.FIELD_NODE_ID, new BytesRef(data));
TermQuery iq = new TermQuery(it);
BooleanQuery q = new BooleanQuery();
q.add(tq, BooleanClause.Occur.MUST);
q.add(iq, BooleanClause.Occur.MUST);
writer.deleteDocuments(q);
}
} catch (IOException e) {
LOG.warn("Error while deleting lucene index entries: " + e.getMessage(), e);
} finally {
index.releaseWriter(writer);
nodesToRemove = null;
}
}
/**
* Query the index. Returns a node set containing all matching nodes. Each node
* in the node set has a {@link LuceneMatch}
* element attached, which stores the score and a link to the query which generated it.
*
* @param contextId current context id, identify to track the position inside nested XPath predicates
* @param docs query will be restricted to documents in this set
* @param contextSet if specified, returned nodes will be descendants of the nodes in this set
* @param qnames query will be restricted to nodes with the qualified names given here
* @param queryStr a lucene query string
* @param axis which node is returned: the node in which a match was found or the corresponding ancestor
* from the contextSet
* @param options the query options
*
* @return node set containing all matching nodes
*
* @throws IOException if an I/O error occurs
* @throws ParseException if the query cannot be parsed
* @throws XPathException if an error occurs executing the query
*/
public NodeSet query(int contextId, DocumentSet docs, NodeSet contextSet,
List<QName> qnames, String queryStr, int axis, QueryOptions options)
throws IOException, ParseException, XPathException {
return index.withSearcher(searcher -> {
final List<QName> definedIndexes = getDefinedIndexes(qnames);
final NodeSet resultSet = new NewArrayNodeSet();
final boolean returnAncestor = axis == NodeSet.ANCESTOR;
for (QName qname : definedIndexes) {
String field = LuceneUtil.encodeQName(qname, index.getBrokerPool().getSymbols());
LuceneConfig config = getLuceneConfig(broker, docs);
Analyzer analyzer = getQueryAnalyzer(config,null, qname, options);
Query query;
if (queryStr == null) {
query = new ConstantScoreQuery(new FieldValueFilter(field));
} else {
QueryParserWrapper parser = getQueryParser(field, analyzer, docs);
options.configureParser(parser.getConfiguration());
query = parser.parse(queryStr);
}
Optional<Map<String, QueryOptions.FacetQuery>> facets = options.getFacets();
if (facets.isPresent() && config != null) {
query = drilldown(facets.get(), query, config);
}
searchAndProcess(contextId, qname, docs, contextSet, resultSet,
returnAncestor, searcher, query, options.getFields(), config);
}
return resultSet;
});
}
/**
* Query the index. Returns a node set containing all matching nodes. Each node
* in the node set has a {@link LuceneMatch}
* element attached, which stores the score and a link to the query which generated it.
*
* @param contextId current context id, identify to track the position inside nested XPath predicates
* @param docs query will be restricted to documents in this set
* @param contextSet if specified, returned nodes will be descendants of the nodes in this set
* @param qnames query will be restricted to nodes with the qualified names given here
* @param queryRoot an XML representation of the query, see {@link XMLToQuery}.
* @param axis which node is returned: the node in which a match was found or the corresponding ancestor
* from the contextSet
* @param options the query options
*
* @return node set containing all matching nodes
*
* @throws IOException if an I/O error occurs
* @throws ParseException if the query cannot be parsed
* @throws XPathException if an error occurs executing the query
*/
public NodeSet query(int contextId, DocumentSet docs, NodeSet contextSet,
List<QName> qnames, Element queryRoot, int axis, QueryOptions options)
throws IOException, ParseException, XPathException {
return index.withSearcher(searcher -> {
final List<QName> definedIndexes = getDefinedIndexes(qnames);
final NodeSet resultSet = new NewArrayNodeSet();
final boolean returnAncestor = axis == NodeSet.ANCESTOR;
for (QName qname : definedIndexes) {
String field = LuceneUtil.encodeQName(qname, index.getBrokerPool().getSymbols());
LuceneConfig config = getLuceneConfig(broker, docs);
analyzer = getQueryAnalyzer(config, null, qname, options);
Query query = queryRoot == null ? new ConstantScoreQuery(new FieldValueFilter(field)) : queryTranslator.parse(field, queryRoot, analyzer, options);
Optional<Map<String, QueryOptions.FacetQuery>> facets = options.getFacets();
if (facets.isPresent() && config != null) {
query = drilldown(facets.get(), query, config);
}
if (query != null) {
searchAndProcess(contextId, qname, docs, contextSet, resultSet,
returnAncestor, searcher, query, options.getFields(), config);
}
}
return resultSet;
});
}
public NodeSet queryField(int contextId, DocumentSet docs, NodeSet contextSet,
String field, Element queryRoot, int axis, QueryOptions options)
throws IOException, XPathException {
return index.withSearcher(searcher -> {
final NodeSet resultSet = new NewArrayNodeSet();
final boolean returnAncestor = axis == NodeSet.ANCESTOR;
final LuceneConfig config = getLuceneConfig(broker, docs);
analyzer = getQueryAnalyzer(config, field, null, options);
final Query query = queryTranslator.parse(field, queryRoot, analyzer, options);
if (query != null) {
searchAndProcess(contextId, null, docs, contextSet, resultSet,
returnAncestor, searcher, query, null, config);
}
return resultSet;
});
}
private Query drilldown(Map<String, QueryOptions.FacetQuery> facets, Query baseQuery, LuceneConfig config) {
final DrillDownQuery drillDownQuery = new DrillDownQuery(config.facetsConfig, baseQuery);
for (final Map.Entry<String, QueryOptions.FacetQuery> facet : facets.entrySet()) {
final FacetsConfig.DimConfig dimConfig = config.facetsConfig.getDimConfig(facet.getKey());
facet.getValue().toQuery(facet.getKey(), drillDownQuery, dimConfig.hierarchical);
}
return drillDownQuery;
}
private void searchAndProcess(int contextId, QName qname, DocumentSet docs,
NodeSet contextSet, NodeSet resultSet, boolean returnAncestor,
SearcherTaxonomyManager.SearcherAndTaxonomy searcher, Query query,
@Nullable Set<String> fields, LuceneConfig config) throws IOException {
final LuceneFacets facets = new LuceneFacets();
final FacetsCollector facetsCollector = new FacetsCollector();
final LuceneHitCollector collector = new LuceneHitCollector(qname, query, docs, contextSet, resultSet, returnAncestor, contextId, facets, facetsCollector, fields);
searcher.searcher.search(query, collector);
// compute facets
facets.compute(searcher.taxonomyReader, config.facetsConfig, facetsCollector);
}
/**
* Wrapper around Lucene {@link Facets}, which are computed after the search has finished.
*/
protected static class LuceneFacets {
private Facets facets;
public Facets getFacets() {
return facets;
}
/**
* Compute facets based on the given {@link FacetsCollector}.
*
* @param reader the taxonomy reader
* @param config the facets configuration
* @param collector the facets collector
*
* @throws IOException if an I/O error occurs
*/
public void compute(DirectoryTaxonomyReader reader, FacetsConfig config, FacetsCollector collector)
throws IOException {
this.facets = new FastTaxonomyFacetCounts(reader, config, collector);
}
}
/**
* Calls {@link LuceneUtil#extractTerms(Query, Map, IndexReader, boolean)} to extract
* the terms which would be matched by the given query.
*
* @param query to extract terms for
* @return the map returned by {@link LuceneUtil#extractTerms(Query, Map, IndexReader, boolean)}
* @throws IOException in case of Lucene IO error
*/
public Map<Object, Query> getTerms(final Query query) throws IOException {
return index.withReader(reader -> {
final Map<Object, Query> termMap = new TreeMap<>();
LuceneUtil.extractTerms(query, termMap, reader, false);
return termMap;
});
}
public NodeSet queryField(XQueryContext context, int contextId, DocumentSet docs, NodeSet contextSet,
String field, String queryString, int axis, QueryOptions options)
throws IOException, XPathException {
return index.withSearcher(searcher -> {
NodeSet resultSet = new NewArrayNodeSet();
boolean returnAncestor = axis == NodeSet.ANCESTOR;
LuceneConfig config = getLuceneConfig(context.getBroker(), docs);
Analyzer analyzer = getQueryAnalyzer(config, field, null, options);
LOG.debug("Using analyzer " + analyzer + " for " + queryString);
QueryParserWrapper parser = getQueryParser(field, analyzer, docs);
options.configureParser(parser.getConfiguration());
Query query = parser.parse(queryString);
searchAndProcess(contextId, null, docs, contextSet, resultSet,
returnAncestor, searcher, query, null, config);
return resultSet;
});
}
/**
* Add SOLR formatted data to lucene index.
*
* <pre>
* {@code
* <doc>
* <field name="name1" boost="value1">data1</field>
* <field name="name2">data2</field>
* </doc>
* }
* </pre>
*
* @param descriptor SOLR styled data
*/
public void indexNonXML(NodeValue descriptor) {
// Verify input
if (!descriptor.getNode().getLocalName().contentEquals("doc")) {
// throw exception
LOG.error("Expected <doc> got <" + descriptor.getNode().getLocalName() + ">");
return;
}
// Setup parser for SOLR syntax and parse
PlainTextIndexConfig solrconfParser = new PlainTextIndexConfig();
solrconfParser.parse(descriptor);
if (pendingDoc == null) {
// create Lucene document
pendingDoc = new Document();
// Set DocId
NumericDocValuesField fDocId = new NumericDocValuesField(FIELD_DOC_ID, currentDoc.getDocId());
pendingDoc.add(fDocId);
IntField fDocIdIdx = new IntField(FIELD_DOC_ID, currentDoc.getDocId(), Field.Store.NO);
pendingDoc.add(fDocIdIdx);
// For binary documents the doc path needs to be stored
String uri = currentDoc.getURI().toString();
Field fDocUri = new Field(FIELD_DOC_URI, uri, Field.Store.YES, Field.Index.NOT_ANALYZED);
pendingDoc.add(fDocUri);
}
// Iterate over all found fields and write the data.
for (PlainTextField field : solrconfParser.getFields()) {
// Get field type configuration
FieldType fieldType = config == null ? null : config.getFieldType(field.getName());
Field.Store store = null;
if (fieldType != null)
store = fieldType.getStore();
if (store == null)
store = field.getStore();
// Get name from SOLR field
String contentFieldName = field.getName();
// Actual field content ; Store flag can be set in solrField
Field contentField = new Field(contentFieldName, field.getData().toString(), store, Field.Index.ANALYZED, Field.TermVector.YES);
// Extract (document) Boost factor
if (field.getBoost() > 0) {
contentField.setBoost(field.getBoost());
}
pendingDoc.add(contentField);
}
}
public void writeNonXML() {
IndexWriter writer = null;
try {
writer = index.getWriter();
writer.addDocument(pendingDoc);
} catch (IOException e) {
LOG.warn("An exception was caught while indexing document: " + e.getMessage(), e);
} finally {
index.releaseWriter(writer);
pendingDoc = null;
cachedNodesSize = 0;
}
}
/**
* SOLR
*
* @param context the xquery context
* @param toBeMatchedURIs the URIs to match
* @param queryText the query
* @param fieldsToGet the fields to get
* @param options the search options
*
* @return search report
*
* @throws XPathException if an error occurs executing the query
* @throws IOException if an I/O error occurs
*/
public NodeImpl search(final XQueryContext context, final List<String> toBeMatchedURIs, String queryText, String[] fieldsToGet, QueryOptions options) throws XPathException, IOException {
return index.withSearcher(searcher -> {
// Get analyzer : to be retrieved from configuration
final Analyzer searchAnalyzer = new StandardAnalyzer(LuceneIndex.LUCENE_VERSION_IN_USE);
// Setup query Version, default field, analyzer
final QueryParserWrapper parser = getQueryParser("", searchAnalyzer, null);
options.configureParser(parser.getConfiguration());
final Query query = parser.parse(queryText);
// extract all used fields from query
final String[] fields;
if (fieldsToGet == null) {
fields = LuceneUtil.extractFields(query, searcher.searcher.getIndexReader());
} else {
fields = fieldsToGet;
}
final PlainTextHighlighter highlighter = new PlainTextHighlighter(query, searcher.searcher.getIndexReader());
context.pushDocumentContext();
try {
final MemTreeBuilder builder = context.getDocumentBuilder();
builder.startDocument();
// start root element
final int nodeNr = builder.startElement("", "results", "results", null);
// Perform actual search
final BinarySearchCollector collector = new BinarySearchCollector(toBeMatchedURIs, builder, fields, searchAnalyzer, highlighter);
searcher.searcher.search(query, collector);
// finish root element
builder.endElement();
//System.out.println(builder.getDocument().toString());
// TODO check
return builder.getDocument().getNode(nodeNr);
} finally {
context.popDocumentContext();
}
});
}
private class BinarySearchCollector extends Collector {
private final List<String> toBeMatchedURIs;
private final MemTreeBuilder builder;
private final String[] fields;
private final Analyzer searchAnalyzer;
private final PlainTextHighlighter highlighter;
private Scorer scorer;
private AtomicReader reader;
public BinarySearchCollector(List<String> toBeMatchedURIs, MemTreeBuilder builder, String[] fields, Analyzer searchAnalyzer, PlainTextHighlighter highlighter) {
this.toBeMatchedURIs = toBeMatchedURIs;
this.builder = builder;
this.fields = fields;
this.searchAnalyzer = searchAnalyzer;
this.highlighter = highlighter;
}
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = scorer;
}
@Override
public void collect(int docNum) throws IOException {
Document doc = reader.document(docNum);
// Get URI field of document
String fDocUri = doc.get(FIELD_DOC_URI);
// Get score
float score = scorer.score();
// Check if document URI has a full match or if a
// document is in a collection
if (isDocumentMatch(fDocUri, toBeMatchedURIs)) {
try(final LockedDocument lockedStoredDoc = broker.getXMLResource(XmldbURI.createInternal(fDocUri), LockMode.READ_LOCK)) {
// try to read document to check if user is allowed to access it
if (lockedStoredDoc == null) {
return;
}
// setup attributes
AttributesImpl attribs = new AttributesImpl();
attribs.addAttribute("", "uri", "uri", "CDATA", fDocUri);
attribs.addAttribute("", "score", "score", "CDATA", "" + score);
// write element and attributes
builder.startElement("", "search", "search", attribs);
for (String field : fields) {
String[] fieldContent = doc.getValues(field);
attribs.clear();
attribs.addAttribute("", "name", "name", "CDATA", field);
for (String content : fieldContent) {
List<Offset> offsets = highlighter.getOffsets(content, searchAnalyzer);
builder.startElement("", "field", "field", attribs);
if (offsets != null) {
highlighter.highlight(content, offsets, builder);
} else {
builder.characters(content);
}
builder.endElement();
}
}
builder.endElement();
// clean attributes
attribs.clear();
} catch (PermissionDeniedException e) {
// not allowed to read the document: ignore the match.
}
}
}
@Override
public void setNextReader(AtomicReaderContext atomicReaderContext) throws IOException {
this.reader = atomicReaderContext.reader();
}
@Override
public boolean acceptsDocsOutOfOrder() {
return true;
}
}
public String getFieldContent(int docId, String field) throws IOException {
final BytesRefBuilder bytes = new BytesRefBuilder();
NumericUtils.intToPrefixCoded(docId, 0, bytes);
Term dt = new Term(FIELD_DOC_ID, bytes.toBytesRef());
return index.withReader(reader -> {
List<AtomicReaderContext> leaves = reader.leaves();
for (AtomicReaderContext context : leaves) {
AtomicReader atomicReader = context.reader();
DocsEnum docs = atomicReader.termDocsEnum(dt);
if (docs != null && docs.nextDoc() != DocsEnum.NO_MORE_DOCS) {
Document doc = atomicReader.document(docs.docID());
String value = doc.get(field);
if (value != null) {
return value;
}
}
}
return null;
});
}
public boolean hasIndex(int docId) throws IOException {
final BytesRefBuilder bytes = new BytesRefBuilder();
NumericUtils.intToPrefixCoded(docId, 0, bytes);
Term dt = new Term(FIELD_DOC_ID, bytes.toBytesRef());
return index.withReader(reader -> {
boolean found = false;
List<AtomicReaderContext> leaves = reader.leaves();
for (AtomicReaderContext context : leaves) {
DocsEnum docs = context.reader().termDocsEnum(dt);
if (docs != null && docs.nextDoc() != DocsEnum.NO_MORE_DOCS) {
found = true;
break;
}
}
return found;
});
}
/**
* Check if Lucene found document matches specified documents or collections.
* Collections should end with "/".
*
* @param docUri The uri of the document found by lucene
* @param toBeMatchedUris List of document and collection URIs
*
* @return true if {@code docUri} is matched or is in collection, false otherwise
*/
private boolean isDocumentMatch(String docUri, List<String> toBeMatchedUris){
if(docUri==null){
LOG.error("docUri is null.");
return false;
}
if(toBeMatchedUris==null){
LOG.error("match is null.");
return false;
}
for(String doc : toBeMatchedUris){
if( docUri.startsWith(doc) ){
return true;
}
}
return false;
}
private class LuceneHitCollector extends Collector {
private Scorer scorer;
private AtomicReader reader;
private NumericDocValues docIdValues;
private BinaryDocValues nodeIdValues;
private final QName qname;
private final DocumentSet docs;
private final NodeSet contextSet;
private final NodeSet resultSet;
private final boolean returnAncestor;
private final int contextId;
private final Query query;
private final LuceneFacets facets;
private final FacetsCollector chainedCollector;
private final Set<String> fields;
private LuceneHitCollector(QName qname, Query query, DocumentSet docs, NodeSet contextSet, NodeSet resultSet, boolean returnAncestor, int contextId, LuceneFacets facets, FacetsCollector nextCollector, @Nullable Set<String> fields) {
this.qname = qname;
this.docs = docs;
this.contextSet = contextSet;
this.resultSet = resultSet;
this.returnAncestor = returnAncestor;
this.contextId = contextId;
this.query = query;
this.facets = facets;
this.chainedCollector = nextCollector;
this.fields = fields;
}
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = scorer;
chainedCollector.setScorer(scorer);
}
@Override
public void setNextReader(AtomicReaderContext atomicReaderContext) throws IOException {
this.reader = atomicReaderContext.reader();
this.docIdValues = this.reader.getNumericDocValues(FIELD_DOC_ID);
this.nodeIdValues = this.reader.getBinaryDocValues(LuceneUtil.FIELD_NODE_ID);
chainedCollector.setNextReader(atomicReaderContext);
}
@Override
public boolean acceptsDocsOutOfOrder() {
return false;
}
@Override
public void collect(int doc) {
try {
float score = scorer.score();
int docId = (int) this.docIdValues.get(doc);
DocumentImpl storedDocument = docs.getDoc(docId);
if (storedDocument == null)
return;
final BytesRef ref = this.nodeIdValues.get(doc);
int units = ByteConversion.byteToShort(ref.bytes, ref.offset);
NodeId nodeId = index.getBrokerPool().getNodeFactory().createFromData(units, ref.bytes, ref.offset + 2);
//LOG.info("doc: " + docId + "; node: " + nodeId.toString() + "; units: " + units);
NodeProxy storedNode = new NodeProxy(storedDocument, nodeId);
if (qname != null)
storedNode.setNodeType(qname.getNameType() == ElementValue.ATTRIBUTE ? Node.ATTRIBUTE_NODE : Node.ELEMENT_NODE);
// if a context set is specified, we can directly check if the
// matching node is a descendant of one of the nodes
// in the context set.
if (contextSet != null) {
int sizeHint = contextSet.getSizeHint(storedDocument);
if (returnAncestor) {
NodeProxy parentNode = contextSet.get(storedNode);
// NodeProxy parentNode = contextSet.parentWithChild(storedNode, false, true, NodeProxy.UNKNOWN_NODE_LEVEL);
if (parentNode != null) {
LuceneMatch match = createMatch(doc, score, nodeId);
parentNode.addMatch(match);
resultSet.add(parentNode, sizeHint);
if (Expression.NO_CONTEXT_ID != contextId) {
parentNode.deepCopyContext(storedNode, contextId);
} else
parentNode.copyContext(storedNode);
chainedCollector.collect(doc);
}
} else {
LuceneMatch match = createMatch(doc, score, nodeId);
storedNode.addMatch(match);
resultSet.add(storedNode, sizeHint);
chainedCollector.collect(doc);
}
} else {
LuceneMatch match = createMatch(doc, score, nodeId);
storedNode.addMatch(match);
resultSet.add(storedNode);
chainedCollector.collect(doc);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private LuceneMatch createMatch(int docId, float score, NodeId nodeId) throws IOException {
final LuceneMatch match = new LuceneMatch(contextId, nodeId, query, facets);
match.setScore(score);
if (fields != null && !fields.isEmpty()) {
final Document luceneDoc = reader.document(docId, fields);
for (String field : fields) {
match.addField(field, luceneDoc.getFields(field));
}
}
return match;
}
}
/**
* Check index configurations for all collection in the given DocumentSet and return
* a list of QNames, which have indexes defined on them.
*
* @param qnames the qnames to find the findexes for
*
* @return List of QName objects on which indexes are defined
*
* @throws IOException if an I/O error occurs
*/
public List<QName> getDefinedIndexes(final List<QName> qnames) throws IOException {
final List<QName> indexes = new ArrayList<>(20);
if (qnames != null && !qnames.isEmpty()) {
for (final QName qname : qnames) {
if (qname.getLocalPart() == null || qname.getLocalPart().equals(QName.WILDCARD)
|| qname.getNamespaceURI() == null || qname.getNamespaceURI().equals(QName.WILDCARD)) {
getDefinedIndexesFor(qname, indexes);
} else {
indexes.add(qname);
}
}
return indexes;
}
return getDefinedIndexesFor(null, indexes);
}
private List<QName> getDefinedIndexesFor(QName qname, final List<QName> indexes) throws IOException {
return index.withReader(reader -> {
for (FieldInfo info: MultiFields.getMergedFieldInfos(reader)) {
if (!FIELD_DOC_ID.equals(info.name)) {
QName name = LuceneUtil.decodeQName(info.name, index.getBrokerPool().getSymbols());
if (name != null && (qname == null || matchQName(qname, name)))
indexes.add(name);
}
}
return indexes;
});
}
private static boolean matchQName(QName qname, QName candidate) {
boolean match = true;
if (qname.getLocalPart() != null && (!qname.getLocalPart().equals(QName.WILDCARD))) {
match = qname.getLocalPart().equals(candidate.getLocalPart());
}
if (match && qname.getNamespaceURI() != null && (!qname.getNamespaceURI().equals(QName.WILDCARD)) && !qname.getNamespaceURI().isEmpty()) {
match = qname.getNamespaceURI().equals(candidate.getNamespaceURI());
}
return match;
}
/**
* Return the analyzer to be used for the given field or qname. Either field
* or qname should be specified.
*
* @param config the lucene config
* @param field the analyzer field
* @param qname the analyzer qname
* @param opts the query options
*
* @return the analyzer or null
*/
@Nullable protected Analyzer getQueryAnalyzer(LuceneConfig config, String field, QName qname, QueryOptions opts) {
if (config != null) {
Analyzer analyzer;
if (opts.getQueryAnalyzerId() != null) {
analyzer = config.getAnalyzerById(opts.getQueryAnalyzerId());
if (analyzer == null) {
String msg = String.format("getAnalyzerById('%s') returned null!", opts.getQueryAnalyzerId());
LOG.error(msg);
}
}
else if (field == null) {
analyzer = config.getAnalyzer(qname);
} else {
analyzer = config.getAnalyzer(field);
}
if (analyzer != null) {
return analyzer;
}
}
return index.getDefaultAnalyzer();
}
/**
* Return the first configuration found for documents in the document set.
*
* @param broker the database broker
* @param docs the document set
*
* @return the lucene config or null
*/
public LuceneConfig getLuceneConfig(DBBroker broker, DocumentSet docs) {
for (Iterator<Collection> i = docs.getCollectionIterator(); i.hasNext(); ) {
Collection collection = i.next();
IndexSpec idxConf = collection.getIndexConfiguration(broker);
if (idxConf != null) {
LuceneConfig config = (LuceneConfig) idxConf.getCustomIndexSpec(LuceneIndex.ID);
if (config != null) {
return config;
}
}
}
return LuceneConfig.DEFAULT_CONFIG;
}
protected QueryParserWrapper getQueryParser(String field, Analyzer analyzer, DocumentSet docs) {
if (docs != null) {
for (Iterator<Collection> i = docs.getCollectionIterator(); i.hasNext(); ) {
Collection collection = i.next();
IndexSpec idxConf = collection.getIndexConfiguration(broker);
if (idxConf != null) {
LuceneConfig config = (LuceneConfig) idxConf.getCustomIndexSpec(LuceneIndex.ID);
if (config != null) {
QueryParserWrapper parser = config.getQueryParser(field, analyzer);
if (parser != null) {
return parser;
}
}
}
}
}
// not found. return default query parser:
return new ClassicQueryParserWrapper(field, analyzer);
}
public boolean checkIndex(DBBroker broker) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
public Occurrences[] scanIndex(XQueryContext context, DocumentSet docs, NodeSet nodes, Map<?,?> hints) {
try {
List<QName> qnames = hints == null ? null : (List<QName>)hints.get(QNAMES_KEY);
qnames = getDefinedIndexes(qnames);
//Expects a StringValue
String start = null;
String end = null;
long max = Long.MAX_VALUE;
if (hints != null) {
Object vstart = hints.get(START_VALUE);
Object vend = hints.get(END_VALUE);
start = vstart == null ? null : vstart.toString();
end = vend == null ? null : vend.toString();
IntegerValue vmax = (IntegerValue) hints.get(VALUE_COUNT);
max = vmax == null ? Long.MAX_VALUE : vmax.getValue();
}
return scanIndexByQName(qnames, docs, nodes, start, end, max);
} catch (IOException e) {
LOG.warn("Failed to scan index occurrences: " + e.getMessage(), e);
return new Occurrences[0];
}
}
public Occurrences[] scanIndexByField(String field, DocumentSet docs, Map<?,?> hints) {
try {
//Expects a StringValue
String start = null;
String end = null;
long max = Long.MAX_VALUE;
if (hints != null) {
Object vstart = hints.get(START_VALUE);
Object vend = hints.get(END_VALUE);
start = vstart == null ? null : vstart.toString();
end = vend == null ? null : vend.toString();
IntegerValue vmax = (IntegerValue) hints.get(VALUE_COUNT);
max = vmax == null ? Long.MAX_VALUE : vmax.getValue();
}
return scanIndexByField(field, docs, null, start, end, max);
} catch (IOException e) {
LOG.warn("Failed to scan index occurrences: " + e.getMessage(), e);
return new Occurrences[0];
}
}
private Occurrences[] scanIndexByQName(List<QName> qnames, DocumentSet docs, NodeSet nodes, String start, String end, long max) throws IOException {
final TreeMap<String, Occurrences> map = new TreeMap<>();
index.withReader(reader -> {
for (QName qname : qnames) {
String field = LuceneUtil.encodeQName(qname, index.getBrokerPool().getSymbols());
doScanIndex(docs, nodes, start, end, max, map, reader, field);
}
return null;
});
Occurrences[] occur = new Occurrences[map.size()];
return map.values().toArray(occur);
}
private Occurrences[] scanIndexByField(String field, DocumentSet docs, NodeSet nodes, String start, String end, long max) throws IOException {
final TreeMap<String, Occurrences> map = new TreeMap<>();
index.withReader(reader -> {
doScanIndex(docs, nodes, start, end, max, map, reader, field);
return null;
});
Occurrences[] occur = new Occurrences[map.size()];
return map.values().toArray(occur);
}
private void doScanIndex(DocumentSet docs, NodeSet nodes, String start, String end, long max, TreeMap<String, Occurrences> map, IndexReader reader, String field) throws IOException {
List<AtomicReaderContext> leaves = reader.leaves();
for (AtomicReaderContext context : leaves) {
NumericDocValues docIdValues = context.reader().getNumericDocValues(FIELD_DOC_ID);
BinaryDocValues nodeIdValues = context.reader().getBinaryDocValues(LuceneUtil.FIELD_NODE_ID);
Bits liveDocs = context.reader().getLiveDocs();
Terms terms = context.reader().terms(field);
if (terms != null) {
TermsEnum termsIter = terms.iterator(null);
if (termsIter.next() != null) {
do {
if (map.size() >= max) {
break;
}
BytesRef ref = termsIter.term();
String term = ref.utf8ToString();
if ((end == null || term.compareTo(end) <= 0) && (start == null || term.startsWith(start))) {
DocsEnum docsEnum = termsIter.docs(null, null);
while (docsEnum.nextDoc() != DocsEnum.NO_MORE_DOCS) {
if (liveDocs != null && !liveDocs.get(docsEnum.docID())) {
continue;
}
int docId = (int) docIdValues.get(docsEnum.docID());
DocumentImpl storedDocument = docs.getDoc(docId);
if (storedDocument == null)
continue;
if (nodes != null) {
final BytesRef nodeIdRef = nodeIdValues.get(docsEnum.docID());
int units = ByteConversion.byteToShort(nodeIdRef.bytes, nodeIdRef.offset);
NodeId nodeId = index.getBrokerPool().getNodeFactory().createFromData(units, nodeIdRef.bytes, nodeIdRef.offset + 2);
if (nodes.get(storedDocument, nodeId) != null) {
addOccurrence(map, term, docsEnum.freq(), storedDocument);
}
} else {
addOccurrence(map, term, docsEnum.freq(), storedDocument);
}
}
}
} while (termsIter.next() != null);
}
}
}
}
private void addOccurrence(TreeMap<String, Occurrences> map, String term, int frequency, DocumentImpl storedDocument) throws IOException {
Occurrences oc = map.get(term);
if (oc == null) {
oc = new Occurrences(term);
map.put(term, oc);
}
oc.addDocument(storedDocument);
oc.addOccurrences(frequency);
}
/**
* Adds the passed character sequence to the lucene index. We
* create one lucene document per XML node, using 2 fields to identify
* the node:
*
* <ul>
* <li>docId: eXist-internal document id of the node, stored as string.</li>
* <li>nodeId: the id of the node, stored in binary compressed form.</li>
* </ul>
*
* The text is indexed into a field whose name encodes the qualified name of
* the node. The qualified name is stored as a hex sequence pointing into the
* global symbol table.
*
* @param nodeId the node if
* @param qname the qname of the node
* @param path the node path
* @param config the lucene index config
* @param content the content of the node
*/
protected void indexText(final NodeId nodeId, final QName qname, final NodePath path, final LuceneIndexConfig config, final CharSequence content) {
final PendingDoc pending = new PendingDoc(nodeId, qname, path, content, config.getBoost(), config);
addPending(pending);
}
/**
* Adds the passed character sequence to the lucene index.
* This version uses the AttrImpl for node specific attribute match boosting.
*
* @param attribs the attributes
* @param nodeId the node id
* @param qname the qname of the node
* @param path the path of the node
* @param config the lucene index config
* @param content the content of the node
*/
protected void indexText(final java.util.Collection<AttrImpl> attribs, final NodeId nodeId, final QName qname, final NodePath path, final LuceneIndexConfig config, final CharSequence content) {
final PendingDoc pending = new PendingDoc(nodeId, qname, path, content, config.getAttrBoost(attribs), config);
addPending(pending);
}
private void addPending(final PendingDoc pending) {
nodesToWrite.add(pending);
cachedNodesSize += pending.text.length();
if (cachedNodesSize > maxCachedNodesSize) {
write();
}
}
private static class PendingDoc {
private final NodeId nodeId;
private final QName qname;
private final NodePath path;
private final CharSequence text;
private final float boost;
private final LuceneIndexConfig idxConf;
private PendingDoc(final NodeId nodeId, final QName qname, final NodePath path, final CharSequence text,
final float boost, final LuceneIndexConfig idxConf) {
this.nodeId = nodeId;
this.qname = qname;
this.path = path;
this.text = text;
this.idxConf = idxConf;
this.boost = boost;
}
}
private static class PendingAttr {
private final AttrImpl attr;
private final LuceneIndexConfig conf;
private final NodePath path;
public PendingAttr(final AttrImpl attr, final NodePath path, final LuceneIndexConfig conf) {
this.attr = attr;
this.conf = conf;
this.path = path;
}
}
private void write() {
if (nodesToWrite == null || nodesToWrite.isEmpty() || !canFlush) {
return;
}
if (broker.getIndexController().isReindexing()) {
// remove old indexed nodes
nodesToRemove = new TreeSet<>();
for (PendingDoc p : nodesToWrite) {
nodesToRemove.add(p.nodeId);
}
removeNodes();
}
IndexWriter writer = null;
try {
writer = index.getWriter();
// docId and nodeId are stored as doc value
NumericDocValuesField fDocId = new NumericDocValuesField(FIELD_DOC_ID, 0);
BinaryDocValuesField fNodeId = new BinaryDocValuesField(LuceneUtil.FIELD_NODE_ID, new BytesRef(8));
// docId also needs to be indexed
IntField fDocIdIdx = new IntField(FIELD_DOC_ID, 0, IntField.TYPE_NOT_STORED);
for (PendingDoc pending : nodesToWrite) {
final Document doc = new Document();
List<AbstractFieldConfig> facetConfigs = pending.idxConf.getFacetsAndFields();
facetConfigs.forEach(config ->
config.build(broker, currentDoc, pending.nodeId, doc, pending.text)
);
fDocId.setLongValue(currentDoc.getDocId());
doc.add(fDocId);
// store the node id
int nodeIdLen = pending.nodeId.size();
byte[] data = new byte[nodeIdLen + 2];
ByteConversion.shortToByte((short) pending.nodeId.units(), data, 0);
pending.nodeId.serialize(data, 2);
fNodeId.setBytesValue(data);
doc.add(fNodeId);
// add separate index for node id
BinaryTokenStream bts = new BinaryTokenStream(new BytesRef(data));
Field fNodeIdIdx = new Field(LuceneUtil.FIELD_NODE_ID, bts, TYPE_NODE_ID);
doc.add(fNodeIdIdx);
if (pending.idxConf.doIndex()) {
String contentField;
// the text content is indexed in a field using either
// the qname of the element or attribute or the field
// name defined in the configuration
if (pending.idxConf.isNamed())
contentField = pending.idxConf.getName();
else
contentField = LuceneUtil.encodeQName(pending.qname, index.getBrokerPool().getSymbols());
Field fld = new Field(contentField, pending.text.toString(), Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.YES);
if (pending.boost > 0) {
fld.setBoost(pending.boost);
} else if (config.getBoost() > 0) {
fld.setBoost(config.getBoost());
}
doc.add(fld);
}
fDocIdIdx.setIntValue(currentDoc.getDocId());
doc.add(fDocIdIdx);
final byte[] docNodeId = LuceneUtil.createId(currentDoc.getDocId(), pending.nodeId);
final Field fDocNodeId = new StoredField("docNodeId", docNodeId);
doc.add(fDocNodeId);
if (pending.idxConf.getAnalyzer() == null) {
writer.addDocument(config.facetsConfig.build(index.getTaxonomyWriter(), doc));
} else {
writer.addDocument(config.facetsConfig.build(index.getTaxonomyWriter(), doc), pending.idxConf.getAnalyzer());
}
}
} catch (final IOException e) {
LOG.warn("An exception was caught while indexing document: " + e.getMessage(), e);
} finally {
index.releaseWriter(writer);
nodesToWrite = new ArrayList<>();
cachedNodesSize = 0;
}
}
/**
* Optimize the Lucene index by merging all segments into a single one. This
* may take a while and write operations will be blocked during the optimize.
*/
public void optimize() {
IndexWriter writer = null;
try {
writer = index.getWriter(true);
writer.forceMerge(1, true);
writer.commit();
} catch (IOException e) {
LOG.warn("An exception was caught while optimizing the lucene index: " + e.getMessage(), e);
} finally {
index.releaseWriter(writer);
}
}
private class LuceneStreamListener extends AbstractStreamListener {
private ArrayList<PendingAttr> pendingAttrs = new ArrayList<>();
private ArrayList<AttrImpl> attributes = new ArrayList<>(10);
private ElementImpl currentElement;
@Override
public void startReplaceDocument(Txn transaction) {
// if config has fields or facets, we cannot flush until the document is completely stored
canFlush = config == null || !config.hasFieldsOrFacets();
}
@Override
public void endReplaceDocument(Txn transaction) {
canFlush = true;
}
@Override
public void startIndexDocument(Txn transaction) {
// if config has fields or facets, we cannot flush until the document is completely stored
canFlush = config == null || !config.hasFieldsOrFacets();
}
@Override
public void endIndexDocument(Txn transaction) {
canFlush = true;
}
@Override
public void startElement(Txn transaction, ElementImpl element, NodePath path) {
if (currentElement != null) {
indexPendingAttrs();
}
currentElement = element;
if (mode == ReindexMode.STORE && config != null) {
if (contentStack != null) {
for (final TextExtractor extractor : contentStack) {
extractor.startElement(element.getQName());
}
}
Iterator<LuceneIndexConfig> configIter = config.getConfig(path);
if (configIter != null) {
if (contentStack == null) {
contentStack = new ArrayDeque<>();
}
while (configIter.hasNext()) {
LuceneIndexConfig configuration = configIter.next();
if (configuration.match(path)) {
TextExtractor extractor = new DefaultTextExtractor();
extractor.configure(config, configuration);
contentStack.push(extractor);
}
}
}
}
super.startElement(transaction, element, path);
}
@Override
public void endElement(Txn transaction, ElementImpl element, NodePath path) {
if (config != null) {
if (mode == ReindexMode.STORE && contentStack != null) {
for (final TextExtractor extractor : contentStack) {
extractor.endElement(element.getQName());
}
}
Iterator<LuceneIndexConfig> configIter = config.getConfig(path);
if (mode != ReindexMode.REMOVE_ALL_NODES && configIter != null) {
if (mode == ReindexMode.REMOVE_SOME_NODES) {
nodesToRemove.add(element.getNodeId());
} else {
while (configIter.hasNext()) {
LuceneIndexConfig configuration = configIter.next();
if (configuration.match(path)) {
TextExtractor extractor = contentStack.pop();
if (configuration.shouldReindexOnAttributeChange()) {
// if we still have the attributes cached
// i e this element had no child elements,
// use them to save some time
// otherwise we fetch the attributes again
boolean wasEmpty = false;
if (attributes.isEmpty()) {
wasEmpty = true;
NamedNodeMap attributes1 = element.getAttributes();
for (int i = 0; i < attributes1.getLength(); i++) {
attributes.add((AttrImpl) attributes1.item(i));
}
}
indexText(attributes, element.getNodeId(), element.getQName(), path, extractor.getIndexConfig(), extractor.getText());
if (wasEmpty) {
attributes.clear();
}
} else {
// no attribute matching, index normally
indexText(element.getNodeId(), element.getQName(), path, extractor.getIndexConfig(), extractor.getText());
}
}
}
}
}
}
indexPendingAttrs();
currentElement = null;
super.endElement(transaction, element, path);
}
@Override
public void attribute(Txn transaction, AttrImpl attrib, NodePath path) {
path.addComponent(attrib.getQName());
AttrImpl attribCopy = null;
if (mode == ReindexMode.STORE && currentElement != null) {
attribCopy = (AttrImpl) NodePool.getInstance().borrowNode(Node.ATTRIBUTE_NODE);
attribCopy.setValue(attrib.getValue());
attribCopy.setNodeId(attrib.getNodeId());
attribCopy.setQName(attrib.getQName());
attributes.add(attribCopy);
}
Iterator<LuceneIndexConfig> configIter = null;
if (config != null)
configIter = config.getConfig(path);
if (mode != ReindexMode.REMOVE_ALL_NODES && configIter != null) {
if (mode == ReindexMode.REMOVE_SOME_NODES) {
nodesToRemove.add(attrib.getNodeId());
} else {
while (configIter.hasNext()) {
LuceneIndexConfig configuration = configIter.next();
if (configuration.match(path)) {
if (configuration.shouldReindexOnAttributeChange()) {
appendAttrToBeIndexedLater(attribCopy, new NodePath(path), configuration);
} else {
indexText(attrib.getNodeId(), attrib.getQName(), path, configuration, attrib.getValue());
}
}
}
}
}
path.removeLastComponent();
super.attribute(transaction, attrib, path);
}
@Override
public void characters(Txn transaction, AbstractCharacterData text, NodePath path) {
if (contentStack != null) {
for (final TextExtractor extractor : contentStack) {
extractor.beforeCharacters();
extractor.characters(text.getXMLString());
}
}
super.characters(transaction, text, path);
}
@Override
public IndexWorker getWorker() {
return LuceneIndexWorker.this;
}
/**
* Delay indexing of attributes until we have them all to calculate boost
*
* @param attr the attribute to be indexed
* @param path the node path
* @param conf the index config
*/
private void appendAttrToBeIndexedLater(AttrImpl attr, NodePath path, LuceneIndexConfig conf) {
if (currentElement == null){
LOG.error("currentElement == null");
} else {
pendingAttrs.add(new PendingAttr(attr, path, conf));
}
}
/**
* Put pending attribute nodes in indexing cache
* and then clear pending attributes
*/
private void indexPendingAttrs() {
try {
if (mode == ReindexMode.STORE && config != null) {
for (PendingAttr pending : pendingAttrs) {
AttrImpl attr = pending.attr;
indexText(attributes, attr.getNodeId(), attr.getQName(), pending.path, pending.conf, attr.getValue());
}
}
} finally {
pendingAttrs.clear();
releaseAttributes();
}
}
private void releaseAttributes() {
try {
for (Attr attr : attributes) {
NodePool.getInstance().returnNode((AttrImpl) attr);
}
} finally {
attributes.clear();
}
}
}
}
| ambs/exist | extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneIndexWorker.java | Java | lgpl-2.1 | 69,204 |
using System;
namespace elp87.TagReader.id3v2.Abstract
{
/// <summary>
/// This abstract base class provides general functionality for frames with user defined information
/// </summary>
public abstract class UserDefinedFrame
: TextFrame
{
#region Fields
/// <summary>
/// Frame description
/// </summary>
protected string _description;
/// <summary>
/// User defined information value
/// </summary>
protected string _value;
/// <summary>
/// Position of string terminator
/// </summary>
protected int _terminatorPos;
#endregion
#region Consructors
/// <summary>
/// Inheritable constructor for <see cref="elp87.TagReader.id3v2.Abstract.UserDefinedFrame"/> class
/// </summary>
public UserDefinedFrame()
: base()
{ }
/// <summary>
/// Main inheritable constructor for <see cref="elp87.TagReader.id3v2.Abstract.UserDefinedFrame"/> class.
/// </summary>
/// <param name="flags">Flag fields of current frame.</param>
/// <param name="frameData">Byte array that contains frame data excluding frame header and header extra data.</param>
public UserDefinedFrame(FrameFlagSet flags, byte[] frameData)
: base(flags, frameData)
{
this.ParseFrame(this._frameData);
}
#endregion
#region Properies
/// <summary>
/// Gets frame description.
/// </summary>
public string Description { get { return this._description; } }
/// <summary>
/// Gets user defined information value.
/// </summary>
public string Value { get { return this._value; } }
#endregion
#region Methods
private int ParseTerminatorPos(byte[] frameData)
{
int position;
if (this._encoding == TextEncoding.UTF16 || this._encoding == TextEncoding.UTF16_BE)
{
byte[] termByteArray = new byte[] { 0x00, 0x00 };
position = ByteArray.FindSubArray(frameData, termByteArray);
}
else
{
byte termByte = 0x00;
position = Array.IndexOf(frameData, termByte);
}
while (frameData[position + 1] == 0x00) { position++; }
return position;
}
/// <summary>
/// Parse frame data to compliant fields.
/// </summary>
/// <param name="frameData">Frame data.</param>
protected void ParseFrame(byte[] frameData)
{
this._terminatorPos = ParseTerminatorPos(frameData);
this._description = ParseDescription(frameData);
this._value = ParseValue(frameData);
}
/// <summary>
/// Parse description from byte array.
/// </summary>
/// <param name="frameData">Byte array.</param>
/// <returns>Description.</returns>
protected string ParseDescription(byte[] frameData)
{
char _UTF16NullChar = System.Text.Encoding.Unicode.GetString(new byte[] { 0x00 }).ToCharArray()[0];
byte[] descData = new byte[this._terminatorPos];
Array.Copy(frameData, descData, descData.Length);
string desc = this.GetString(descData);
if (desc == "") return "";
if (desc[desc.Length - 1] == _UTF16NullChar)
{ desc = desc.Substring(0, desc.Length - 1); }
return desc;
}
/// <summary>
/// Abstract method that should return user defined information value from byte array.
/// </summary>
/// <param name="frameData">Byte array.</param>
/// <returns>User defined information value.</returns>
protected abstract string ParseValue(byte[] frameData);
#endregion
}
}
| elp87/TagReader | elp87.TagReader/id3v2/Abstract/UserDefinedFrame.cs | C# | lgpl-2.1 | 4,123 |
import { FocusTools, Keys, UiFinder, Waiter } from '@ephox/agar';
import { describe, it } from '@ephox/bedrock-client';
import { TinyAssertions, TinyHooks, TinyUiActions } from '@ephox/mcagar';
import { Attribute, SugarBody, SugarDocument, SugarElement } from '@ephox/sugar';
import { assert } from 'chai';
import Editor from 'tinymce/core/api/Editor';
import Plugin from 'tinymce/plugins/emoticons/Plugin';
import Theme from 'tinymce/themes/silver/Theme';
import { fakeEvent } from '../module/test/Utils';
describe('browser.tinymce.plugins.emoticons.ImageEmoticonTest', () => {
const hook = TinyHooks.bddSetupLight<Editor>({
plugins: 'emoticons',
toolbar: 'emoticons',
base_url: '/project/tinymce/js/tinymce',
emoticons_database_url: '/project/tinymce/src/plugins/emoticons/main/js/emojiimages.js'
}, [ Plugin, Theme ], true);
it('TBA: Open dialog, Search for "dog", Dog should be first option', async () => {
const editor = hook.editor();
const doc = SugarDocument.getDocument();
TinyUiActions.clickOnToolbar(editor, 'button');
await TinyUiActions.pWaitForDialog(editor);
await FocusTools.pTryOnSelector('Focus should start on input', doc, 'input');
const input = FocusTools.setActiveValue(doc, 'dog');
fakeEvent(input, 'input');
await Waiter.pTryUntil(
'Wait until dog is the first choice (search should filter)',
() => {
const item = UiFinder.findIn(SugarBody.body(), '.tox-collection__item:first').getOrDie();
const attr = Attribute.get(item, 'data-collection-item-value');
const img = SugarElement.fromHtml<HTMLImageElement>(attr);
const src = Attribute.get(img, 'src');
assert.equal(src, 'https://twemoji.maxcdn.com/v/13.0.1/72x72/1f436.png', 'Search should show a dog');
}
);
TinyUiActions.keydown(editor, Keys.tab());
await FocusTools.pTryOnSelector('Focus should have moved to collection', doc, '.tox-collection__item');
TinyUiActions.keydown(editor, Keys.enter());
await Waiter.pTryUntil(
'Waiting for content update',
() => TinyAssertions.assertContentPresence(editor, {
'img[data-emoticon]': 1,
'img[data-mce-resize="false"]': 1,
'img[data-mce-placeholder="1"]': 1,
'img[alt="\ud83d\udc36"]': 1,
'img[src="https://twemoji.maxcdn.com/v/13.0.1/72x72/1f436.png"]': 1
})
);
});
});
| TeamupCom/tinymce | modules/tinymce/src/plugins/emoticons/test/ts/browser/ImageEmoticonTest.ts | TypeScript | lgpl-2.1 | 2,391 |
namespace JDC.CustomControl
{
partial class StringTextBox
{
/// <summary>
/// 必要なデザイナー変数です。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 使用中のリソースをすべてクリーンアップします。
/// </summary>
/// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region コンポーネント デザイナーで生成されたコード
/// <summary>
/// デザイナー サポートに必要なメソッドです。このメソッドの内容を
/// コード エディターで変更しないでください。
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// CustomControl_StringTextBox
//
this.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.Font = new System.Drawing.Font("Meiryo UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.ResumeLayout(false);
}
#endregion
}
}
| madscient/FITOMApp | FITOMGUI.NET/CustomControl.old/StringTextBox.Designer.cs | C# | lgpl-2.1 | 1,575 |
/*
This file is part of the Intelligent Store and Dump project
an application of the YAES simulator.
Created on: Jan 6, 2011
storeanddump.visualization.paintUncertainMovementSegment
Copyright (c) 2010 Ladislau Boloni
This package is licensed under the LGPL version 2.
*/
package yaes.sensornetwork.visualization;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.io.Serializable;
import yaes.sensornetwork.knowledge.UncertainMovementSegment;
import yaes.ui.visualization.VisualCanvas;
import yaes.ui.visualization.VisualizationProperties;
import yaes.ui.visualization.painters.IPainter;
import yaes.ui.visualization.painters.PaintSpec;
import yaes.ui.visualization.painters.PainterHelper;
/**
*
* <code>storeanddump.visualization.paintUncertainMovementSegment</code> paints
* an uncertain movement component
*
* @author Ladislau Boloni (lboloni@eecs.ucf.edu)
*/
public class paintUncertainMovementSegment implements IPainter, Serializable {
private PaintSpec umsSpec = PaintSpec.createDraw(Color.blue.darker()
.darker());
/*
* (non-Javadoc)
*
* @see yaes.ui.visualization.painters.IPainter#getLayer()
*/
@Override
public int getLayer() {
return BACKGROUND_LAYER;
}
/*
* (non-Javadoc)
*
* @see yaes.ui.visualization.painters.IPainter#paint(java.awt.Graphics2D,
* java.lang.Object, yaes.ui.visualization.VisualCanvas)
*/
@Override
public void paint(Graphics2D g, Object o, VisualCanvas panel) {
UncertainMovementSegment ums = (UncertainMovementSegment) o;
Shape s = ums.getShape();
PainterHelper.paintShape(s, umsSpec, g, panel);
PainterHelper.paintArrow(ums.getLocationFrom(), ums.getLocationTo(),
umsSpec.getBorderColor(), g, panel);
PainterHelper.paintHtmlLabel("" + ums.getTimeTo(), ums.getLocationTo(),
5, 5, Color.white, false, 0, null, false, g, panel);
}
/*
* (non-Javadoc)
*
* @see yaes.ui.visualization.painters.IPainter#registerParameters(yaes.ui.
* visualization.VisualizationProperties)
*/
@Override
public void registerParameters(
VisualizationProperties visualizationProperties) {
// nothing here
}
}
| NetMoc/Yaes-SensorNetwork | src/main/java/yaes/sensornetwork/visualization/paintUncertainMovementSegment.java | Java | lgpl-2.1 | 2,167 |
/*
* This program 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.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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 Lesser General Public License for more details.
*
* Copyright (c) 2006 - 2013 Pentaho Corporation and Contributors. All rights reserved.
*/
package org.pentaho.reporting.libraries.formula.function.math;
import org.pentaho.reporting.libraries.formula.EvaluationException;
import org.pentaho.reporting.libraries.formula.FormulaContext;
import org.pentaho.reporting.libraries.formula.LibFormulaErrorValue;
import org.pentaho.reporting.libraries.formula.function.Function;
import org.pentaho.reporting.libraries.formula.function.ParameterCallback;
import org.pentaho.reporting.libraries.formula.lvalues.TypeValuePair;
import org.pentaho.reporting.libraries.formula.typing.Type;
import org.pentaho.reporting.libraries.formula.typing.coretypes.NumberType;
import java.math.BigDecimal;
/**
* This function returns the acos of the value.
*
* @author ocke
*/
public class AsinFunction implements Function {
public String getCanonicalName() {
return "ASIN";
}
public TypeValuePair evaluate( FormulaContext context, ParameterCallback parameters ) throws EvaluationException {
final int parameterCount = parameters.getParameterCount();
if ( parameterCount != 1 ) {
throw EvaluationException.getInstance( LibFormulaErrorValue.ERROR_ARGUMENTS_VALUE );
}
final Type type1 = parameters.getType( 0 );
final Object value1 = parameters.getValue( 0 );
final Number result = context.getTypeRegistry().convertToNumber( type1, value1 );
if ( result == null ) {
throw EvaluationException.getInstance( LibFormulaErrorValue.ERROR_INVALID_ARGUMENT_VALUE );
}
final double d = result.doubleValue();
if ( d < -1.0 || d > 1.0 ) {
throw EvaluationException.getInstance( LibFormulaErrorValue.ERROR_INVALID_ARGUMENT_VALUE );
}
return new TypeValuePair( NumberType.GENERIC_NUMBER, new BigDecimal( Math.asin( d ) ) );
}
}
| EgorZhuk/pentaho-reporting | libraries/libformula/src/main/java/org/pentaho/reporting/libraries/formula/function/math/AsinFunction.java | Java | lgpl-2.1 | 2,573 |
// -*- c++ -*-
/*!
*
* Copyright (C) 2015 Jolla Ltd.
*
* Contact: Valerio Valerio <valerio.valerio@jolla.com>
* Author: Andres Gomez <andres.gomez@jolla.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "dbusextendedpendingcallwatcher_p.h"
#include <DBusExtendedAbstractInterface>
#include <QtDBus/QDBusMetaType>
#include <QtDBus/QDBusMessage>
#include <QtDBus/QDBusPendingCall>
#include <QtDBus/QDBusPendingCallWatcher>
#include <QtDBus/QDBusPendingReply>
#include <QtCore/QDebug>
#include <QtCore/QMetaProperty>
Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, dBusPropertiesInterface, ("org.freedesktop.DBus.Properties"))
Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, dBusPropertiesChangedSignal, ("PropertiesChanged"))
Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, propertyChangedSignature, ("propertyChanged(QString,QVariant)"))
Q_GLOBAL_STATIC_WITH_ARGS(QByteArray, propertyInvalidatedSignature, ("propertyInvalidated(QString)"))
DBusExtendedAbstractInterface::DBusExtendedAbstractInterface(const QString &service, const QString &path, const char *interface, const QDBusConnection &connection, QObject *parent)
: QDBusAbstractInterface(service, path, interface, connection, parent)
, m_sync(false)
, m_useCache(false)
, m_getAllPendingCallWatcher(0)
, m_propertiesChangedConnected(false)
{
}
DBusExtendedAbstractInterface::~DBusExtendedAbstractInterface()
{
}
void DBusExtendedAbstractInterface::getAllProperties()
{
m_lastExtendedError = QDBusError();
if (!isValid()) {
QString errorMessage = QStringLiteral("This Extended DBus interface is not valid yet.");
m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
qDebug() << Q_FUNC_INFO << errorMessage;
return;
}
if (!m_sync && m_getAllPendingCallWatcher) {
// Call already in place, not repeating ...
return;
}
QDBusMessage msg = QDBusMessage::createMethodCall(service(), path(), *dBusPropertiesInterface(), QStringLiteral("GetAll"));
msg << interface();
if (m_sync) {
QDBusMessage reply = connection().call(msg);
if (reply.type() != QDBusMessage::ReplyMessage) {
m_lastExtendedError = QDBusError(reply);
qWarning() << Q_FUNC_INFO << m_lastExtendedError.message();
return;
}
if (reply.signature() != QLatin1String("a{sv}")) {
QString errorMessage = QStringLiteral("Invalid signature \"%1\" in return from call to %2")
.arg(reply.signature(),
QString(*dBusPropertiesInterface()));
qWarning() << Q_FUNC_INFO << errorMessage;
m_lastExtendedError = QDBusError(QDBusError::InvalidSignature, errorMessage);
return;
}
QVariantMap value = reply.arguments().at(0).toMap();
onPropertiesChanged(interface(), value, QStringList());
} else {
QDBusPendingReply<QVariantMap> async = connection().asyncCall(msg);
m_getAllPendingCallWatcher = new QDBusPendingCallWatcher(async, this);
connect(m_getAllPendingCallWatcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(onAsyncGetAllPropertiesFinished(QDBusPendingCallWatcher*)));
return;
}
}
void DBusExtendedAbstractInterface::connectNotify(const QMetaMethod &signal)
{
if (signal.methodType() == QMetaMethod::Signal
&& (signal.methodSignature() == *propertyChangedSignature()
|| signal.methodSignature() == *propertyInvalidatedSignature())) {
if (!m_propertiesChangedConnected) {
QStringList argumentMatch;
argumentMatch << interface();
connection().connect(service(), path(), *dBusPropertiesInterface(), *dBusPropertiesChangedSignal(),
argumentMatch, QString(),
this, SLOT(onPropertiesChanged(QString, QVariantMap, QStringList)));
m_propertiesChangedConnected = true;
return;
}
} else {
QDBusAbstractInterface::connectNotify(signal);
}
}
void DBusExtendedAbstractInterface::disconnectNotify(const QMetaMethod &signal)
{
if (signal.methodType() == QMetaMethod::Signal
&& (signal.methodSignature() == *propertyChangedSignature()
|| signal.methodSignature() == *propertyInvalidatedSignature())) {
if (m_propertiesChangedConnected
&& 0 == receivers(propertyChangedSignature()->constData())
&& 0 == receivers(propertyInvalidatedSignature()->constData())) {
QStringList argumentMatch;
argumentMatch << interface();
connection().disconnect(service(), path(), *dBusPropertiesInterface(), *dBusPropertiesChangedSignal(),
argumentMatch, QString(),
this, SLOT(onPropertiesChanged(QString, QVariantMap, QStringList)));
m_propertiesChangedConnected = false;
return;
}
} else {
QDBusAbstractInterface::disconnectNotify(signal);
}
}
QVariant DBusExtendedAbstractInterface::internalPropGet(const char *propname, void *propertyPtr)
{
m_lastExtendedError = QDBusError();
if (m_useCache) {
int propertyIndex = metaObject()->indexOfProperty(propname);
QMetaProperty metaProperty = metaObject()->property(propertyIndex);
return QVariant(metaProperty.type(), propertyPtr);
}
if (m_sync) {
return property(propname);
} else {
if (!isValid()) {
QString errorMessage = QStringLiteral("This Extended DBus interface is not valid yet.");
m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
qDebug() << Q_FUNC_INFO << errorMessage;
return QVariant();
}
int propertyIndex = metaObject()->indexOfProperty(propname);
if (-1 == propertyIndex) {
QString errorMessage = QStringLiteral("Got unknown property \"%1\" to read")
.arg(QString::fromLatin1(propname));
m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
qWarning() << Q_FUNC_INFO << errorMessage;
return QVariant();
}
QMetaProperty metaProperty = metaObject()->property(propertyIndex);
if (!metaProperty.isReadable()) {
QString errorMessage = QStringLiteral("Property \"%1\" is NOT readable")
.arg(QString::fromLatin1(propname));
m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
qWarning() << Q_FUNC_INFO << errorMessage;
return QVariant();
}
// is this metatype registered?
const char *expectedSignature = "";
if (int(metaProperty.type()) != QMetaType::QVariant) {
expectedSignature = QDBusMetaType::typeToSignature(metaProperty.userType());
if (0 == expectedSignature) {
QString errorMessage =
QStringLiteral("Type %1 must be registered with Qt D-Bus "
"before it can be used to read property "
"%2.%3")
.arg(metaProperty.typeName(),
interface(),
propname);
m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
qWarning() << Q_FUNC_INFO << errorMessage;
return QVariant();
}
}
asyncProperty(propname);
return QVariant(metaProperty.type(), propertyPtr);
}
}
void DBusExtendedAbstractInterface::internalPropSet(const char *propname, const QVariant &value, void *propertyPtr)
{
m_lastExtendedError = QDBusError();
if (m_sync) {
setProperty(propname, value);
} else {
if (!isValid()) {
QString errorMessage = QStringLiteral("This interface is not yet valid");
m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
qDebug() << Q_FUNC_INFO << errorMessage;
return;
}
int propertyIndex = metaObject()->indexOfProperty(propname);
if (-1 == propertyIndex) {
QString errorMessage = QStringLiteral("Got unknown property \"%1\" to write")
.arg(QString::fromLatin1(propname));
m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
qWarning() << Q_FUNC_INFO << errorMessage;
return;
}
QMetaProperty metaProperty = metaObject()->property(propertyIndex);
if (!metaProperty.isWritable()) {
QString errorMessage = QStringLiteral("Property \"%1\" is NOT writable")
.arg(QString::fromLatin1(propname));
m_lastExtendedError = QDBusMessage::createError(QDBusError::Failed, errorMessage);
qWarning() << Q_FUNC_INFO << errorMessage;
return;
}
asyncSetProperty(propname, QVariant(metaProperty.type(), propertyPtr));
}
}
QVariant DBusExtendedAbstractInterface::asyncProperty(const QString &propertyName)
{
QDBusMessage msg = QDBusMessage::createMethodCall(service(), path(), *dBusPropertiesInterface(), QStringLiteral("Get"));
msg << interface() << propertyName;
QDBusPendingReply<QVariant> async = connection().asyncCall(msg);
DBusExtendedPendingCallWatcher *watcher = new DBusExtendedPendingCallWatcher(async, propertyName, QVariant(), this);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(onAsyncPropertyFinished(QDBusPendingCallWatcher*)));
return QVariant();
}
void DBusExtendedAbstractInterface::asyncSetProperty(const QString &propertyName, const QVariant &value)
{
QDBusMessage msg = QDBusMessage::createMethodCall(service(), path(), *dBusPropertiesInterface(), QStringLiteral("Set"));
msg << interface() << propertyName << value;
QDBusPendingReply<QVariant> async = connection().asyncCall(msg);
DBusExtendedPendingCallWatcher *watcher = new DBusExtendedPendingCallWatcher(async, propertyName, value, this);
connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(onAsyncSetPropertyFinished(QDBusPendingCallWatcher*)));
}
void DBusExtendedAbstractInterface::onAsyncPropertyFinished(DBusExtendedPendingCallWatcher *watcher)
{
QDBusPendingReply<QVariant> reply = *watcher;
if (reply.isError()) {
m_lastExtendedError = reply.error();
} else {
int propertyIndex = metaObject()->indexOfProperty(watcher->asyncProperty().toLatin1().constData());
QVariant value = demarshall(interface(),
metaObject()->property(propertyIndex),
reply.value(),
&m_lastExtendedError);
if (m_lastExtendedError.isValid()) {
emit propertyInvalidated(watcher->asyncProperty());
} else {
emit propertyChanged(watcher->asyncProperty(), value);
}
}
emit asyncPropertyFinished(watcher->asyncProperty());
watcher->deleteLater();
}
void DBusExtendedAbstractInterface::onAsyncSetPropertyFinished(DBusExtendedPendingCallWatcher *watcher)
{
QDBusPendingReply<QVariant> reply = *watcher;
if (reply.isError()) {
m_lastExtendedError = reply.error();
} else {
m_lastExtendedError = QDBusError();
}
emit asyncSetPropertyFinished(watcher->asyncProperty());
// Resetting the property to its previous value after sending the
// finished signal
if (reply.isError()) {
m_lastExtendedError = QDBusError();
emit propertyChanged(watcher->asyncProperty(), watcher->previousValue());
}
watcher->deleteLater();
}
void DBusExtendedAbstractInterface::onAsyncGetAllPropertiesFinished(QDBusPendingCallWatcher *watcher)
{
m_getAllPendingCallWatcher = 0;
QDBusPendingReply<QVariantMap> reply = *watcher;
if (reply.isError()) {
m_lastExtendedError = reply.error();
} else {
m_lastExtendedError = QDBusError();
}
emit asyncGetAllPropertiesFinished();
if (!reply.isError()) {
onPropertiesChanged(interface(), reply.value(), QStringList());
}
watcher->deleteLater();
}
void DBusExtendedAbstractInterface::onPropertiesChanged(const QString& interfaceName,
const QVariantMap& changedProperties,
const QStringList& invalidatedProperties)
{
if (interfaceName == interface()) {
QVariantMap::const_iterator i = changedProperties.constBegin();
while (i != changedProperties.constEnd()) {
int propertyIndex = metaObject()->indexOfProperty(i.key().toLatin1().constData());
if (-1 == propertyIndex) {
qDebug() << Q_FUNC_INFO << "Got unknown changed property" << i.key();
} else {
QVariant value = demarshall(interface(), metaObject()->property(propertyIndex), i.value(), &m_lastExtendedError);
if (m_lastExtendedError.isValid()) {
emit propertyInvalidated(i.key());
} else {
emit propertyChanged(i.key(), value);
}
}
++i;
}
QStringList::const_iterator j = invalidatedProperties.constBegin();
while (j != invalidatedProperties.constEnd()) {
if (-1 == metaObject()->indexOfProperty(j->toLatin1().constData())) {
qDebug() << Q_FUNC_INFO << "Got unknown invalidated property" << *j;
} else {
m_lastExtendedError = QDBusError();
emit propertyInvalidated(*j);
}
++j;
}
}
}
QVariant DBusExtendedAbstractInterface::demarshall(const QString &interface, const QMetaProperty &metaProperty, const QVariant &value, QDBusError *error)
{
Q_ASSERT(metaProperty.isValid());
Q_ASSERT(error != 0);
if (value.userType() == metaProperty.userType()) {
// No need demarshalling. Passing back straight away ...
*error = QDBusError();
return value;
}
QVariant result = QVariant(metaProperty.userType(), (void*)0);
QString errorMessage;
const char *expectedSignature = QDBusMetaType::typeToSignature(metaProperty.userType());
if (value.userType() == qMetaTypeId<QDBusArgument>()) {
// demarshalling a DBus argument ...
QDBusArgument dbusArg = value.value<QDBusArgument>();
if (expectedSignature == dbusArg.currentSignature().toLatin1()) {
QDBusMetaType::demarshall(dbusArg, metaProperty.userType(), result.data());
if (!result.isValid()) {
errorMessage = QStringLiteral("Unexpected failure demarshalling "
"upon PropertiesChanged signal arrival "
"for property `%3.%4' (expected type `%5' (%6))")
.arg(interface,
QString::fromLatin1(metaProperty.name()),
QString::fromLatin1(metaProperty.typeName()),
expectedSignature);
}
} else {
errorMessage = QStringLiteral("Unexpected `user type' (%2) "
"upon PropertiesChanged signal arrival "
"for property `%3.%4' (expected type `%5' (%6))")
.arg(dbusArg.currentSignature(),
interface,
QString::fromLatin1(metaProperty.name()),
QString::fromLatin1(metaProperty.typeName()),
QString::fromLatin1(expectedSignature));
}
} else {
const char *actualSignature = QDBusMetaType::typeToSignature(value.userType());
errorMessage = QStringLiteral("Unexpected `%1' (%2) "
"upon PropertiesChanged signal arrival "
"for property `%3.%4' (expected type `%5' (%6))")
.arg(QString::fromLatin1(value.typeName()),
QString::fromLatin1(actualSignature),
interface,
QString::fromLatin1(metaProperty.name()),
QString::fromLatin1(metaProperty.typeName()),
QString::fromLatin1(expectedSignature));
}
if (errorMessage.isEmpty()) {
*error = QDBusError();
} else {
*error = QDBusMessage::createError(QDBusError::InvalidSignature, errorMessage);
qDebug() << Q_FUNC_INFO << errorMessage;
}
return result;
}
| nemomobile/qtdbusextended | src/dbusextendedabstractinterface.cpp | C++ | lgpl-2.1 | 17,552 |
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (c) 2012-2014 Monty Program Ab
// Copyright (c) 2015-2021 MariaDB Corporation Ab
package org.mariadb.jdbc.message.server;
import org.mariadb.jdbc.client.ReadableByteBuf;
import org.mariadb.jdbc.client.ServerVersion;
import org.mariadb.jdbc.message.ServerMessage;
import org.mariadb.jdbc.message.server.util.ServerVersionUtility;
import org.mariadb.jdbc.util.constants.Capabilities;
public final class InitialHandshakePacket implements ServerMessage {
private static final String MARIADB_RPL_HACK_PREFIX = "5.5.5-";
private final long threadId;
private final byte[] seed;
private final long capabilities;
private final short defaultCollation;
private final short serverStatus;
private final String authenticationPluginType;
private final ServerVersion version;
private InitialHandshakePacket(
String serverVersion,
long threadId,
byte[] seed,
long capabilities,
short defaultCollation,
short serverStatus,
boolean mariaDBServer,
String authenticationPluginType) {
this.threadId = threadId;
this.seed = seed;
this.capabilities = capabilities;
this.defaultCollation = defaultCollation;
this.serverStatus = serverStatus;
this.authenticationPluginType = authenticationPluginType;
this.version = new ServerVersionUtility(serverVersion, mariaDBServer);
}
public static InitialHandshakePacket decode(ReadableByteBuf reader) {
byte protocolVersion = reader.readByte();
if (protocolVersion != 0x0a) {
throw new IllegalArgumentException(
String.format("Unexpected initial handshake protocol value [%s]", protocolVersion));
}
String serverVersion = reader.readStringNullEnd();
long threadId = reader.readInt();
final byte[] seed1 = new byte[8];
reader.readBytes(seed1);
reader.skip();
int serverCapabilities2FirstBytes = reader.readUnsignedShort();
short defaultCollation = reader.readUnsignedByte();
short serverStatus = reader.readShort();
int serverCapabilities4FirstBytes = serverCapabilities2FirstBytes + (reader.readShort() << 16);
int saltLength = 0;
if ((serverCapabilities4FirstBytes & Capabilities.PLUGIN_AUTH) != 0) {
saltLength = Math.max(12, reader.readByte() - 9);
} else {
reader.skip();
}
reader.skip(6);
// MariaDB additional capabilities.
// Filled only if MariaDB server 10.2+
long mariaDbAdditionalCapacities = reader.readInt();
byte[] seed;
if ((serverCapabilities4FirstBytes & Capabilities.SECURE_CONNECTION) != 0) {
final byte[] seed2;
if (saltLength > 0) {
seed2 = new byte[saltLength];
reader.readBytes(seed2);
} else {
seed2 = reader.readBytesNullEnd();
}
seed = new byte[seed1.length + seed2.length];
System.arraycopy(seed1, 0, seed, 0, seed1.length);
System.arraycopy(seed2, 0, seed, seed1.length, seed2.length);
} else {
seed = seed1;
}
reader.skip();
/*
* check for MariaDB 10.x replication hack , remove fake prefix if needed
* (see comments about MARIADB_RPL_HACK_PREFIX)
*/
boolean serverMariaDb;
if (serverVersion.startsWith(MARIADB_RPL_HACK_PREFIX)) {
serverMariaDb = true;
serverVersion = serverVersion.substring(MARIADB_RPL_HACK_PREFIX.length());
} else {
serverMariaDb = serverVersion.contains("MariaDB");
}
// since MariaDB 10.2
long serverCapabilities;
if ((serverCapabilities4FirstBytes & Capabilities.CLIENT_MYSQL) == 0) {
serverCapabilities =
(serverCapabilities4FirstBytes & 0xffffffffL) + (mariaDbAdditionalCapacities << 32);
serverMariaDb = true;
} else {
serverCapabilities = serverCapabilities4FirstBytes & 0xffffffffL;
}
String authenticationPluginType = null;
if ((serverCapabilities4FirstBytes & Capabilities.PLUGIN_AUTH) != 0) {
authenticationPluginType = reader.readStringNullEnd();
}
return new InitialHandshakePacket(
serverVersion,
threadId,
seed,
serverCapabilities,
defaultCollation,
serverStatus,
serverMariaDb,
authenticationPluginType);
}
public ServerVersion getVersion() {
return version;
}
public long getThreadId() {
return threadId;
}
public byte[] getSeed() {
return seed;
}
public long getCapabilities() {
return capabilities;
}
public short getDefaultCollation() {
return defaultCollation;
}
public short getServerStatus() {
return serverStatus;
}
public String getAuthenticationPluginType() {
return authenticationPluginType;
}
}
| MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/message/server/InitialHandshakePacket.java | Java | lgpl-2.1 | 4,713 |
#ifndef SDL_DOUBLE_LIST_HPP
#define SDL_DOUBLE_LIST_HPP
#include "SDLList.hpp"
#include "DoubleListItem.hpp"
SDLListdeclare(SDLDoubleList, DoubleListItem*, double_value, double)
#endif
| tenpercent/cp-sandbox | src/cgm/util/SDLDoubleList.hpp | C++ | lgpl-2.1 | 190 |
package org.wings.plaf.css.script;
import org.wings.script.ScriptListener;
public class HideSelectBoxesScript
implements ScriptListener
{
@Override
public String getEvent() {
return null;
}
@Override
public String getCode() {
return null;
}
@Override
public String getScript() {
final StringBuilder script = new StringBuilder();
script.append("function hideSelectBoxes() {\n");
script.append(" for (var i = 0; i < document.forms.length; i++) {\n");
script.append(" for (var e = 0; e < document.forms[i].length; e++) {\n");
script.append(" if (document.forms[i].elements[e].tagName == 'SELECT') {\n");
script.append(" document.forms[i].elements[e].style.visibility = 'hidden';\n");
script.append(" }\n");
script.append(" }\n");
script.append(" }\n");
script.append("}\n");
script.append("hideSelectBoxes();\n");
return script.toString();
}
@Override
public int getPriority() {
return 0;
}
}
| dheid/wings3 | wings/src/main/java/org/wings/plaf/css/script/HideSelectBoxesScript.java | Java | lgpl-2.1 | 1,125 |
#include <iostream>
#include <vector>
#include <boost/lexical_cast.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <sill/factor/any_factor.hpp>
#include <sill/factor/table_factor.hpp>
#include <sill/inference/exact/junction_tree_inference.hpp>
#include <sill/stl_io.hpp>
#include <sill/range/algorithm.hpp>
int main(int argc, char** argv)
{
using namespace sill;
using namespace std;
/*
typedef table_factor< dense_table<double> > table_factor;
typedef any_factor<double> any_factor;
*/
/*
typedef any_factor<double> factor_type;
factor_type f = tablef(1);
factor_type f1= tablef(1);
factor_type g = constant_factor(2);
factor_type h = f*g;
cout << f << endl;
cout << g << endl;
cout << h << endl;
cout << (f == f1) << endl;
cout << (f == g) << endl;
*/
size_t m = (argc > 1) ? boost::lexical_cast<size_t>(argv[1]) : 2;
size_t n = (argc > 2) ? boost::lexical_cast<size_t>(argv[2]) : 100;
size_t k = (m * n) / 2;
universe u;
finite_var_vector v = u.new_finite_variables(k, 2);
std::vector< tablef > factors(n);
// Generate n random table factors, each with <=m variables
boost::mt19937 rng;
uniform_factor_generator gen;
for(size_t i = 0; i < n; i++) {
finite_domain d;
for(size_t j = 0; j < m; j++) d.insert(v[rng() % k]);
factors[i] = gen(d, rng);
}
if (n < 10) {
cout << "Random factors:" << endl;
cout << v << endl;
}
// Perform junction tree inference using the table factors
shafer_shenoy<tablef> ss_table(factors);
cout << "Tree width of ss_table: " << ss_table.tree_width() << endl;
ss_table.calibrate();
ss_table.normalize();
std::vector< tablef > table_beliefs = ss_table.clique_beliefs();
if (n < 10) cout << table_beliefs << endl;
// Perform junction tree inference using polymorphic factors
shafer_shenoy<any_factor> ss_poly(factors);
cout << "Tree width of ss_poly: " << ss_table.tree_width() << endl;
ss_poly.calibrate();
ss_poly.normalize();
std::vector<any_factor> poly_beliefs = ss_poly.clique_beliefs();
if (n < 10) cout << poly_beliefs << endl;
assert(norm_inf(poly_beliefs[0], poly_beliefs[0]) < 1e-10);
assert(table_beliefs[0] == poly_beliefs[0]);
//assert(!(poly_beliefs[0] < poly_beliefs[0]));
// Compare the computed beliefs
assert(poly_beliefs.size() == table_beliefs.size());
assert(sill::equal(poly_beliefs, table_beliefs));
}
| Matt3164/sill | tests/factor/any_factor.cpp | C++ | lgpl-2.1 | 2,402 |
package le.mon;
/**
* Contains shared constant values for the different MFW implementation elements.
*
* @author Teemu Kanstren
*/
public class MsgConst {
//describes the base measure "class" for a probe
public static final String PROBE_BM_CLASS = "bm_class";
//base measure name for a probe
public static final String PROBE_BM_NAME = "bm_name";
//base measure description for a probe
public static final String PROBE_BM_DESCRIPTION = "bm_description";
//the name of a probe
public static final String PROBE_NAME = "description";
//precision of a probe, integer, higher is better probe with better measurements
public static final String PROBE_PRECISION = "precision";
//the name of the target of measurement for a probe
public static final String PROBE_TARGET_NAME = "target_name";
//the type of the target of measurement for a probe
public static final String PROBE_TARGET_TYPE = "target_type";
public static final String PROBE_URL = "probe_url";
public static final String THREAD_POOL_SIZE = "thread_pool_size";
public static final String TASK_TIMEOUT = "task_timeout";
public static final String PROBE_TIMEOUT = "probe_timeout";
public static final String PARAM_TIME = "time";
public static final String PARAM_MEASURE_URI = "measure_uri";
public static final String PARAM_PROBE_URL = "probe_url";
public static final String PARAM_VALUE = "value";
public static final String PARAM_EVENT_TYPE = "event_type";
public static final String PARAM_EVENT_SOURCE = "event_source";
public static final String PARAM_EVENT_MSG = "event_msg";
public static final String PARAM_CONFIG = "config";
public static final String PARAM_ID = "id";
public static final String PARAM_PUBLIC_KEY = "public_key";
//property that defines the type of message being sent
public static final String MSGTYPE = "msg_name";
public static final String MSG_REGISTER = "msg_register";
public static final String MSG_UNREGISTER = "msg_unregister";
public static final String MSG_MEASUREMENT = "msg_measurement";
public static final String MSG_EVENT = "msg_event";
public static final String MSG_ADD_MEASURE = "msg_add_measure";
public static final String MSG_REMOVE_MEASURE = "msg_remove_measure";
public static final String MSG_KEEP_ALIVE = "msg_keep_alive";
public static final String EVENT_NO_VALUE_FOR_BM = "event_no_valid_value";
public static final String EVENT_PROBE_HANGS = "event_probe_hangs";
public static final String MEASURE_INTERVAL = "measure_interval";
public static final String HTTP_PORT = "http_port";
public static String createMeasureURI(String targetType, String targetName, String bmClass, String bmName) {
return "MFW://" + targetType + "/" + targetName + "/" + bmClass + "/" + bmName;
}
}
| mukatee/le-mon | src/le/mon/MsgConst.java | Java | lgpl-2.1 | 2,779 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 5 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at the following url: |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Author: Stig Sæther Bakken <ssb@php.net> |
// +----------------------------------------------------------------------+
//
// $Id: Common.php,v 1.2 2006/11/23 10:56:08 cvs_roman Exp $
require_once "PEAR.php";
class PEAR_Command_Common extends PEAR
{
// {{{ properties
/**
* PEAR_Config object used to pass user system and configuration
* on when executing commands
*
* @var object
*/
var $config;
/**
* User Interface object, for all interaction with the user.
* @var object
*/
var $ui;
var $_deps_rel_trans = array(
'lt' => '<',
'le' => '<=',
'eq' => '=',
'ne' => '!=',
'gt' => '>',
'ge' => '>=',
'has' => '=='
);
var $_deps_type_trans = array(
'pkg' => 'package',
'extension' => 'extension',
'php' => 'PHP',
'prog' => 'external program',
'ldlib' => 'external library for linking',
'rtlib' => 'external runtime library',
'os' => 'operating system',
'websrv' => 'web server',
'sapi' => 'SAPI backend'
);
// }}}
// {{{ constructor
/**
* PEAR_Command_Common constructor.
*
* @access public
*/
function PEAR_Command_Common(&$ui, &$config)
{
parent::PEAR();
$this->config = &$config;
$this->ui = &$ui;
}
// }}}
// {{{ getCommands()
/**
* Return a list of all the commands defined by this class.
* @return array list of commands
* @access public
*/
function getCommands()
{
$ret = array();
foreach (array_keys($this->commands) as $command) {
$ret[$command] = $this->commands[$command]['summary'];
}
return $ret;
}
// }}}
// {{{ getShortcuts()
/**
* Return a list of all the command shortcuts defined by this class.
* @return array shortcut => command
* @access public
*/
function getShortcuts()
{
$ret = array();
foreach (array_keys($this->commands) as $command) {
if (isset($this->commands[$command]['shortcut'])) {
$ret[$this->commands[$command]['shortcut']] = $command;
}
}
return $ret;
}
// }}}
// {{{ getOptions()
function getOptions($command)
{
return @$this->commands[$command]['options'];
}
// }}}
// {{{ getGetoptArgs()
function getGetoptArgs($command, &$short_args, &$long_args)
{
$short_args = "";
$long_args = array();
if (empty($this->commands[$command])) {
return;
}
reset($this->commands[$command]);
while (list($option, $info) = each($this->commands[$command]['options'])) {
$larg = $sarg = '';
if (isset($info['arg'])) {
if ($info['arg']{0} == '(') {
$larg = '==';
$sarg = '::';
$arg = substr($info['arg'], 1, -1);
} else {
$larg = '=';
$sarg = ':';
$arg = $info['arg'];
}
}
if (isset($info['shortopt'])) {
$short_args .= $info['shortopt'] . $sarg;
}
$long_args[] = $option . $larg;
}
}
// }}}
// {{{ getHelp()
/**
* Returns the help message for the given command
*
* @param string $command The command
* @return mixed A fail string if the command does not have help or
* a two elements array containing [0]=>help string,
* [1]=> help string for the accepted cmd args
*/
function getHelp($command)
{
$config = &PEAR_Config::singleton();
$help = @$this->commands[$command]['doc'];
if (empty($help)) {
// XXX (cox) Fallback to summary if there is no doc (show both?)
if (!$help = @$this->commands[$command]['summary']) {
return "No help for command \"$command\"";
}
}
if (preg_match_all('/{config\s+([^\}]+)}/e', $help, $matches)) {
foreach($matches[0] as $k => $v) {
$help = preg_replace("/$v/", $config->get($matches[1][$k]), $help);
}
}
return array($help, $this->getHelpArgs($command));
}
// }}}
// {{{ getHelpArgs()
/**
* Returns the help for the accepted arguments of a command
*
* @param string $command
* @return string The help string
*/
function getHelpArgs($command)
{
if (isset($this->commands[$command]['options']) &&
count($this->commands[$command]['options']))
{
$help = "Options:\n";
foreach ($this->commands[$command]['options'] as $k => $v) {
if (isset($v['arg'])) {
if ($v['arg']{0} == '(') {
$arg = substr($v['arg'], 1, -1);
$sapp = " [$arg]";
$lapp = "[=$arg]";
} else {
$sapp = " $v[arg]";
$lapp = "=$v[arg]";
}
} else {
$sapp = $lapp = "";
}
if (isset($v['shortopt'])) {
$s = $v['shortopt'];
@$help .= " -$s$sapp, --$k$lapp\n";
} else {
@$help .= " --$k$lapp\n";
}
$p = " ";
$doc = rtrim(str_replace("\n", "\n$p", $v['doc']));
$help .= " $doc\n";
}
return $help;
}
return null;
}
// }}}
// {{{ run()
function run($command, $options, $params)
{
$func = @$this->commands[$command]['function'];
if (empty($func)) {
// look for shortcuts
foreach (array_keys($this->commands) as $cmd) {
if (@$this->commands[$cmd]['shortcut'] == $command) {
$command = $cmd;
$func = @$this->commands[$command]['function'];
if (empty($func)) {
return $this->raiseError("unknown command `$command'");
}
break;
}
}
}
return $this->$func($command, $options, $params);
}
// }}}
}
?> | iPark-Media/quickform_legacy | PEAR/Command/Common.php | PHP | lgpl-2.1 | 7,989 |
/*
* Copyright (c) 2002-2005 The RapidSvn Group.
* Copyright (c) 2005-2009 by Rajko Albrecht (ral@alwins-world.de)
* Copyright (c) 2011 Tim Besard <tim.besard@gmail.com>
* All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program (in the file LGPL.txt); if not,
* write to the Free Software Foundation, Inc., 51 Franklin St,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "client.h"
#include "tests/testconfig.h"
#include "repository.h"
#include "repositorylistener.h"
#include "repoparameter.h"
#include "targets.h"
#include "client_parameter.h"
#include "testlistener.h"
#include <iostream>
#include <unistd.h>
#include <qstringlist.h>
class Listener:public svn::repository::RepositoryListener
{
public:
Listener(){}
virtual ~Listener(){}
virtual void sendWarning(const QString&msg)
{
std::cout << msg.toAscii().data() << std::endl;
}
virtual void sendError(const QString&msg)
{
std::cout << msg.toAscii().data() << std::endl;
}
virtual bool isCanceld(){return false;}
};
int main(int,char**)
{
QString p = TESTREPOPATH;
Listener ls;
svn::repository::Repository rp(&ls);
try {
rp.CreateOpen(svn::repository::CreateRepoParameter().path(p).fstype("fsfs"));
} catch (svn::ClientException e) {
QString ex = e.msg();
std::cout << ex.toUtf8().data() << std::endl;
return -1;
}
svn::ContextP m_CurrentContext;
svn::Client* m_Svnclient;
m_Svnclient=svn::Client::getobject(0,0);
TestListener tl;
m_CurrentContext = new svn::Context();
m_CurrentContext->setListener(&tl);
p = "file://"+p;
m_Svnclient->setContext(m_CurrentContext);
QStringList s; s.append(p+"/trunk"); s.append(p+"/branches"); s.append(p+"/tags");
svn::CheckoutParameter cparams;
cparams.moduleName(p).destination(TESTCOPATH).revision(svn::Revision::HEAD).peg(svn::Revision::HEAD).depth(svn::DepthInfinity);
try {
m_Svnclient->mkdir(svn::Targets(s),"Test mkdir");
m_Svnclient->checkout(cparams);
} catch (svn::ClientException e) {
QString ex = e.msg();
std::cout << ex.toUtf8().data() << std::endl;
return -1;
}
return 0;
}
| MIRAvzw/svnqt | src/tests/crepo.cpp | C++ | lgpl-2.1 | 2,849 |
/*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2014 LensKit Contributors. See CONTRIBUTORS.md.
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of the
* License, or (at your option) any later version.
*
* 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 General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.grouplens.lenskit.util;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import java.io.*;
import java.net.URL;
import java.util.Enumeration;
import java.util.Set;
/**
* Directory to look up where classes might be found. It loads lists of classes from
* <tt>META-INF/classes.lst</tt> and exposes them for use in resolving unresolved imports.
*
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
*/
public class ClassDirectory {
/**
* Get a class directory for the current thread's class loader.
* @return A class directory.
*/
public static ClassDirectory forCurrentClassLoader() {
return forClassLoader(Thread.currentThread().getContextClassLoader());
}
/**
* Get a class directory for a specific class loader.
* @param loader The class loader.
* @return The class directory.
*/
public static ClassDirectory forClassLoader(ClassLoader loader) {
ImmutableSetMultimap.Builder<String,String> mapping = ImmutableSetMultimap.builder();
try {
Enumeration<URL> urls = loader.getResources("META-INF/classes.lst");
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
try (InputStream stream = url.openStream();
Reader rdr = new InputStreamReader(stream, Charsets.UTF_8);
BufferedReader buf = new BufferedReader(rdr)) {
String line = buf.readLine();
while (line != null) {
int idx = line.lastIndexOf('.');
if (idx >= 0) {
String name = line.substring(idx + 1);
String pkg = line.substring(0, idx);
mapping.put(name, pkg);
}
line = buf.readLine();
}
}
}
} catch (IOException e) {
throw new RuntimeException("Error loading class lists", e);
}
return new ClassDirectory(mapping.build());
}
private final SetMultimap<String, String> directory;
private ClassDirectory(SetMultimap<String,String> map) {
directory = map;
}
/**
* Get the packages that contain a class with the specified name.
* @param name The name to look for.
* @return The set of packages (empty if the name is unknown).
*/
public Set<String> getPackages(String name) {
return directory.get(name);
}
}
| tajinder-txstate/lenskit | lenskit-core/src/main/java/org/grouplens/lenskit/util/ClassDirectory.java | Java | lgpl-2.1 | 3,639 |
/**
* DSS - Digital Signature Services
* Copyright (C) 2015 European Commission, provided under the CEF programme
*
* This file is part of the "DSS - Digital Signature Services" project.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package eu.europa.esig.dss.cookbook.example.snippets;
import eu.europa.esig.dss.enumerations.DigestAlgorithm;
import eu.europa.esig.dss.model.SignatureValue;
import eu.europa.esig.dss.model.ToBeSigned;
import eu.europa.esig.dss.token.AppleSignatureToken;
import eu.europa.esig.dss.token.DSSPrivateKeyEntry;
import eu.europa.esig.dss.utils.Utils;
import java.util.List;
public class AppleKeychainSnippet {
public static void main(String[] args) {
// tag::demo[]
try (AppleSignatureToken token = new AppleSignatureToken()) {
List<DSSPrivateKeyEntry> keys = token.getKeys();
for (DSSPrivateKeyEntry entry : keys) {
System.out.println(entry.getCertificate().getCertificate());
}
ToBeSigned toBeSigned = new ToBeSigned("Hello world".getBytes());
SignatureValue signatureValue = token.sign(toBeSigned, DigestAlgorithm.SHA256, keys.get(0));
System.out.println("Signature value : " + Utils.toBase64(signatureValue.getValue()));
}
// end::demo[]
}
}
| esig/dss | dss-cookbook/src/test/java/eu/europa/esig/dss/cookbook/example/snippets/AppleKeychainSnippet.java | Java | lgpl-2.1 | 2,023 |
/**
* DSS - Digital Signature Services
* Copyright (C) 2015 European Commission, provided under the CEF programme
*
* This file is part of the "DSS - Digital Signature Services" project.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package eu.europa.esig.dss.asic.xades.validation;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import eu.europa.esig.dss.diagnostic.DiagnosticData;
import eu.europa.esig.dss.diagnostic.SignatureWrapper;
import eu.europa.esig.dss.diagnostic.jaxb.XmlDigestMatcher;
import eu.europa.esig.dss.utils.Utils;
public abstract class AbstractOpenDocumentTestValidation extends AbstractASiCWithXAdESTestValidation {
@Override
protected void checkBLevelValid(DiagnosticData diagnosticData) {
super.checkBLevelValid(diagnosticData);
assertTrue(areManifestAndMimetypeCovered(diagnosticData));
}
private boolean areManifestAndMimetypeCovered(DiagnosticData diagnosticData) {
SignatureWrapper signature = diagnosticData.getSignatureById(diagnosticData.getFirstSignatureId());
assertNotNull(signature);
List<XmlDigestMatcher> digestMatchers = signature.getDigestMatchers();
assertTrue(Utils.isCollectionNotEmpty(digestMatchers));
boolean isManifestCovered = false;
boolean isMimetypeCovered = false;
for (XmlDigestMatcher digestMatcher : digestMatchers) {
if (digestMatcher.getName().contains("manifest.xml")) {
isManifestCovered = true;
} else if (digestMatcher.getName().contains("mimetype")) {
isMimetypeCovered = true;
}
}
return isManifestCovered && isMimetypeCovered;
}
// @Override
// protected void verifyOriginalDocuments(SignedDocumentValidator validator, DiagnosticData diagnosticData) {
// for (AdvancedSignature advancedSignature : validator.getSignatures()) {
// assertTrue(Utils.isCollectionEmpty(validator.getOriginalDocuments(advancedSignature)));
// }
// }
}
| esig/dss | dss-asic-xades/src/test/java/eu/europa/esig/dss/asic/xades/validation/AbstractOpenDocumentTestValidation.java | Java | lgpl-2.1 | 2,662 |
// -*- Mode: Java -*-
//
// DescriptionExtensionIterator.java
/*
+---------------------------- BEGIN LICENSE BLOCK ---------------------------+
| |
| Version: MPL 1.1/GPL 2.0/LGPL 2.1 |
| |
| The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ |
| |
| Software distributed under the License is distributed on an "AS IS" basis, |
| WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License |
| for the specific language governing rights and limitations under the |
| License. |
| |
| The Original Code is the PowerLoom KR&R System. |
| |
| The Initial Developer of the Original Code is |
| UNIVERSITY OF SOUTHERN CALIFORNIA, INFORMATION SCIENCES INSTITUTE |
| 4676 Admiralty Way, Marina Del Rey, California 90292, U.S.A. |
| |
| Portions created by the Initial Developer are Copyright (C) 1997-2012 |
| the Initial Developer. All Rights Reserved. |
| |
| Contributor(s): |
| |
| Alternatively, the contents of this file may be used under the terms of |
| either the GNU General Public License Version 2 or later (the "GPL"), or |
| the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), |
| in which case the provisions of the GPL or the LGPL are applicable instead |
| of those above. If you wish to allow use of your version of this file only |
| under the terms of either the GPL or the LGPL, and not to allow others to |
| use your version of this file under the terms of the MPL, indicate your |
| decision by deleting the provisions above and replace them with the notice |
| and other provisions required by the GPL or the LGPL. If you do not delete |
| the provisions above, a recipient may use your version of this file under |
| the terms of any one of the MPL, the GPL or the LGPL. |
| |
+----------------------------- END LICENSE BLOCK ----------------------------+
*/
package edu.isi.powerloom.logic;
import edu.isi.stella.javalib.Native;
import edu.isi.stella.javalib.StellaSpecialVariable;
import edu.isi.stella.*;
/** Iterates over the extension of a description and
* its subdescriptions, returning those propositions that are currently true.
* @author Stella Java Translator
*/
public class DescriptionExtensionIterator extends Iterator {
public NamedDescription rootDescription;
public Cons subcollections;
public Iterator extensionIterator;
public Proposition referenceProposition;
public List alreadyGeneratedList;
public HashTable alreadyGeneratedTable;
public boolean removingDuplicatesP;
public TruthValue truthValue;
public static DescriptionExtensionIterator newDescriptionExtensionIterator() {
{ DescriptionExtensionIterator self = null;
self = new DescriptionExtensionIterator();
self.firstIterationP = true;
self.value = null;
self.truthValue = null;
self.removingDuplicatesP = false;
self.alreadyGeneratedTable = null;
self.alreadyGeneratedList = List.newList();
self.referenceProposition = null;
self.extensionIterator = null;
self.subcollections = null;
self.rootDescription = null;
return (self);
}
}
public boolean nextP() {
{ DescriptionExtensionIterator self = this;
{ boolean withinqueryP = ((QueryIterator)(Logic.$QUERYITERATOR$.get())) != null;
PatternRecord patternrecord = (withinqueryP ? ((QueryIterator)(Logic.$QUERYITERATOR$.get())).currentPatternRecord : ((PatternRecord)(null)));
int ubstackoffset = (withinqueryP ? (patternrecord.topUnbindingStackOffset + 1) : ((int)(Stella.NULL_INTEGER)));
loop000 : for (;;) {
loop001 : for (;;) {
if (!self.extensionIterator.nextP()) {
break loop001;
}
{ Proposition value = ((Proposition)(self.extensionIterator.value));
if (!(((!value.deletedP()) &&
((((Boolean)(Logic.$REVERSEPOLARITYp$.get())).booleanValue() ? Proposition.falseP(value) : (Proposition.trueP(value) ||
Proposition.functionWithDefinedValueP(value))))) &&
((self.referenceProposition == null) ||
Proposition.argumentsMatchArgumentsP(value, self.referenceProposition)))) {
continue loop001;
}
self.value = value;
self.truthValue = Proposition.propositionTruthValue(value);
if ((self.subcollections != null) &&
(!(self.subcollections == Stella.NIL))) {
self.truthValue = TruthValue.conjoinTruthValues(self.truthValue, ((TruthValue)(((Cons)(self.subcollections.value)).rest.value)));
}
if (!self.removingDuplicatesP) {
return (true);
}
{ Stella_Object instance = (value.arguments.theArray)[0];
if ((self.alreadyGeneratedTable == null) &&
(self.alreadyGeneratedList.length() >= Logic.$DUPLICATEINSTANCESCACHECROSSOVERPOINT$)) {
{ HashTable hashtable = HashTable.newHashTable();
{ Stella_Object m = null;
Cons iter000 = self.alreadyGeneratedList.theConsList;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
m = iter000.value;
hashtable.insertAt(m, m);
}
}
self.alreadyGeneratedTable = hashtable;
}
}
if (self.alreadyGeneratedTable != null) {
if (!(self.alreadyGeneratedTable.lookup(instance) != null)) {
self.alreadyGeneratedTable.insertAt(instance, instance);
return (true);
}
}
else {
if (!self.alreadyGeneratedList.memberP(instance)) {
self.alreadyGeneratedList.push(instance);
return (true);
}
}
if (withinqueryP) {
PatternRecord.unbindVariablesBeginningAt(patternrecord, ubstackoffset);
}
}
}
}
{ Cons subcollections = self.subcollections;
NamedDescription subcollection = null;
if (subcollections == null) {
subcollections = LogicObject.allSupportedNamedSubcollections(self.rootDescription);
}
else {
subcollections = subcollections.rest;
}
loop003 : while (!(subcollections == Stella.NIL)) {
subcollection = ((NamedDescription)(((Cons)(subcollections.value)).value));
if (!NamedDescription.getDescriptionExtension(subcollection, true).emptyP()) {
break loop003;
}
else {
subcollections = subcollections.rest;
}
}
if (subcollection == null) {
break loop000;
}
self.extensionIterator = NamedDescription.allExtensionMembers(subcollection);
self.subcollections = subcollections;
}
}
return (false);
}
}
}
public static Stella_Object accessDescriptionExtensionIteratorSlotValue(DescriptionExtensionIterator self, Symbol slotname, Stella_Object value, boolean setvalueP) {
if (slotname == Logic.SYM_LOGIC_ROOT_DESCRIPTION) {
if (setvalueP) {
self.rootDescription = ((NamedDescription)(value));
}
else {
value = self.rootDescription;
}
}
else if (slotname == Logic.SYM_LOGIC_SUBCOLLECTIONS) {
if (setvalueP) {
self.subcollections = ((Cons)(value));
}
else {
value = self.subcollections;
}
}
else if (slotname == Logic.SYM_LOGIC_EXTENSION_ITERATOR) {
if (setvalueP) {
self.extensionIterator = ((Iterator)(value));
}
else {
value = self.extensionIterator;
}
}
else if (slotname == Logic.SYM_LOGIC_REFERENCE_PROPOSITION) {
if (setvalueP) {
self.referenceProposition = ((Proposition)(value));
}
else {
value = self.referenceProposition;
}
}
else if (slotname == Logic.SYM_LOGIC_ALREADY_GENERATED_LIST) {
if (setvalueP) {
self.alreadyGeneratedList = ((List)(value));
}
else {
value = self.alreadyGeneratedList;
}
}
else if (slotname == Logic.SYM_LOGIC_ALREADY_GENERATED_TABLE) {
if (setvalueP) {
self.alreadyGeneratedTable = ((HashTable)(value));
}
else {
value = self.alreadyGeneratedTable;
}
}
else if (slotname == Logic.SYM_LOGIC_REMOVING_DUPLICATESp) {
if (setvalueP) {
self.removingDuplicatesP = BooleanWrapper.coerceWrappedBooleanToBoolean(((BooleanWrapper)(value)));
}
else {
value = (self.removingDuplicatesP ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER);
}
}
else if (slotname == Logic.SYM_LOGIC_TRUTH_VALUE) {
if (setvalueP) {
self.truthValue = ((TruthValue)(value));
}
else {
value = self.truthValue;
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + slotname + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
return (value);
}
public Surrogate primaryType() {
{ DescriptionExtensionIterator self = this;
return (Logic.SGT_LOGIC_DESCRIPTION_EXTENSION_ITERATOR);
}
}
}
| agentlab/powerloom-osgi | plugins/edu.isi.powerloom/src/edu/isi/powerloom/logic/DescriptionExtensionIterator.java | Java | lgpl-2.1 | 10,966 |
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: JSBSim.cpp
Author: Jon S. Berndt
Date started: 08/17/99
Purpose: Standalone version of JSBSim.
Called by: The USER.
------------- Copyright (C) 1999 Jon S. Berndt (jon@jsbsim.org) -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
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 Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
This class implements the JSBSim standalone application. It is set up for compilation
under gnu C++, MSVC++, or other compiler.
HISTORY
--------------------------------------------------------------------------------
08/17/99 JSB Created
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "initialization/FGTrim.h"
#include "FGFDMExec.h"
#include "input_output/FGXMLFileRead.h"
#if !defined(__GNUC__) && !defined(sgi) && !defined(_MSC_VER)
# include <time>
#else
# include <time.h>
#endif
#if defined(_MSC_VER)
# include <float.h>
#elif defined(__GNUC__) && !defined(sgi)
# include <fenv.h>
#endif
#if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__)
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# include <mmsystem.h>
# include <regstr.h>
# include <sys/types.h>
# include <sys/timeb.h>
#else
# include <sys/time.h>
#endif
#include <iostream>
#include <cstdlib>
using namespace std;
using JSBSim::FGXMLFileRead;
using JSBSim::Element;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DEFINITIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
IDENT(IdSrc,"$Id: JSBSim.cpp,v 1.89 2016/05/20 14:14:05 ehofman Exp $");
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
GLOBAL DATA
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
string RootDir = "";
string ScriptName;
string AircraftName;
string ResetName;
vector <string> LogOutputName;
vector <string> LogDirectiveName;
vector <string> CommandLineProperties;
vector <double> CommandLinePropertyValues;
JSBSim::FGFDMExec* FDMExec;
JSBSim::FGTrim* trimmer;
bool realtime;
bool play_nice;
bool suspend;
bool catalog;
bool nohighlight;
double end_time = 1e99;
double simulation_rate = 1./120.;
bool override_sim_rate = false;
double sleep_period=0.01;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FORWARD DECLARATIONS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
bool options(int, char**);
int real_main(int argc, char* argv[]);
void PrintHelp(void);
#if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__)
double getcurrentseconds(void)
{
struct timeb tm_ptr;
ftime(&tm_ptr);
return tm_ptr.time + tm_ptr.millitm*0.001;
}
#else
double getcurrentseconds(void)
{
struct timeval tval;
struct timezone tz;
gettimeofday(&tval, &tz);
return (tval.tv_sec + tval.tv_usec*1e-6);
}
#endif
#if defined(__BORLANDC__) || defined(_MSC_VER) || defined(__MINGW32__)
void sim_nsleep(long nanosec)
{
Sleep((DWORD)(nanosec*1e-6)); // convert nanoseconds (passed in) to milliseconds for Win32.
}
#else
void sim_nsleep(long nanosec)
{
struct timespec ts, ts1;
ts.tv_sec = 0;
ts.tv_nsec = nanosec;
nanosleep(&ts, &ts1);
}
#endif
/** This class is solely for the purpose of determining what type
of file is given on the command line */
class XMLFile : public FGXMLFileRead {
public:
bool IsScriptFile(std::string filename) {
bool result=false;
Element *document = LoadXMLDocument(filename, false);
if (document && document->GetName() == "runscript") result = true;
ResetParser();
return result;
}
bool IsLogDirectiveFile(std::string filename) {
bool result=false;
Element *document = LoadXMLDocument(filename, false);
if (document && document->GetName() == "output") result = true;
ResetParser();
return result;
}
bool IsAircraftFile(std::string filename) {
bool result=false;
Element* document = LoadXMLDocument(filename, false);
if (document && document->GetName() == "fdm_config") result = true;
ResetParser();
return result;
}
bool IsInitFile(std::string filename) {
bool result=false;
Element *document = LoadXMLDocument(filename, false);
if (document && document->GetName() == "initialize") result = true;
ResetParser();
return result;
}
};
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS DOCUMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
/** \mainpage JSBSim
* An Open Source, Object-Oriented, Cross-Platform Flight Dynamics Model in C++
* \section intro Introduction
*
* JSBSim is an open source, multi-platform, object-oriented flight dynamics
* model (FDM) framework written in the C++ programming language. It is
* designed to support simulation modeling of any aerospace craft without the
* need for specific compiled and linked program code, instead relying on a
* versatile and powerful specification written in an XML format. The format is
* formally known as JSBSim-ML (JSBSim Markup Language).
*
* JSBSim (www.jsbsim.org) was created initially for the open source FlightGear
* flight simulator (www.flightgear.org). JSBSim maintains the ability to run
* as a standalone executable in soft real-time, or batch mode. This is useful
* for running tests or sets of tests automatically using the internal scripting
* capability.
*
* JSBSim does not model specific aircraft in program code. The aircraft itself
* is defined in a file written in an XML-based format
* where the aircraft mass and geometric properties are specified. Additional
* statements define such characteristics as:
*
* - Landing gear location and properties.
* - Pilot eyepoint
* - Additional point masses (passengers, cargo, etc.)
* - Propulsion system (engines, fuel tanks, and "thrusters")
* - Flight control system
* - Autopilot
* - Aerodynamic stability derivatives and coefficients
*
* The configuration file format is set up to be easily comprehensible, for
* instance featuring textbook-like coefficients, which enables newcomers to
* become immediately fluent in describing vehicles, and requiring only prior
* basic theoretical aero knowledge.
*
* One of the more unique features of JSBSim is its method of modeling aircraft
* systems such as a flight control system, autopilot, electrical, etc.
* These are modeled by assembling strings of components that represent filters,
* switches, summers, gains, sensors, and so on.
*
* Another unique feature is displayed in the use of "properties". Properties
* essentially expose chosen variables as nodes in a tree, in a directory-like
* hierarchy. This approach facilitates plugging in different FDMs (Flight Dynamics
* Model) into FlightGear, but it also is a fundamental tool in allowing a wide
* range of aircraft to be modeled, each having its own unique control system,
* aerosurfaces, and flight deck instrument panel. The use of properties allows
* all these items for a craft to be modeled and integrated without the need for
* specific and unique program source code.
*
* The equations of motion are modeled essentially as they are presented in
* aerospace textbooks for the benefit of student users, but quaternions are
* used to track orientation, avoiding "gimbal lock". JSBSim can model the
* atmospheric flight of an aircraft, or the motion of a spacecraft in orbit.
* Coriolis and centripetal accelerations are incorporated into the EOM.
*
* JSBSim can output (log) data in a configurable way. Sets of data that are
* logically related can be selected to be output at a chosen rate, and
* individual properties can be selected for output. The output can be streamed
* to the console, and/or to a file (or files), and/or can be transmitted through a
* socket or sockets, or any combination of the aforementioned methods.
*
* JSBSim has been used in a variety of ways:
*
* - For developing control laws for a sounding rocket
* - For crafting an aircraft autopilot as part of a thesis project
* - As a flight model for FlightGear
* - As an FDM that drives motion base simulators for some
* commercial/entertainment simulators
*
* \section Supported Platforms:
* JSBSim has been built on the following platforms:
*
* - Linux (x86)
* - Windows (MSVC, Cygwin, Mingwin)
* - SGI (native compilers)
* - Mac OS X
* - FreeBSD
*
* \section depends Dependencies
*
* JSBSim has no external dependencies at present. No code is autogenerated.
*
* \section license Licensing
*
* JSBSim is licensed under the terms of the Lesser GPL (LGPL)
*
* \section website Website
*
* For more information, see the JSBSim web site: www.jsbsim.org.
*/
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
int main(int argc, char* argv[])
{
#if defined(_MSC_VER)
_clearfp();
_controlfp(_controlfp(0, 0) & ~(_EM_INVALID | _EM_ZERODIVIDE | _EM_OVERFLOW),
_MCW_EM);
#elif defined(__GNUC__) && !defined(sgi)
feenableexcept(FE_DIVBYZERO | FE_INVALID);
#endif
try {
real_main(argc, argv);
} catch (string& msg) {
std::cerr << "FATAL ERROR: JSBSim terminated with an exception."
<< std::endl << "The message was: " << msg << std::endl;
return 1;
} catch (...) {
std::cerr << "FATAL ERROR: JSBSim terminated with an unknown exception."
<< std::endl;
return 1;
}
return 0;
}
int real_main(int argc, char* argv[])
{
// *** INITIALIZATIONS *** //
ScriptName = "";
AircraftName = "";
ResetName = "";
LogOutputName.clear();
LogDirectiveName.clear();
bool result = false, success;
bool was_paused = false;
double frame_duration;
double new_five_second_value = 0.0;
double actual_elapsed_time = 0;
double initial_seconds = 0;
double current_seconds = 0.0;
double paused_seconds = 0.0;
double sim_lag_time = 0;
double cycle_duration = 0.0;
double override_sim_rate_value = 0.0;
long sleep_nseconds = 0;
realtime = false;
play_nice = false;
suspend = false;
catalog = false;
nohighlight = false;
// *** PARSE OPTIONS PASSED INTO THIS SPECIFIC APPLICATION: JSBSim *** //
success = options(argc, argv);
if (!success) {
PrintHelp();
exit(-1);
}
// *** SET UP JSBSIM *** //
FDMExec = new JSBSim::FGFDMExec();
FDMExec->SetRootDir(RootDir);
FDMExec->SetAircraftPath("aircraft");
FDMExec->SetEnginePath("engine");
FDMExec->SetSystemsPath("systems");
FDMExec->GetPropertyManager()->Tie("simulation/frame_start_time", &actual_elapsed_time);
FDMExec->GetPropertyManager()->Tie("simulation/cycle_duration", &cycle_duration);
if (nohighlight) FDMExec->disableHighLighting();
if (simulation_rate < 1.0 )
FDMExec->Setdt(simulation_rate);
else
FDMExec->Setdt(1.0/simulation_rate);
if (override_sim_rate) override_sim_rate_value = FDMExec->GetDeltaT();
// SET PROPERTY VALUES THAT ARE GIVEN ON THE COMMAND LINE and which are for the simulation only.
for (unsigned int i=0; i<CommandLineProperties.size(); i++) {
if (CommandLineProperties[i].find("simulation") != std::string::npos) {
if (FDMExec->GetPropertyManager()->GetNode(CommandLineProperties[i])) {
FDMExec->SetPropertyValue(CommandLineProperties[i], CommandLinePropertyValues[i]);
}
}
}
// *** OPTION A: LOAD A SCRIPT, WHICH LOADS EVERYTHING ELSE *** //
if (!ScriptName.empty()) {
result = FDMExec->LoadScript(ScriptName, override_sim_rate_value, ResetName);
if (!result) {
cerr << "Script file " << ScriptName << " was not successfully loaded" << endl;
delete FDMExec;
exit(-1);
}
// *** OPTION B: LOAD AN AIRCRAFT AND A SET OF INITIAL CONDITIONS *** //
} else if (!AircraftName.empty() || !ResetName.empty()) {
if (catalog) FDMExec->SetDebugLevel(0);
if ( ! FDMExec->LoadModel( "aircraft",
"engine",
"systems",
AircraftName)) {
cerr << " JSBSim could not be started" << endl << endl;
delete FDMExec;
exit(-1);
}
if (catalog) {
FDMExec->PrintPropertyCatalog();
delete FDMExec;
return 0;
}
JSBSim::FGInitialCondition *IC = FDMExec->GetIC();
if ( ! IC->Load(ResetName)) {
delete FDMExec;
cerr << "Initialization unsuccessful" << endl;
exit(-1);
}
} else {
cout << " No Aircraft, Script, or Reset information given" << endl << endl;
delete FDMExec;
exit(-1);
}
// Load output directives file[s], if given
for (unsigned int i=0; i<LogDirectiveName.size(); i++) {
if (!LogDirectiveName[i].empty()) {
if (!FDMExec->SetOutputDirectives(LogDirectiveName[i])) {
cout << "Output directives not properly set in file " << LogDirectiveName[i] << endl;
delete FDMExec;
exit(-1);
}
}
}
// OVERRIDE OUTPUT FILE NAME. THIS IS USEFUL FOR CASES WHERE MULTIPLE
// RUNS ARE BEING MADE (SUCH AS IN A MONTE CARLO STUDY) AND THE OUTPUT FILE
// NAME MUST BE SET EACH TIME TO AVOID THE PREVIOUS RUN DATA FROM BEING OVER-
// WRITTEN.
for (unsigned int i=0; i<LogOutputName.size(); i++) {
string old_filename = FDMExec->GetOutputFileName(i);
if (!FDMExec->SetOutputFileName(i, LogOutputName[i])) {
cout << "Output filename could not be set" << endl;
} else {
cout << "Output filename change from " << old_filename << " from aircraft"
" configuration file to " << LogOutputName[i] << " specified on"
" command line" << endl;
}
}
// SET PROPERTY VALUES THAT ARE GIVEN ON THE COMMAND LINE
for (unsigned int i=0; i<CommandLineProperties.size(); i++) {
if (!FDMExec->GetPropertyManager()->GetNode(CommandLineProperties[i])) {
cerr << endl << " No property by the name " << CommandLineProperties[i] << endl;
goto quit;
} else {
FDMExec->SetPropertyValue(CommandLineProperties[i], CommandLinePropertyValues[i]);
}
}
FDMExec->RunIC();
// PRINT SIMULATION CONFIGURATION
FDMExec->PrintSimulationConfiguration();
// Dump the simulation state (position, orientation, etc.)
FDMExec->GetPropagate()->DumpState();
if (FDMExec->GetIC()->NeedTrim()) {
trimmer = new JSBSim::FGTrim( FDMExec );
try {
trimmer->DoTrim();
delete trimmer;
} catch (string& msg) {
cerr << endl << msg << endl << endl;
exit(1);
}
}
cout << endl << JSBSim::FGFDMExec::fggreen << JSBSim::FGFDMExec::highint
<< "---- JSBSim Execution beginning ... --------------------------------------------"
<< JSBSim::FGFDMExec::reset << endl << endl;
result = FDMExec->Run(); // MAKE AN INITIAL RUN
if (suspend) FDMExec->Hold();
// Print actual time at start
char s[100];
time_t tod;
time(&tod);
strftime(s, 99, "%A %B %d %Y %X", localtime(&tod));
cout << "Start: " << s << " (HH:MM:SS)" << endl;
frame_duration = FDMExec->GetDeltaT();
if (realtime) sleep_nseconds = (long)(frame_duration*1e9);
else sleep_nseconds = (sleep_period )*1e9; // 0.01 seconds
tzset();
current_seconds = initial_seconds = getcurrentseconds();
// *** CYCLIC EXECUTION LOOP, AND MESSAGE READING *** //
while (result && FDMExec->GetSimTime() <= end_time) {
FDMExec->ProcessMessage(); // Process messages, if any.
// Check if increment then hold is on and take appropriate actions if it is
// Iterate is not supported in realtime - only in batch and playnice modes
FDMExec->CheckIncrementalHold();
// if running realtime, throttle the execution, else just run flat-out fast
// unless "playing nice", in which case sleep for a while (0.01 seconds) each frame.
// If suspended, then don't increment cumulative realtime "stopwatch".
if ( ! FDMExec->Holding()) {
if ( ! realtime ) { // ------------ RUNNING IN BATCH MODE
result = FDMExec->Run();
if (play_nice) sim_nsleep(sleep_nseconds);
} else { // ------------ RUNNING IN REALTIME MODE
// "was_paused" will be true if entering this "run" loop from a paused state.
if (was_paused) {
initial_seconds += paused_seconds;
was_paused = false;
}
current_seconds = getcurrentseconds(); // Seconds since 1 Jan 1970
actual_elapsed_time = current_seconds - initial_seconds; // Real world elapsed seconds since start
sim_lag_time = actual_elapsed_time - FDMExec->GetSimTime(); // How far behind sim-time is from actual
// elapsed time.
for (int i=0; i<(int)(sim_lag_time/frame_duration); i++) { // catch up sim time to actual elapsed time.
result = FDMExec->Run();
cycle_duration = getcurrentseconds() - current_seconds; // Calculate cycle duration
current_seconds = getcurrentseconds(); // Get new current_seconds
if (FDMExec->Holding()) break;
}
if (play_nice) sim_nsleep(sleep_nseconds);
if (FDMExec->GetSimTime() >= new_five_second_value) { // Print out elapsed time every five seconds.
cout << "Simulation elapsed time: " << FDMExec->GetSimTime() << endl;
new_five_second_value += 5.0;
}
}
} else { // Suspended
was_paused = true;
paused_seconds = getcurrentseconds() - current_seconds;
sim_nsleep(sleep_nseconds);
result = FDMExec->Run();
}
}
quit:
// PRINT ENDING CLOCK TIME
time(&tod);
strftime(s, 99, "%A %B %d %Y %X", localtime(&tod));
cout << "End: " << s << " (HH:MM:SS)" << endl;
// CLEAN UP
delete FDMExec;
return 0;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#define gripe cerr << "Option '" << keyword \
<< "' requires a value, as in '" \
<< keyword << "=something'" << endl << endl;/**/
bool options(int count, char **arg)
{
int i;
bool result = true;
if (count == 1) {
PrintHelp();
exit(0);
}
cout.setf(ios_base::fixed);
for (i=1; i<count; i++) {
string argument = string(arg[i]);
string keyword(argument);
string value("");
string::size_type n=argument.find("=");
if (n != string::npos && n > 0) {
keyword = argument.substr(0, n);
value = argument.substr(n+1);
}
if (keyword == "--help") {
PrintHelp();
exit(0);
} else if (keyword == "--version") {
cout << endl << " JSBSim Version: " << FDMExec->GetVersion() << endl << endl;
exit (0);
} else if (keyword == "--realtime") {
realtime = true;
} else if (keyword == "--nice") {
play_nice = true;
if (n != string::npos) {
try {
sleep_period = atof( value.c_str() );
} catch (...) {
cerr << endl << " Invalid sleep period given!" << endl << endl;
result = false;
}
} else {
sleep_period = 0.01;
}
} else if (keyword == "--suspend") {
suspend = true;
} else if (keyword == "--nohighlight") {
nohighlight = true;
} else if (keyword == "--outputlogfile") {
if (n != string::npos) {
LogOutputName.push_back(value);
}
} else if (keyword == "--logdirectivefile") {
if (n != string::npos) {
LogDirectiveName.push_back(value);
} else {
gripe;
exit(1);
}
} else if (keyword == "--root") {
if (n != string::npos) {
RootDir = value;
if (RootDir[RootDir.length()-1] != '/') {
RootDir += '/';
}
} else {
gripe;
exit(1);
}
} else if (keyword == "--aircraft") {
if (n != string::npos) {
AircraftName = value;
} else {
gripe;
exit(1);
}
} else if (keyword == "--script") {
if (n != string::npos) {
ScriptName = value;
} else {
gripe;
exit(1);
}
} else if (keyword == "--initfile") {
if (n != string::npos) {
ResetName = value;
} else {
gripe;
exit(1);
}
} else if (keyword == "--property") {
if (n != string::npos) {
string propName = value.substr(0,value.find("="));
string propValueString = value.substr(value.find("=")+1);
double propValue = atof(propValueString.c_str());
CommandLineProperties.push_back(propName);
CommandLinePropertyValues.push_back(propValue);
} else {
gripe;
exit(1);
}
} else if (keyword.substr(0,5) == "--end") {
if (n != string::npos) {
try {
end_time = atof( value.c_str() );
} catch (...) {
cerr << endl << " Invalid end time given!" << endl << endl;
result = false;
}
} else {
gripe;
exit(1);
}
} else if (keyword == "--simulation-rate") {
if (n != string::npos) {
try {
simulation_rate = atof( value.c_str() );
override_sim_rate = true;
} catch (...) {
cerr << endl << " Invalid simulation rate given!" << endl << endl;
result = false;
}
} else {
gripe;
exit(1);
}
} else if (keyword == "--catalog") {
catalog = true;
if (value.size() > 0) AircraftName=value;
} else if (keyword.substr(0,2) != "--" && value.empty() ) {
// See what kind of files we are specifying on the command line
XMLFile xmlFile;
if (xmlFile.IsScriptFile(keyword)) ScriptName = keyword;
else if (xmlFile.IsLogDirectiveFile(keyword)) LogDirectiveName.push_back(keyword);
else if (xmlFile.IsAircraftFile("aircraft/" + keyword + "/" + keyword)) AircraftName = keyword;
else if (xmlFile.IsInitFile(keyword)) ResetName = keyword;
else if (xmlFile.IsInitFile("aircraft/" + AircraftName + "/" + keyword)) ResetName = keyword;
else {
cerr << "The argument \"" << keyword << "\" cannot be interpreted as a file name or option." << endl;
exit(1);
}
}
else //Unknown keyword so print the help file, the bad keyword and abort
{
PrintHelp();
cerr << "The argument \"" << keyword << "\" cannot be interpreted as a file name or option." << endl;
exit(1);
}
}
// Post-processing for script options. check for incompatible options.
if (catalog && !ScriptName.empty()) {
cerr << "Cannot specify catalog with script option" << endl << endl;
result = false;
}
if (AircraftName.size() > 0 && ResetName.size() == 0 && !catalog) {
cerr << "You must specify an initialization file with the aircraft name." << endl << endl;
result = false;
}
if (ScriptName.size() > 0 && AircraftName.size() > 0) {
cerr << "You cannot specify an aircraft file with a script." << endl;
result = false;
}
return result;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void PrintHelp(void)
{
cout << endl << " JSBSim version " << FDMExec->GetVersion() << endl << endl;
cout << " Usage: jsbsim [script file name] [output file names] <options>" << endl << endl;
cout << " options:" << endl;
cout << " --help returns this message" << endl;
cout << " --version returns the version number" << endl;
cout << " --outputlogfile=<filename> sets (overrides) the name of a data output file" << endl;
cout << " --logdirectivefile=<filename> specifies the name of a data logging directives file" << endl;
cout << " (can appear multiple times)" << endl;
cout << " --root=<path> specifies the JSBSim root directory (where aircraft/, engine/, etc. reside)" << endl;
cout << " --aircraft=<filename> specifies the name of the aircraft to be modeled" << endl;
cout << " --script=<filename> specifies a script to run" << endl;
cout << " --realtime specifies to run in actual real world time" << endl;
cout << " --nice specifies to run at lower CPU usage" << endl;
cout << " --nohighlight specifies that console output should be pure text only (no color)" << endl;
cout << " --suspend specifies to suspend the simulation after initialization" << endl;
cout << " --initfile=<filename> specifies an initilization file" << endl;
cout << " --catalog specifies that all properties for this aircraft model should be printed" << endl;
cout << " (catalog=aircraftname is an optional format)" << endl;
cout << " --property=<name=value> e.g. --property=simulation/integrator/rate/rotational=1" << endl;
cout << " --simulation-rate=<rate (double)> specifies the sim dT time or frequency" << endl;
cout << " If rate specified is less than 1, it is interpreted as" << endl;
cout << " a time step size, otherwise it is assumed to be a rate in Hertz." << endl;
cout << " --end=<time (double)> specifies the sim end time" << endl << endl;
cout << " NOTE: There can be no spaces around the = sign when" << endl;
cout << " an option is followed by a filename" << endl << endl;
}
| pmatigakis/jsbsim | src/JSBSim.cpp | C++ | lgpl-2.1 | 26,538 |
using Signum.Engine;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.Routing;
namespace Signum.React.Filters
{
public class SignumAuthenticationAndProfilerAttribute : FilterAttribute, IAuthorizationFilter
{
public const string SavedRequestKey = "SAVED_REQUEST";
public static Func<HttpActionContext, IDisposable> Authenticate;
public static Func<HttpActionContext, IDisposable> GetCurrentCultures;
public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
string action = ProfilerActionSplitterAttribute.GetActionDescription(actionContext);
using (TimeTracker.Start(action))
{
using (HeavyProfiler.Log("Web.API " + actionContext.Request.Method, () => actionContext.Request.RequestUri.ToString()))
{
//if (ProfilerLogic.SessionTimeout != null)
//{
// IDisposable sessionTimeout = Connector.CommandTimeoutScope(ProfilerLogic.SessionTimeout.Value);
// if (sessionTimeout != null)
// actionContext.Request.RegisterForDispose(sessionTimeout);
//}
actionContext.Request.Properties[SavedRequestKey] = await actionContext.Request.Content.ReadAsStringAsync();
using (Authenticate == null ? null : Authenticate(actionContext))
{
using (GetCurrentCultures(actionContext))
{
if (actionContext.Response != null)
return actionContext.Response;
return await continuation();
}
}
}
}
}
}
} | solaimanjdn/framework | Signum.React/Filters/SignumAuthenticationAndProfilerAttribute.cs | C# | lgpl-3.0 | 2,299 |
// Copyright 2017 The Cayley Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gizmo
import (
"context"
"fmt"
"sort"
"github.com/dop251/goja"
"github.com/cayleygraph/cayley/clog"
"github.com/cayleygraph/cayley/graph"
"github.com/cayleygraph/cayley/graph/iterator"
"github.com/cayleygraph/cayley/quad"
"github.com/cayleygraph/cayley/query"
"github.com/cayleygraph/cayley/voc"
)
const Name = "gizmo"
func init() {
query.RegisterLanguage(query.Language{
Name: Name,
Session: func(qs graph.QuadStore) query.Session {
return NewSession(qs)
},
HTTP: func(qs graph.QuadStore) query.HTTP {
return NewSession(qs)
},
REPL: func(qs graph.QuadStore) query.REPLSession {
return NewSession(qs)
},
})
}
func NewSession(qs graph.QuadStore) *Session {
s := &Session{
ctx: context.Background(),
qs: qs, limit: -1,
}
if err := s.buildEnv(); err != nil {
panic(err)
}
return s
}
type Session struct {
qs graph.QuadStore
vm *goja.Runtime
ns voc.Namespaces
last string
p *goja.Program
out chan query.Result
ctx context.Context
limit int
count int
// used only to collate web results
dataOutput []interface{}
err error
shape map[string]interface{}
}
func (s *Session) context() context.Context {
return s.ctx
}
func (s *Session) buildEnv() error {
if s.vm != nil {
return nil
}
s.vm = goja.New()
s.vm.Set("graph", &graphObject{s: s})
s.vm.Set("g", s.vm.Get("graph"))
for name, val := range defaultEnv {
fnc := val
s.vm.Set(name, func(call goja.FunctionCall) goja.Value {
return fnc(s.vm, call)
})
}
return nil
}
func (s *Session) tagsToValueMap(m map[string]graph.Value) map[string]interface{} {
outputMap := make(map[string]interface{})
for k, v := range m {
if o := quadValueToNative(s.qs.NameOf(v)); o != nil {
outputMap[k] = o
}
}
if len(outputMap) == 0 {
return nil
}
return outputMap
}
func (s *Session) runIteratorToArray(it graph.Iterator, limit int) ([]map[string]interface{}, error) {
ctx := s.context()
output := make([]map[string]interface{}, 0)
err := graph.Iterate(ctx, it).Limit(limit).TagEach(func(tags map[string]graph.Value) {
tm := s.tagsToValueMap(tags)
if tm == nil {
return
}
output = append(output, tm)
})
if err != nil {
return nil, err
}
return output, nil
}
func (s *Session) runIteratorToArrayNoTags(it graph.Iterator, limit int) ([]interface{}, error) {
ctx := s.context()
output := make([]interface{}, 0)
err := graph.Iterate(ctx, it).Paths(false).Limit(limit).EachValue(s.qs, func(v quad.Value) {
if o := quadValueToNative(v); o != nil {
output = append(output, o)
}
})
if err != nil {
return nil, err
}
return output, nil
}
func (s *Session) runIteratorWithCallback(it graph.Iterator, callback goja.Value, this goja.FunctionCall, limit int) error {
fnc, ok := goja.AssertFunction(callback)
if !ok {
return fmt.Errorf("expected js callback function")
}
ctx, cancel := context.WithCancel(s.context())
defer cancel()
var gerr error
err := graph.Iterate(ctx, it).Paths(true).Limit(limit).TagEach(func(tags map[string]graph.Value) {
tm := s.tagsToValueMap(tags)
if tm == nil {
return
}
if _, err := fnc(this.This, s.vm.ToValue(tm)); err != nil {
gerr = err
cancel()
}
})
if gerr != nil {
err = gerr
}
return err
}
func (s *Session) send(ctx context.Context, r *Result) bool {
if s.limit >= 0 && s.count >= s.limit {
return false
}
if s.out == nil {
return false
}
if ctx == nil {
ctx = s.ctx
}
select {
case s.out <- r:
case <-ctx.Done():
return false
}
s.count++
return s.limit < 0 || s.count < s.limit
}
func (s *Session) runIterator(it graph.Iterator) error {
if s.shape != nil {
iterator.OutputQueryShapeForIterator(it, s.qs, s.shape)
return nil
}
ctx, cancel := context.WithCancel(s.context())
defer cancel()
stop := false
err := graph.Iterate(ctx, it).Paths(true).TagEach(func(tags map[string]graph.Value) {
if !s.send(ctx, &Result{Tags: tags}) {
cancel()
stop = true
}
})
if stop {
err = nil
}
return err
}
func (s *Session) countResults(it graph.Iterator) (int64, error) {
if s.shape != nil {
iterator.OutputQueryShapeForIterator(it, s.qs, s.shape)
return 0, nil
}
return graph.Iterate(s.context(), it).Paths(true).Count()
}
type Result struct {
Meta bool
Val interface{}
Tags map[string]graph.Value
}
func (r *Result) Result() interface{} {
if r.Tags != nil {
return r.Tags
}
return r.Val
}
func (r *Result) Err() error { return nil }
func (s *Session) run(qu string) (v goja.Value, err error) {
var p *goja.Program
if s.last == qu && s.last != "" {
p = s.p
} else {
p, err = goja.Compile("", qu, false)
if err != nil {
return
}
s.last, s.p = qu, p
}
v, err = s.vm.RunProgram(p)
if e, ok := err.(*goja.Exception); ok && e.Value() != nil {
if er, ok := e.Value().Export().(error); ok {
err = er
}
}
return v, err
}
func (s *Session) Execute(ctx context.Context, qu string, out chan query.Result, limit int) {
defer close(out)
s.out = out
s.limit = limit
s.count = 0
s.ctx = ctx
done := make(chan struct{})
defer close(done)
go func() {
select {
case <-ctx.Done():
s.vm.Interrupt(ctx.Err())
case <-done:
}
}()
v, err := s.run(qu)
if err != nil {
select {
case <-ctx.Done():
case out <- query.ErrorResult(err):
}
return
}
if !goja.IsNull(v) && !goja.IsUndefined(v) {
s.send(ctx, &Result{Meta: true, Val: v.Export()})
}
}
func (s *Session) FormatREPL(result query.Result) string {
if err := result.Err(); err != nil {
return fmt.Sprintf("error: %v", err)
}
data, ok := result.(*Result)
if !ok {
return fmt.Sprintf("Error: unexpected result type: %T\n", result)
}
if data.Meta {
if data.Val != nil {
s := data.Val
switch s.(type) {
case *pathObject, *graphObject:
s = "[internal Iterator]"
}
return fmt.Sprintln("=>", s)
}
return fmt.Sprintln("=>", nil)
}
var out string
out = fmt.Sprintln("****")
if data.Val == nil {
tags := data.Tags
tagKeys := make([]string, len(tags))
i := 0
for k := range tags {
tagKeys[i] = k
i++
}
sort.Strings(tagKeys)
for _, k := range tagKeys {
if k == "$_" {
continue
}
out += fmt.Sprintf("%s : %s\n", k, quadValueToString(s.qs.NameOf(tags[k])))
}
} else {
switch export := data.Val.(type) {
case map[string]string:
for k, v := range export {
out += fmt.Sprintf("%s : %s\n", k, v)
}
case map[string]interface{}:
for k, v := range export {
out += fmt.Sprintf("%s : %v\n", k, v)
}
default:
out += fmt.Sprintf("%s\n", data.Val)
}
}
return out
}
// Web stuff
func (s *Session) ShapeOf(qu string) (interface{}, error) {
s.shape = make(map[string]interface{})
_, err := s.run(qu)
out := s.shape
s.shape = nil
return out, err
}
func (s *Session) Collate(result query.Result) {
if err := result.Err(); err != nil {
s.err = err
return
}
data, ok := result.(*Result)
if !ok {
clog.Errorf("unexpected result type: %T", result)
return
} else if data.Meta {
return
}
if data.Val != nil {
s.dataOutput = append(s.dataOutput, data.Val)
return
}
obj := make(map[string]interface{})
tags := data.Tags
var tagKeys []string
for k := range tags {
tagKeys = append(tagKeys, k)
}
sort.Strings(tagKeys)
for _, k := range tagKeys {
if name := s.qs.NameOf(tags[k]); name != nil {
obj[k] = quadValueToNative(name)
} else {
delete(obj, k)
}
}
if len(obj) != 0 {
s.dataOutput = append(s.dataOutput, obj)
}
}
func (s *Session) Results() (interface{}, error) {
defer s.Clear()
if s.err != nil {
return nil, s.err
}
return s.dataOutput, nil
}
func (s *Session) Clear() {
s.dataOutput = nil
}
| meta-network/go-meta | vendor/github.com/cayleygraph/cayley/query/gizmo/gizmo.go | GO | lgpl-3.0 | 8,256 |
<?php
namespace Crell\Transformer\Tests;
class TestA {
const CLASSNAME = __CLASS__;
} | Crell/Transformer | tests/TestA.php | PHP | lgpl-3.0 | 92 |
<?php namespace QueueIT\Security;
require_once('IValidateResultRepository.php');
require_once('ValidateResultRepositoryBase.php');
require_once('SessionStateModel.php');
require_once('AcceptedConfirmedResult.php');
require_once('Md5KnownUser.php');
require_once('Queue.php');
require_once('IQueue.php');
class SessionValidateResultRepository extends ValidateResultRepositoryBase
{
static function reset($loadConfiguration = false)
{
global $idleExpiration;
global $extendValidity;
$idleExpiration = 180;
if (!$loadConfiguration)
return;
$iniFileName = $_SERVER['DOCUMENT_ROOT'] . "\queueit.ini";
if (!file_exists($iniFileName))
return;
$settings_array = parse_ini_file($iniFileName, true);
if (!$settings_array)
return;
$settings = $settings_array['settings'];
if ($settings == null)
return;
if (isset($settings['$idleExpiration']) && $settings['$idleExpiration'] != null)
$idleExpiration = (int)$settings['$idleExpiration'];
if (isset($settings['extendValidity']))
$extendValidity = $settings['extendValidity'] == 1 ? true : false;
}
public static function configure(
$idleExpirationValue = null,
$extendValidityValue = null)
{
global $idleExpiration;
global $extendValidity;
if ($idleExpirationValue != null)
$idleExpiration = $idleExpirationValue;
if ($extendValidityValue != null)
$extendValidity = $extendValidityValue;
}
public function getValidationResult($queue)
{
$key = $this->generateKey($queue->getCustomerId(), $queue->getEventId());
if (!isset($_SESSION[$key]))
return null;
$model = unserialize($_SESSION[$key]);
if ($model->expiration != null && $model->expiration < time())
return null;
$result = new AcceptedConfirmedResult(
$queue,
new Md5KnownUser(
$model->queueId,
$model->placeInQueue,
$model->timeStamp,
$queue->getCustomerId(),
$queue->getEventId(),
$model->redirectType,
$model->originalUrl),
false);
return $result;
}
public function setValidationResult($queue, $validationResult, $expirationTime = null)
{
global $idleExpiration;
global $extendValidity;
if ($validationResult instanceof AcceptedConfirmedResult)
{
if ($expirationTime != null)
$expiration = $expirationTime;
elseif ($validationResult->getKnownUser()->getRedirectType() == RedirectType::Idle)
$expiration = time() + idleExpiration;
elseif ($extendValidity == false)
$expiration = time() + ini_get("session.gc_maxlifetime");
else
$expiration = null;
$model = new SessionStateModel();
$model->queueId = $validationResult->getKnownUser()->getQueueId();
$model->originalUrl = $validationResult->getKnownUser()->getOriginalUrl();
$model->timeStamp = $validationResult->getKnownUser()->getTimeStamp();
$model->redirectType = $validationResult->getKnownUser()->getRedirectType();
$model->placeInQueue = $validationResult->getKnownUser()->getPlaceInQueue();
$model->expiration = $expiration;
$key = $this->generateKey($queue->getCustomerId(), $queue->getEventId());
$_SESSION[$key] = serialize($model);
}
}
public function cancel($queue, $validationResult)
{
$key = $this->generateKey($queue->getCustomerId(), $queue->getEventId());
$_SESSION[$key] = null;
}
}
SessionValidateResultRepository::reset(true);
?>
| queueit/QueueIT.Security-Php | QueueIT.Security/SessionValidateResultRepository.php | PHP | lgpl-3.0 | 3,321 |
/**
* DataCleaner (community edition)
* Copyright (C) 2014 Neopost - Customer Information Management
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.datacleaner.monitor.scheduling.command;
import org.datacleaner.monitor.shared.model.JobIdentifier;
import org.datacleaner.monitor.shared.model.TenantIdentifier;
import org.datacleaner.monitor.shared.widgets.DCPopupPanel;
import org.datacleaner.monitor.util.DCRequestBuilder;
import org.datacleaner.monitor.util.DCRequestCallback;
import org.datacleaner.monitor.util.Urls;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
public class DeleteJobCommand implements Command {
private TenantIdentifier _tenant;
private JobIdentifier _job ;
private DCPopupPanel _morePopup;
public DeleteJobCommand(TenantIdentifier tenant,JobIdentifier jobIdentifier, DCPopupPanel morePopup) {
_tenant = tenant;
_job = jobIdentifier;
_morePopup = morePopup;
}
@Override
public void execute() {
_morePopup.hide();
boolean delete = Window.confirm("Are you sure you want to delete the job '" + _job.getName()
+ "' and related schedule, results and timelines.");
if (delete) {
final String url = Urls.createRepositoryUrl(_tenant, "jobs/" + _job.getName() + ".delete");
final DCRequestBuilder requestBuilder = new DCRequestBuilder(RequestBuilder.POST, url);
requestBuilder.setHeader("Content-Type", "application/json");
requestBuilder.send("", new DCRequestCallback() {
@Override
protected void onSuccess(Request request, Response response) {
Window.Location.reload();
}
});
}
}
}
| anandswarupv/DataCleaner | monitor/widgets/src/main/java/org/datacleaner/monitor/scheduling/command/DeleteJobCommand.java | Java | lgpl-3.0 | 2,577 |
const DEPLOYMENT_TYPE_COSTS = {
kubernetes_custom: 95000,
kubernetes_existing: 0,
kubernetes_reference: 45000,
openstack_custom: 150000,
openstack_existing: 0,
openstack_reference: 75000
};
const MANAGED_SERVICE_COSTS = {
maas: 300,
openstack: 4275,
kubernetes: 3250,
openstack_and_kubernetes: 6465
};
const SERVICE_LEVEL_COST_PER_HOST = {
none: 0,
essential: 225,
standard: 750,
advanced: 1500
};
const STORAGE_COSTS = {
standard: {
tier_one: { base: 0, multiplier: 16.67 },
tier_two: { base: 2500, multiplier: 12.5 },
tier_three: { base: 19375, multiplier: 6.67 },
tier_four: { base: 29375, multiplier: 3.33 },
tier_five: { base: 69375, multiplier: 1.67 },
tier_six: { base: 94375, multiplier: 0 }
},
advanced: {
tier_one: { base: 0, multiplier: 33.33 },
tier_two: { base: 5000, multiplier: 25 },
tier_three: { base: 38750, multiplier: 13.33 },
tier_four: { base: 58750, multiplier: 6.67 },
tier_five: { base: 138750, multiplier: 3.33 },
tier_six: { base: 188750, multiplier: 0 }
}
};
function initTCOCalculator() {
updateTotals();
attachInputEvents();
}
function attachInputEvents() {
const rangeContainers = document.querySelectorAll(
".js-tco-calculator__range"
);
const checkboxInputs = document.querySelectorAll(
".js-tco-calculator__checkbox"
);
const radioInputs = document.querySelectorAll(".js-tco-calculator__radio");
rangeContainers.forEach(container => {
let input = container.querySelector("input[type='number']");
let range = container.querySelector("input[type='range']");
input.addEventListener("input", e => {
range.value = e.target.value;
updateTotals();
});
range.addEventListener("input", e => {
input.value = e.target.value;
updateTotals();
});
});
checkboxInputs.forEach(checkbox => {
checkbox.addEventListener("input", () => {
updateTotals();
});
});
radioInputs.forEach(radio => {
radio.addEventListener("input", () => {
updateTotals();
});
});
}
function calculateStorageCost(serviceLevel, dataVolume) {
let tier = "tier_";
let adjustment = 0;
if (dataVolume <= 150) {
tier += "one";
} else if (dataVolume > 150 && dataVolume <= 1500) {
tier += "two";
adjustment = 150;
} else if (dataVolume > 1500 && dataVolume <= 3000) {
tier += "three";
adjustment = 1500;
} else if (dataVolume > 3000 && dataVolume <= 15000) {
tier += "four";
adjustment = 3000;
} else if (dataVolume > 15000 && dataVolume <= 30000) {
tier += "five";
adjustment = 15000;
} else if (dataVolume > 30000) {
tier += "six";
adjustment = 30000;
}
const storageCosts = STORAGE_COSTS[serviceLevel][tier];
const adjustedVolume = dataVolume - adjustment;
const finalCosts =
storageCosts.base + adjustedVolume * storageCosts.multiplier;
return finalCosts;
}
function renderTotals(rollout, yearly, selfYearly) {
const rolloutEl = document.querySelector("#intial-rollout--managed");
const selfRolloutEl = document.querySelector("#intial-rollout--self");
const yearlyEl = document.querySelector("#yearly-cost--managed");
const selfYearlyEl = document.querySelector("#yearly-cost--self");
const formattedRollout = `$${new Intl.NumberFormat("en-US").format(rollout)}`;
const formattedYearly = `$${new Intl.NumberFormat("en-US").format(yearly)}`;
const formattedSelfYearly = `$${new Intl.NumberFormat("en-US").format(
selfYearly
)}`;
rolloutEl.innerHTML = formattedRollout;
selfRolloutEl.innerHTML = formattedRollout;
yearlyEl.innerHTML = formattedYearly;
selfYearlyEl.innerHTML = formattedSelfYearly;
}
function updateTotals() {
const dataVolume = parseInt(
document.querySelector("#data-volume__input").value
);
const deploymentType = document.querySelector(
"[name='deployment-type']:checked"
).value;
const hosts = parseInt(document.querySelector("#hosts__input").value)-3;
const kubernetes = document.querySelector("#ct-k8s");
const kubernetesDeploymentCost =
DEPLOYMENT_TYPE_COSTS[`kubernetes_${deploymentType}`];
const openstack = document.querySelector("#ct-openstack");
const openstackDeploymentCost =
DEPLOYMENT_TYPE_COSTS[`openstack_${deploymentType}`];
const serviceLevel = document.querySelector("[name='self-managed']:checked")
.value;
// an additional 3 hosts are required to host MAAS, Juju, etc
const hostCost = SERVICE_LEVEL_COST_PER_HOST[serviceLevel] * (hosts + 3);
const maasHostCost = MANAGED_SERVICE_COSTS["maas"] * 3;
const managedSupportCost =
SERVICE_LEVEL_COST_PER_HOST["advanced"] * (hosts + 3);
let managedServicesCost = 0;
let rollout = 0;
let selfYearly = 0;
let storageCost = 0;
let yearly = 0;
if (
dataVolume / hosts > 48 &&
serviceLevel !== "none" &&
serviceLevel !== "essential"
) {
storageCost += calculateStorageCost(serviceLevel, dataVolume);
}
if (openstack.checked && kubernetes.checked) {
rollout += kubernetesDeploymentCost + openstackDeploymentCost;
managedServicesCost +=
hosts * MANAGED_SERVICE_COSTS["openstack_and_kubernetes"];
} else if (openstack.checked) {
rollout += openstackDeploymentCost;
managedServicesCost += hosts * MANAGED_SERVICE_COSTS["openstack"];
} else if (kubernetes.checked) {
rollout += kubernetesDeploymentCost;
managedServicesCost += hosts * MANAGED_SERVICE_COSTS["kubernetes"];
}
if (openstack.checked || kubernetes.checked) {
yearly +=
managedServicesCost + managedSupportCost + storageCost + maasHostCost;
selfYearly += hostCost + storageCost;
}
renderTotals(rollout, yearly, selfYearly);
}
window.addEventListener("DOMContentLoaded", () => {
const calculator = document.querySelector(".js-tco-calculator");
if (calculator) {
initTCOCalculator();
}
});
| barrymcgee/www.ubuntu.com | static/js/src/tco-calculator.js | JavaScript | lgpl-3.0 | 5,881 |
package me.sd5.billboard;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
/**
*
* @author sd5
*
* The config contains all
* changeable settings.
* Loads/Saves from/to
* the config file on the hard disk.
*
*/
public class Config {
private static FileConfiguration config;
private static File configFile;
public static int maxBillboardLength;
public static int maxPlayerAdvertising;
public static int pageSize;
public static String dateFormat;
public static String mySqlHost;
public static String mySqlPort;
public static String mySqlUsername;
public static String mySqlPassword;
public static String mySqlDatabase;
public static String mySqlTable;
/**
* Loads the config from the hard disk.
*/
public static void load() {
if(configFile == null) {
configFile = new File(BBMain.p.getDataFolder(), "config.yml");
if(! (configFile.exists())) {
Bukkit.getLogger().log(Level.INFO, "Config doesn't exist. Creating new one with default values.");
}
}
config = YamlConfiguration.loadConfiguration(configFile);
//Look for defaults in the jar.
InputStream is = BBMain.p.getResource("config.yml");
if(is != null) {
YamlConfiguration defaultConfig = YamlConfiguration.loadConfiguration(is);
config.setDefaults(defaultConfig);
config.options().copyDefaults(true);
}
save();
//Load values from config.
ConfigurationSection settings = config.getConfigurationSection("settings");
maxBillboardLength = settings.getInt("max-billboard-length");
maxPlayerAdvertising = settings.getInt("max-player-advertising");
pageSize = settings.getInt("page-size");
dateFormat = settings.getString("date-format");
ConfigurationSection mySql = config.getConfigurationSection("my-sql");
mySqlHost = mySql.getString("host");
mySqlPort = mySql.getString("port");
mySqlUsername = mySql.getString("username");
mySqlPassword = mySql.getString("password");
mySqlDatabase = mySql.getString("database");
mySqlTable = mySql.getString("table");
}
/**
* Saves the config to the hard disk.
*/
public static void save() {
if(config == null || configFile == null) {
return;
}
try {
config.save(configFile);
} catch(IOException e) {
Bukkit.getLogger().log(Level.SEVERE, "Could not save config to " + configFile, e);
}
}
}
| sd5/BillBoard | src/me/sd5/billboard/Config.java | Java | lgpl-3.0 | 2,584 |
/*
* Copyright (c) NoticeDog 2017.
* GNU LESSER GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*
*
* This version of the GNU Lesser General Public License incorporates
* the terms and conditions of version 3 of the GNU General Public
* License, supplemented by the additional permissions listed below.
*
* 0. Additional Definitions.
*
* As used herein, "this License" refers to version 3 of the GNU Lesser
* General Public License, and the "GNU GPL" refers to version 3 of the GNU
* General Public License.
*
* "The Library" refers to a covered work governed by this License,
* other than an Application or a Combined Work as defined below.
*
* An "Application" is any work that makes use of an interface provided
* by the Library, but which is not otherwise based on the Library.
* Defining a subclass of a class defined by the Library is deemed a mode
* of using an interface provided by the Library.
*
* A "Combined Work" is a work produced by combining or linking an
* Application with the Library. The particular version of the Library
* with which the Combined Work was made is also called the "Linked
* Version".
*
* The "Minimal Corresponding Source" for a Combined Work means the
* Corresponding Source for the Combined Work, excluding any source code
* for portions of the Combined Work that, considered in isolation, are
* based on the Application, and not on the Linked Version.
*
* The "Corresponding Application Code" for a Combined Work means the
* object code and/or source code for the Application, including any data
* and utility programs needed for reproducing the Combined Work from the
* Application, but excluding the System Libraries of the Combined Work.
*
* 1. Exception to Section 3 of the GNU GPL.
*
* You may convey a covered work under sections 3 and 4 of this License
* without being bound by section 3 of the GNU GPL.
*
* 2. Conveying Modified Versions.
*
* If you modify a copy of the Library, and, in your modifications, a
* facility refers to a function or data to be supplied by an Application
* that uses the facility (other than as an argument passed when the
* facility is invoked), then you may convey a copy of the modified
* version:
*
* a) under this License, provided that you make a good faith effort to
* ensure that, in the event an Application does not supply the
* function or data, the facility still operates, and performs
* whatever part of its purpose remains meaningful, or
*
* b) under the GNU GPL, with none of the additional permissions of
* this License applicable to that copy.
*
* 3. Object Code Incorporating Material from Library Header Files.
*
* The object code form of an Application may incorporate material from
* a header file that is part of the Library. You may convey such object
* code under terms of your choice, provided that, if the incorporated
* material is not limited to numerical parameters, data structure
* layouts and accessors, or small macros, inline functions and templates
* (ten or fewer lines in length), you do both of the following:
*
* a) Give prominent notice with each copy of the object code that the
* Library is used in it and that the Library and its use are
* covered by this License.
*
* b) Accompany the object code with a copy of the GNU GPL and this license
* document.
*
* 4. Combined Works.
*
* You may convey a Combined Work under terms of your choice that,
* taken together, effectively do not restrict modification of the
* portions of the Library contained in the Combined Work and reverse
* engineering for debugging such modifications, if you also do each of
* the following:
*
* a) Give prominent notice with each copy of the Combined Work that
* the Library is used in it and that the Library and its use are
* covered by this License.
*
* b) Accompany the Combined Work with a copy of the GNU GPL and this license
* document.
*
* c) For a Combined Work that displays copyright notices during
* execution, include the copyright notice for the Library among
* these notices, as well as a reference directing the user to the
* copies of the GNU GPL and this license document.
*
* d) Do one of the following:
*
* 0) Convey the Minimal Corresponding Source under the terms of this
* License, and the Corresponding Application Code in a form
* suitable for, and under terms that permit, the user to
* recombine or relink the Application with a modified version of
* the Linked Version to produce a modified Combined Work, in the
* manner specified by section 6 of the GNU GPL for conveying
* Corresponding Source.
*
* 1) Use a suitable shared library mechanism for linking with the
* Library. A suitable mechanism is one that (a) uses at run time
* a copy of the Library already present on the user's computer
* system, and (b) will operate properly with a modified version
* of the Library that is interface-compatible with the Linked
* Version.
*
* e) Provide Installation Information, but only if you would otherwise
* be required to provide such information under section 6 of the
* GNU GPL, and only to the extent that such information is
* necessary to install and execute a modified version of the
* Combined Work produced by recombining or relinking the
* Application with a modified version of the Linked Version. (If
* you use option 4d0, the Installation Information must accompany
* the Minimal Corresponding Source and Corresponding Application
* Code. If you use option 4d1, you must provide the Installation
* Information in the manner specified by section 6 of the GNU GPL
* for conveying Corresponding Source.)
*
* 5. Combined Libraries.
*
* You may place library facilities that are a work based on the
* Library side by side in a single library together with other library
* facilities that are not Applications and are not covered by this
* License, and convey such a combined library under terms of your
* choice, if you do both of the following:
*
* a) Accompany the combined library with a copy of the same work based
* on the Library, uncombined with any other library facilities,
* conveyed under the terms of this License.
*
* b) Give prominent notice with the combined library that part of it
* is a work based on the Library, and explaining where to find the
* accompanying uncombined form of the same work.
*
* 6. Revised Versions of the GNU Lesser General Public License.
*
* The Free Software Foundation may publish revised and/or new versions
* of the GNU Lesser General Public License from time to time. Such new
* versions will be similar in spirit to the present version, but may
* differ in detail to address new problems or concerns.
*
* Each version is given a distinguishing version number. If the
* Library as you received it specifies that a certain numbered version
* of the GNU Lesser General Public License "or any later version"
* applies to it, you have the option of following the terms and
* conditions either of that published version or of any later version
* published by the Free Software Foundation. If the Library as you
* received it does not specify a version number of the GNU Lesser
* General Public License, you may choose any version of the GNU Lesser
* General Public License ever published by the Free Software Foundation.
*
* If the Library as you received it specifies that a proxy can decide
* whether future versions of the GNU Lesser General Public License shall
* apply, that proxy's public statement of acceptance of any version is
* permanent authorization for you to choose that version for the
* Library.
*/
package io.bunnyblue.noticedog.app.apps;
import android.app.PendingIntent;
import android.content.Context;
import android.graphics.Bitmap;
import java.util.ArrayList;
import java.util.List;
import io.bunnyblue.noticedog.app.R;
import io.bunnyblue.noticedog.app.apps.templates.InputFormatBuilder;
import io.bunnyblue.noticedog.app.apps.templates.MessageProcessor;
import io.bunnyblue.noticedog.app.apps.templates.MessageProcessorBuilder;
import io.bunnyblue.noticedog.app.apps.templates.OutputFormatBuilder;
import io.bunnyblue.noticedog.app.inbox.RawMessage;
import io.bunnyblue.noticedog.app.notifications.Notification;
import io.bunnyblue.noticedog.app.notifications.NotificationProcessor;
import io.bunnyblue.noticedog.app.notifications.NotificationProcessorResult;
public class QQIApp extends BaseApp implements NotificationProcessor {
public static final String PACKAGE_NAME = "com.tencent.qqi";
List<MessageProcessor> messageProcessors;
@Override
public void start(Context context) {
super.start(context);
this.messageProcessors = new ArrayList();
if (isAppInstalled()) {
initMessageProcessors();
}
}
@Override
public void stop() {
this.messageProcessors = null;
super.stop();
}
@Override
public String getAppId() {
return PACKAGE_NAME;
}
@Override
public boolean shouldHandleNotification(Notification n) {
return (!n.getPackageName().equals(PACKAGE_NAME) || n.getTickerText() == null || n.getTickerText().equals("") || n
.getTickerText().length() == 0) ? false : true;
}
@Override
public NotificationProcessorResult processNotification(Notification n) {
String tickerText = n.getTickerText();
MessageProcessor.Result result = null;
for (MessageProcessor messageProcessor : this.messageProcessors) {
result = messageProcessor.processMessage(tickerText);
if (result.matches()) {
break;
}
}
String from = result.getOutputForKey("from");
String messageBody = result.getOutputForKey("message");
if (from == null || messageBody == null) {
return null;
}
long timestamp = n.getWhen();
PendingIntent pendingLaunchIntent = n.getPendingLaunchIntent();
List actions = n.getActions();
Bitmap profilePhoto = null;
if (shouldUseAsProfilePhoto(n.getExpandedLargeIconBig())) {
profilePhoto = n.getExpandedLargeIconBig();
} else if (shouldUseAsProfilePhoto(n.getLargeIcon())) {
profilePhoto = n.getLargeIcon();
}
return new NotificationProcessorResult(new RawMessage(n.getPackageName(), null, from, messageBody, timestamp,
profilePhoto, pendingLaunchIntent, actions), true);
}
void initMessageProcessors() {
addTransform(new MessageProcessorBuilder()
.setInputFormat(
new InputFormatBuilder().setCanonicalInputTemplate("%1$s: %2$s").labelToken(1, "sender")
.labelToken(2, "message").build(this.context))
.addOutputFormat(
"from",
new OutputFormatBuilder().setOutputTemplateFromResouce(R.string.entry_of_from).build(
this.context))
.addOutputFormat(
"message",
new OutputFormatBuilder().setOutputTemplateFromResouce(R.string.entry_of_message_text).build(
this.context)).build(this.context));
}
void addTransform(MessageProcessor t) {
if (t != null) {
this.messageProcessors.add(t);
}
}
}
| bunnyblue/NoticeDog | app/src/main/java/io/bunnyblue/noticedog/app/apps/QQIApp.java | Java | lgpl-3.0 | 11,656 |
/*
* Copyright (c) NoticeDog 2017.
* GNU LESSER GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
* Everyone is permitted to copy and distribute verbatim copies
* of this license document, but changing it is not allowed.
*
*
* This version of the GNU Lesser General Public License incorporates
* the terms and conditions of version 3 of the GNU General Public
* License, supplemented by the additional permissions listed below.
*
* 0. Additional Definitions.
*
* As used herein, "this License" refers to version 3 of the GNU Lesser
* General Public License, and the "GNU GPL" refers to version 3 of the GNU
* General Public License.
*
* "The Library" refers to a covered work governed by this License,
* other than an Application or a Combined Work as defined below.
*
* An "Application" is any work that makes use of an interface provided
* by the Library, but which is not otherwise based on the Library.
* Defining a subclass of a class defined by the Library is deemed a mode
* of using an interface provided by the Library.
*
* A "Combined Work" is a work produced by combining or linking an
* Application with the Library. The particular version of the Library
* with which the Combined Work was made is also called the "Linked
* Version".
*
* The "Minimal Corresponding Source" for a Combined Work means the
* Corresponding Source for the Combined Work, excluding any source code
* for portions of the Combined Work that, considered in isolation, are
* based on the Application, and not on the Linked Version.
*
* The "Corresponding Application Code" for a Combined Work means the
* object code and/or source code for the Application, including any data
* and utility programs needed for reproducing the Combined Work from the
* Application, but excluding the System Libraries of the Combined Work.
*
* 1. Exception to Section 3 of the GNU GPL.
*
* You may convey a covered work under sections 3 and 4 of this License
* without being bound by section 3 of the GNU GPL.
*
* 2. Conveying Modified Versions.
*
* If you modify a copy of the Library, and, in your modifications, a
* facility refers to a function or data to be supplied by an Application
* that uses the facility (other than as an argument passed when the
* facility is invoked), then you may convey a copy of the modified
* version:
*
* a) under this License, provided that you make a good faith effort to
* ensure that, in the event an Application does not supply the
* function or data, the facility still operates, and performs
* whatever part of its purpose remains meaningful, or
*
* b) under the GNU GPL, with none of the additional permissions of
* this License applicable to that copy.
*
* 3. Object Code Incorporating Material from Library Header Files.
*
* The object code form of an Application may incorporate material from
* a header file that is part of the Library. You may convey such object
* code under terms of your choice, provided that, if the incorporated
* material is not limited to numerical parameters, data structure
* layouts and accessors, or small macros, inline functions and templates
* (ten or fewer lines in length), you do both of the following:
*
* a) Give prominent notice with each copy of the object code that the
* Library is used in it and that the Library and its use are
* covered by this License.
*
* b) Accompany the object code with a copy of the GNU GPL and this license
* document.
*
* 4. Combined Works.
*
* You may convey a Combined Work under terms of your choice that,
* taken together, effectively do not restrict modification of the
* portions of the Library contained in the Combined Work and reverse
* engineering for debugging such modifications, if you also do each of
* the following:
*
* a) Give prominent notice with each copy of the Combined Work that
* the Library is used in it and that the Library and its use are
* covered by this License.
*
* b) Accompany the Combined Work with a copy of the GNU GPL and this license
* document.
*
* c) For a Combined Work that displays copyright notices during
* execution, include the copyright notice for the Library among
* these notices, as well as a reference directing the user to the
* copies of the GNU GPL and this license document.
*
* d) Do one of the following:
*
* 0) Convey the Minimal Corresponding Source under the terms of this
* License, and the Corresponding Application Code in a form
* suitable for, and under terms that permit, the user to
* recombine or relink the Application with a modified version of
* the Linked Version to produce a modified Combined Work, in the
* manner specified by section 6 of the GNU GPL for conveying
* Corresponding Source.
*
* 1) Use a suitable shared library mechanism for linking with the
* Library. A suitable mechanism is one that (a) uses at run time
* a copy of the Library already present on the user's computer
* system, and (b) will operate properly with a modified version
* of the Library that is interface-compatible with the Linked
* Version.
*
* e) Provide Installation Information, but only if you would otherwise
* be required to provide such information under section 6 of the
* GNU GPL, and only to the extent that such information is
* necessary to install and execute a modified version of the
* Combined Work produced by recombining or relinking the
* Application with a modified version of the Linked Version. (If
* you use option 4d0, the Installation Information must accompany
* the Minimal Corresponding Source and Corresponding Application
* Code. If you use option 4d1, you must provide the Installation
* Information in the manner specified by section 6 of the GNU GPL
* for conveying Corresponding Source.)
*
* 5. Combined Libraries.
*
* You may place library facilities that are a work based on the
* Library side by side in a single library together with other library
* facilities that are not Applications and are not covered by this
* License, and convey such a combined library under terms of your
* choice, if you do both of the following:
*
* a) Accompany the combined library with a copy of the same work based
* on the Library, uncombined with any other library facilities,
* conveyed under the terms of this License.
*
* b) Give prominent notice with the combined library that part of it
* is a work based on the Library, and explaining where to find the
* accompanying uncombined form of the same work.
*
* 6. Revised Versions of the GNU Lesser General Public License.
*
* The Free Software Foundation may publish revised and/or new versions
* of the GNU Lesser General Public License from time to time. Such new
* versions will be similar in spirit to the present version, but may
* differ in detail to address new problems or concerns.
*
* Each version is given a distinguishing version number. If the
* Library as you received it specifies that a certain numbered version
* of the GNU Lesser General Public License "or any later version"
* applies to it, you have the option of following the terms and
* conditions either of that published version or of any later version
* published by the Free Software Foundation. If the Library as you
* received it does not specify a version number of the GNU Lesser
* General Public License, you may choose any version of the GNU Lesser
* General Public License ever published by the Free Software Foundation.
*
* If the Library as you received it specifies that a proxy can decide
* whether future versions of the GNU Lesser General Public License shall
* apply, that proxy's public statement of acceptance of any version is
* permanent authorization for you to choose that version for the
* Library.
*/
package io.bunnyblue.noticedog.app.apps.templates;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class MessageProcessor {
public static final String DEFAULT_INPUT_KEY = "default";
private static final String TAG = "MessageProcessor";
Map<String, InputFormat> inputFormatMap;
Map<String, OutputFormat> outputFormatMap;
public static MessageProcessor newInstance(Map<String, InputFormat> inputFormatMap, Map<String, OutputFormat> outputFormatMap) {
if (inputFormatMap == null) {
Log.d(TAG, "InputFormatMap is null");
return null;
} else if (inputFormatMap.size() == 0) {
Log.d(TAG, "zero input formats specified");
return null;
} else {
for (InputFormat inputFormat : inputFormatMap.values()) {
if (inputFormat == null) {
Log.d(TAG, "found null input format");
return null;
}
}
MessageProcessor messageProcessor = new MessageProcessor();
messageProcessor.inputFormatMap = inputFormatMap;
messageProcessor.outputFormatMap = outputFormatMap;
return messageProcessor;
}
}
public Result processMessage(String input) {
Map inputs = new HashMap();
inputs.put(DEFAULT_INPUT_KEY, input);
return processMessage(inputs);
}
public Result processMessage(Map<String, String> inputs) {
Map<String, String> labeledResults = new HashMap();
Map<String, String> output = new HashMap();
for (Entry<String, InputFormat> stringInputFormatEntry : this.inputFormatMap.entrySet()) {
String key = (String) stringInputFormatEntry.getKey();
InputFormat inputFormat = (InputFormat) stringInputFormatEntry.getValue();
String input = (String) inputs.get(key);
if (input == null) {
Log.d(TAG, "Input not specified for key: " + key);
return new Result();
}
Map<String, String> labeledResult = processInput(input, inputFormat);
if (labeledResult == null) {
Log.d(TAG, "Failed to get labeled results for key: " + key);
return new Result();
}
try {
labeledResults.putAll(labeledResult);
} catch (Exception e) {
Log.d(TAG, "Caught exception: " + Log.getStackTraceString(e));
return new Result();
}
}
for (Entry<String, OutputFormat> stringOutputFormatEntry : this.outputFormatMap.entrySet()) {
String key = (String) stringOutputFormatEntry.getKey();
String outputForKey = ((OutputFormat) stringOutputFormatEntry.getValue()).applyOutputFormat(labeledResults);
if (outputForKey == null) {
break;
}
output.put(key, outputForKey);
}
return new Result(output, labeledResults);
}
Map<String, String> processInput(String input, InputFormat inputFormat) {
String canonicalInputTemplate = inputFormat.getCanonicalInputTemplate();
String[] canonicalInputTokens = inputFormat.getCanonicalInputTokens();
Map<String, String> canonicalInputLabels = inputFormat.getCanonicalInputLabels();
Map<String, String> canonicalResult = new NumberedFormatStringParser(canonicalInputTemplate, canonicalInputTokens).parseFormattedString(input);
if (canonicalResult != null) {
return getLabeledResult(canonicalResult, canonicalInputLabels);
}
return null;
}
Map<String, String> getLabeledResult(Map<String, String> canonicalResult, Map<String, String> canonicalLabels) {
Map<String, String> labeledResult = new HashMap();
for (Entry<String, String> stringStringEntry : canonicalLabels.entrySet()) {
String label = (String) stringStringEntry.getKey();
String value = (String) canonicalResult.get((String) stringStringEntry.getValue());
if (value == null) {
return null;
}
labeledResult.put(label, value);
}
return labeledResult;
}
public class Result {
Map<String, String> labeledValues;
Map<String, String> outputMap;
public Result() {
this.outputMap = null;
this.labeledValues = null;
}
public Result(Map<String, String> outputMap, Map<String, String> labeledValues) {
this.outputMap = outputMap;
this.labeledValues = labeledValues;
}
public boolean matches() {
return this.labeledValues != null;
}
public String getOutputForKey(String key) {
if (this.outputMap != null) {
return (String) this.outputMap.get(key);
}
return null;
}
public String getValue(String label) {
if (this.labeledValues != null) {
return (String) this.labeledValues.get(label);
}
return null;
}
}
}
| bunnyblue/NoticeDog | app/src/main/java/io/bunnyblue/noticedog/app/apps/templates/MessageProcessor.java | Java | lgpl-3.0 | 13,067 |
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.scanner.sensor.noop;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.sensor.cpd.NewCpdTokens;
public class NoOpNewCpdTokens implements NewCpdTokens {
@Override
public void save() {
// Do nothing
}
@Override
public NoOpNewCpdTokens onFile(InputFile inputFile) {
// Do nothing
return this;
}
@Override
public NewCpdTokens addToken(TextRange range, String image) {
// Do nothing
return this;
}
@Override
public NewCpdTokens addToken(int startLine, int startLineOffset, int endLine, int endLineOffset, String image) {
// Do nothing
return this;
}
}
| lbndev/sonarqube | sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/noop/NoOpNewCpdTokens.java | Java | lgpl-3.0 | 1,524 |
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.permission;
import javax.annotation.Nullable;
import org.sonar.server.usergroups.ws.GroupIdOrAnyone;
public class GroupPermissionChange extends PermissionChange {
private final GroupIdOrAnyone groupId;
public GroupPermissionChange(Operation operation, String permission, @Nullable ProjectId projectId,
GroupIdOrAnyone groupId) {
super(operation, groupId.getOrganizationUuid(), permission, projectId);
this.groupId = groupId;
}
public GroupIdOrAnyone getGroupIdOrAnyone() {
return groupId;
}
}
| lbndev/sonarqube | server/sonar-server/src/main/java/org/sonar/server/permission/GroupPermissionChange.java | Java | lgpl-3.0 | 1,392 |
package nova.core.wrapper.mc17.util;
/**
*
* @author Stan Hebben
*/
public class ObfuscationConstants {
public static final String[] NBTTAGLIST_TAGLIST = {"tagList", "field_74747_a"};
public static final String[] OREDICTIONARY_IDTOSTACK = {"idToStack"};
public static final String[] OREDICTIONARY_IDTOSTACKUN = {"idToStackUn"};
public static final String[] MINECRAFTSERVER_ANVILFILE = {"anvilFile", "field_71308_o"};
public static final String[] INVENTORYCRAFTING_EVENTHANDLER = {"eventHandler", "field_70465_c"};
public static final String[] SLOTCRAFTING_PLAYER = {"thePlayer", "field_75238_b"};
public static final String[] STRINGTRANSLATE_INSTANCE = {"instance", "field_74817_a"};
public static final String[] CRAFTINGMANAGER_RECIPES = {"recipes", "field_77597_b"};
private ObfuscationConstants() {
}
}
| Victorious3/NovaCore | minecraft/1.7/src/main/java/nova/core/wrapper/mc17/util/ObfuscationConstants.java | Java | lgpl-3.0 | 824 |
package s3_test
import (
. "gopkg.in/check.v1"
"gopkg.in/amz.v1/aws"
"gopkg.in/amz.v1/s3"
)
// S3 ReST authentication docs: http://goo.gl/G1LrK
var testAuth = aws.Auth{"0PN5J17HBGZHT7JJ3X82", "uV3F3YluFJax1cknvbcGwgjvx4QpvB+leU8dUj2o"}
func (s *S) TestSignExampleObjectGet(c *C) {
method := "GET"
path := "/johnsmith/photos/puppy.jpg"
headers := map[string][]string{
"Host": {"johnsmith.s3.amazonaws.com"},
"Date": {"Tue, 27 Mar 2007 19:36:42 +0000"},
}
s3.Sign(testAuth, method, path, nil, headers)
expected := "AWS 0PN5J17HBGZHT7JJ3X82:xXjDGYUmKxnwqr5KXNPGldn5LbA="
c.Assert(headers["Authorization"], DeepEquals, []string{expected})
}
func (s *S) TestSignExampleObjectPut(c *C) {
method := "PUT"
path := "/johnsmith/photos/puppy.jpg"
headers := map[string][]string{
"Host": {"johnsmith.s3.amazonaws.com"},
"Date": {"Tue, 27 Mar 2007 21:15:45 +0000"},
"Content-Type": {"image/jpeg"},
"Content-Length": {"94328"},
}
s3.Sign(testAuth, method, path, nil, headers)
expected := "AWS 0PN5J17HBGZHT7JJ3X82:hcicpDDvL9SsO6AkvxqmIWkmOuQ="
c.Assert(headers["Authorization"], DeepEquals, []string{expected})
}
func (s *S) TestSignExampleList(c *C) {
method := "GET"
path := "/johnsmith/"
params := map[string][]string{
"prefix": {"photos"},
"max-keys": {"50"},
"marker": {"puppy"},
}
headers := map[string][]string{
"Host": {"johnsmith.s3.amazonaws.com"},
"Date": {"Tue, 27 Mar 2007 19:42:41 +0000"},
"User-Agent": {"Mozilla/5.0"},
}
s3.Sign(testAuth, method, path, params, headers)
expected := "AWS 0PN5J17HBGZHT7JJ3X82:jsRt/rhG+Vtp88HrYL706QhE4w4="
c.Assert(headers["Authorization"], DeepEquals, []string{expected})
}
func (s *S) TestSignExampleFetch(c *C) {
method := "GET"
path := "/johnsmith/"
params := map[string][]string{
"acl": {""},
}
headers := map[string][]string{
"Host": {"johnsmith.s3.amazonaws.com"},
"Date": {"Tue, 27 Mar 2007 19:44:46 +0000"},
}
s3.Sign(testAuth, method, path, params, headers)
expected := "AWS 0PN5J17HBGZHT7JJ3X82:thdUi9VAkzhkniLj96JIrOPGi0g="
c.Assert(headers["Authorization"], DeepEquals, []string{expected})
}
func (s *S) TestSignExampleDelete(c *C) {
method := "DELETE"
path := "/johnsmith/photos/puppy.jpg"
params := map[string][]string{}
headers := map[string][]string{
"Host": {"s3.amazonaws.com"},
"Date": {"Tue, 27 Mar 2007 21:20:27 +0000"},
"User-Agent": {"dotnet"},
"x-amz-date": {"Tue, 27 Mar 2007 21:20:26 +0000"},
}
s3.Sign(testAuth, method, path, params, headers)
expected := "AWS 0PN5J17HBGZHT7JJ3X82:k3nL7gH3+PadhTEVn5Ip83xlYzk="
c.Assert(headers["Authorization"], DeepEquals, []string{expected})
}
func (s *S) TestSignExampleUpload(c *C) {
method := "PUT"
path := "/static.johnsmith.net/db-backup.dat.gz"
params := map[string][]string{}
headers := map[string][]string{
"Host": {"static.johnsmith.net:8080"},
"Date": {"Tue, 27 Mar 2007 21:06:08 +0000"},
"User-Agent": {"curl/7.15.5"},
"x-amz-acl": {"public-read"},
"content-type": {"application/x-download"},
"Content-MD5": {"4gJE4saaMU4BqNR0kLY+lw=="},
"X-Amz-Meta-ReviewedBy": {"joe@johnsmith.net,jane@johnsmith.net"},
"X-Amz-Meta-FileChecksum": {"0x02661779"},
"X-Amz-Meta-ChecksumAlgorithm": {"crc32"},
"Content-Disposition": {"attachment; filename=database.dat"},
"Content-Encoding": {"gzip"},
"Content-Length": {"5913339"},
}
s3.Sign(testAuth, method, path, params, headers)
expected := "AWS 0PN5J17HBGZHT7JJ3X82:C0FlOtU8Ylb9KDTpZqYkZPX91iI="
c.Assert(headers["Authorization"], DeepEquals, []string{expected})
}
func (s *S) TestSignExampleListAllMyBuckets(c *C) {
method := "GET"
path := "/"
headers := map[string][]string{
"Host": {"s3.amazonaws.com"},
"Date": {"Wed, 28 Mar 2007 01:29:59 +0000"},
}
s3.Sign(testAuth, method, path, nil, headers)
expected := "AWS 0PN5J17HBGZHT7JJ3X82:Db+gepJSUbZKwpx1FR0DLtEYoZA="
c.Assert(headers["Authorization"], DeepEquals, []string{expected})
}
func (s *S) TestSignExampleUnicodeKeys(c *C) {
method := "GET"
path := "/dictionary/fran%C3%A7ais/pr%c3%a9f%c3%a8re"
headers := map[string][]string{
"Host": {"s3.amazonaws.com"},
"Date": {"Wed, 28 Mar 2007 01:49:49 +0000"},
}
s3.Sign(testAuth, method, path, nil, headers)
expected := "AWS 0PN5J17HBGZHT7JJ3X82:dxhSBHoI6eVSPcXJqEghlUzZMnY="
c.Assert(headers["Authorization"], DeepEquals, []string{expected})
}
| axw/amz | s3/sign_test.go | GO | lgpl-3.0 | 4,554 |
<?php
namespace Front\Presenters;
use Nette\Application\UI\Form,
Grido\Grid,
Grido\Components\Filters\Filter,
Grido\Translations\FileTranslator,
Nette\Application\Responses\JsonResponse,
Nette\Application\Responses\TextResponse,
Nette\Utils\Html,
Nette\Mail\Message,
IPub\VisualPaginator\Components as VisualPaginator,
Nette\Diagnostics\Debugger;
class DefaultPresenter extends \Base\Presenters\BasePresenter
{
public $quote;
public $cart_id;
public $cart;
public $store_id;
public function startup() {
parent::startup();
\DependentSelectBox\JsonDependentSelectBox::register('addJSelect');
}
public function beforeRender() {
parent::beforeRender();
\DependentSelectBox\JsonDependentSelectBox::tryJsonResponse($this /*(presenter)*/);
}
public function actionViewSizeEstimator(){
}
public function handleShowBiggerSize($cart_id, $previousSize){
$new_main_product_id = $this->backendModel->getBiggerSize($previousSize, $this->store_id);
if($new_main_product_id)
$this->redirect("Default:showPrices", $cart_id, $new_main_product_id);
}
public function handleShowSmallerSize($cart_id, $previousSize){
$new_main_product_id = $this->backendModel->getSmallerSize($previousSize, $this->store_id);
if($new_main_product_id)
$this->redirect("Default:showPrices", $cart_id, $new_main_product_id);
}
public function distance($lat1, $lon1, $lat2, $lon2, $unit) {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}
public function handlePscChange($postalCode){
if(isset($postalCode)&&!empty($postalCode)) $this->redirect("this", array("values" => array("psc"=>$postalCode)));
}
public function actionDefault($values = array()){
$form = $this["quoteForm"];
if(isset($values['psc'])&&!empty($values['psc'])){
//$this["quoteForm"]->setDefaults(array("postalCode"=>$values['psc']));
//mame psc
$url ="http://maps.googleapis.com/maps/api/geocode/xml?address=".$values['psc']."&sensor=false";
$result = simplexml_load_file($url);
$lat1 = $result->result->geometry->location->lat;
$lon1 = $result->result->geometry->location->lng;
$stores = $this->backendModel->getStores()->fetchAll();
$distances = array();
if(count($stores)>0){
foreach($stores AS $store){
$distances[$store->store_id] = $this->distance((string)$lat1, (string)$lon1, $store->lat, $store->lon, 'K');
//echo $this->distance($this->toFloat($lat1), $this->toFloat($lon1), $store->lat, $store->lon, 'K');
}
}
//Debugger::dump($distances);
if(count($distances)>0){
//vybere pobocku nejblizeme a nastavime formular
$chosenOne = array_keys($distances, min($distances));
//$products = $form["store_id"], array($this, "getStoreProducts")
//$this["quoteForm"]["main_product_id"]->setDefaultValues($this->backendModel->getMainProductsByStorePairs(end($chosenOne)));
$form->setDefaults(array("store_id"=>end($chosenOne), "postalCode"=>$values['psc']));
//$form["store_id"]->setAttribute("readonly", "readonly");
//$this->invalidateControl("productsSnippet");
/*unset($form["main_product_id"]);
$form->addJSelect("main_product_id", "Select your size", $form["store_id"], array($this, "getStoreProducts"))
->setPrompt("select size")
->addRule($form::FILLED, "Please choose your size.")
->setAttribute('class', 'form-control');*/
$form["main_product_id"]->refresh();
$this->invalidateControl("productsSnippet");
}
}
if(isset($values['store_id'])&&isset($values['main_product_id'])){
$this->quote = $values;
$this->template->step2 = true;
$this->template->store = $this->backendModel->getStoreData($values['store_id']);
}
}
public function handleOrder($cart_id, $product_id, $offer){
//prvni zjistime ceny
$pricesArray = array();
$this->cart = $this->backendModel->getCartWDetails($cart_id);
$product = $this->backendModel->getProductData($product_id);
$pricesArray = $this->countProductPrices($product, $this->cart->cartLeaseInMonths);
//aktualizujeme kosik
$cart = array(
"cart_id" => $cart_id,
"product_id" => $product_id
);
if($offer == 1){
$cart["cartPrice"] = $pricesArray['cartPrice'];
$cart["cartSale"] = $pricesArray['cartSale'];
$cart["cartPriceTotal"] = $pricesArray['cartPriceTotal'];
}
elseif($offer == 2){
$cart["cartPrice"] = $pricesArray['cartPrice'];
$cart["cartSale"] = $pricesArray['cartSale'];
$cart["cartPriceTotal"] = $pricesArray['cartPriceTotal2'];
}
$this->backendModel->saveCart($cart);
$order = array(
"cart_id" => (INT)$cart_id,
"order_state_id" => 3,
"orderAdDate" => date("Y-m-d H:i:s")
);
$this->backendModel->saveOrder($order);
//titan email
$mail = new Message;
$mail->setFrom("noreply@titanstorage.co.uk");
$mail->addTo("braintree@titanstorage.co.uk");
$mail->setSubject('New booking');
$mail->setHtmlBody("
There is a new booking in your CRM system.\n
Total: £".round($this->cart->cartPriceTotal, 2)."\n
From: $this->cart->leaseFrom\n
To: $this->cart->leaseTo\n
Product name: $this->cart->productName\n
Product description: $this->cart->productDescription\n
titanstorage.co.uk
");
$this->mailer->send($mail);
//customer email
$email = $this->cart->customerEmail;
$mail = new Message;
$mail->setFrom("noreply@titanstorage.co.uk");
$mail->addTo($email);
$mail->setSubject('Titan Storage - New booking');
$mail->setHtmlBody("
Your order is confirmed.\n
\n
Price total: £".round($this->cart->cartPriceTotal, 2)."\n
From: $this->cart->leaseFrom\n
To: $this->cart->leaseTo\n
Product name: $this->cart->productName\n
titanstorage.co.uk
");
$this->mailer->send($mail);
/*//zasleme email
$email = $this->cart->customerEmail;
//mail pro zaslání dodatečných informací
$mail = new Message;
$mail->setFrom("noreply@titanstorage.co.uk");
$mail->addTo($email);
$mail->setSubject('Titan Storage');
$mail->setHtmlBody("
$values[templateHtml]
");
try{
$this->mailer->send($mail);
$this->flashMessage('Email sent.', 'success');
} catch (\Exception $e) {
$this->flashMessage("ERROR: sending of email failed.", 'error');
}*/
$this->flashMessage("You have booked a ".$product->productName." unit from ".date("d/m/y", strtotime($this->cart->leaseFrom))." to ".date("d/m/y", strtotime($this->cart->leaseTo)).". You will shortly receive a confirmation email.", "success");
//$this->redirect(":Front:Default:default");
header('Location: http://titantest.lahivecreative.co.uk/your-quote-from-titan/');
}
public function actionShowPrices($cart_id, $new_main_product_id = NULL){
if(isset($cart_id)){
$this->cart_id = $cart_id;
$this->template->cart_id = $this->cart_id;
$this->cart = $this->backendModel->getCart($this->cart_id);
$this->template->cart = $this->cart;
$this->store_id = $this->cart->store_id;
$new_main_product_size = 0;
if($new_main_product_id){
$new_main_product_size = $this->backendModel->getMainProductSize($new_main_product_id);
}
$this->template->prevSize = ($new_main_product_id)?$new_main_product_size:$this->cart->mainProductSize;
$main_product_id = ($new_main_product_id)?$new_main_product_id:$this->cart->main_product_id;
if($main_product_id){
//ziskame prvni prostredni produkt
$products = array();
$subProducts = array();
$middle = $this->backendModel->getMiddleProductByMainProduct($main_product_id, $this->cart->cartLeaseInMonths);
$subProducts[] = $middle;
//Debugger::dump($middle);
$prev_main_product_id = $this->backendModel->getSmallerSize($middle->mainProductSize, $this->store_id);
$next_main_product_id = $this->backendModel->getBiggerSize($middle->mainProductSize, $this->store_id);
$prev = $this->backendModel->getMiddleProductByMainProduct($prev_main_product_id, $this->cart->cartLeaseInMonths);
array_unshift ($subProducts, $prev);
$next = $this->backendModel->getMiddleProductByMainProduct($next_main_product_id, $this->cart->cartLeaseInMonths);
array_push ($subProducts, $next);
//jak ted kurva ziskam vrchni a spodni produkt?
//$subProducts = $this->backendModel->getProductsByMainProduct($main_product_id);
if(count($subProducts)>0){
$pricesArray = array();
foreach($subProducts AS $key => $product){
if(!isset($product->product_id)) continue;
$pricesArray = $this->countProductPrices($product, $this->cart->cartLeaseInMonths);
$products[] = array(
"product_id" => $product->product_id,
"productName" => $product->productName,
"productDescription" => $product->productDescription,
"productPricePerMonth" => $product->productPricePerMonth,
"productStandartPricePerWeek" => number_format(round($product->productStandartPricePerWeek, 2), 2),
"productTotal" => $product->productTotal,
"productOccupancy" => $product->productOccupancy,
"productVacancy" => $product->productVacancy,
"productUnitType" => $product->productUnitType,
"promotionName" => $product->promotionName,
"promotionActive" => $product->promotionActive,
"productVacancy" => $product->productVacancy,
"productPricePerMonthSale" => round($pricesArray['cartPriceTotal']/$this->cart->cartLeaseInMonths, 2),
"productPricePerMonthSale2" => round($pricesArray['cartPriceTotal2']/$this->cart->cartLeaseInMonths, 2),
"standartTotalPrice" => number_format(round($product->productPricePerMonth*$this->cart->cartLeaseInMonths, 2), 2),
"cartSaleActive" => $pricesArray['cartSaleActive'],
"cartPrice" => number_format(round($pricesArray['cartPrice'], 2), 2),
"cartSale" => number_format(round($pricesArray['cartSale'], 2), 2),
"cartPriceTotal" => number_format(round($pricesArray['cartPriceTotal'], 2), 2),
"cartPriceTotal2" => number_format(round($pricesArray['cartPriceTotal2'], 2), 2),
"cartSaleActive2" => $pricesArray['cartSaleActive2']
);
}
}
$this->template->products = $products;
//Debugger::dump($products); die();
}
}
}
public function getStoreProducts($form, $dependentSelectBoxName) {
$select1 = $form["store_id"]->getValue();
/*Debugger::log($this->backendModel->getProductsByStorePairs($select1));
Debugger::log($select1);*/
return $this->backendModel->getMainProductsByStorePairs($select1);
}
protected function createComponentQuoteForm($name){
$form = new Form($this, $name);
$form->getElementPrototype()->class[] = "stdForm";
$form->setMethod('get');
$postalCode = $form->addText('postalCode', 'Postal code');
$postalCode->setAttribute('placeholder', 'Your postcode');
$postalCode->setAttribute('class', 'form-control');
$store = $form->addSelect('store_id', 'Select your local store', $this->backendModel->getStorePairs());
$store->setPrompt("select store");
$store->addRule($form::FILLED, "Please select your local store.");
$store->setAttribute('class', 'form-control');
$form->addJSelect("main_product_id", "Select your size", $form["store_id"], array($this, "getStoreProducts"))
->setPrompt("select size")
->addRule($form::FILLED, "Please choose your size.")
->setAttribute('class', 'form-control');
if($this->isAjax()) {
$form["main_product_id"]->addOnSubmitCallback(array($this, "invalidateControl"), "productsSnippet");
}
$form->addText('leaseFrom', 'Lease from')
->addRule($form::FILLED, "Please select 'Lease from' field")
->setAttribute('placeholder', 'from')
->setAttribute('class', 'form-control');
$form->addText('leaseTo', 'Lease to')
->addRule($form::FILLED, "Please select 'Lease to' field")
->setAttribute('placeholder', 'to')
->setAttribute('class', 'form-control');
/*$form->addSelect('product_id', 'Select your size', array(1 => "dummy product"))
->setPrompt("Choose your size")
->addRule($form::FILLED, "Please choose your size.")
->setAttribute('class', 'form-control');*/
$form->onSuccess[] = array($this, 'quoteFormSubmitted');
$form->addSubmit('submit', 'Continue')
->setAttribute('class', 'btn btn-primary quoteFormSubmit ajax'); //ajax!!
return $form;
}
public function quoteFormSubmitted($form){
if($form->isSubmitted() && $form->isValid()){
if($form['submit']->isSubmittedBy()){
$values = $form->values;
$this->redirect("this", $values);
}
}
}
protected function createComponentCustomerForm($name){
$form = new Form($this, $name);
$form->getElementPrototype()->class[] = "stdForm";
$form->addSelect('salutation_id', 'Title', $this->userModel->getSalutationPairs())
->getControlPrototype()->class("form-control");
$form->addText('customerFirstname', 'Firstname')
->getControlPrototype()->class("form-control");
$form->addText('customerSurname', 'Surname')
->getControlPrototype()->class("form-control");
$form->addText('customerEmail', 'Email')
->addRule($form::EMAIL, "Please fill valid email address.")
->addRule($form::FILLED, "Please fill your email.")
->getControlPrototype()->class("form-control");
$form->addText('customerPhone', 'Phone')
->addRule($form::FILLED, "Please fill your phone.")
->getControlPrototype()->class("form-control");
$form->onSuccess[] = array($this, 'customerFormSubmitted');
$form->addSubmit('submit', 'Show prices')
->setAttribute('class', 'btn btn-primary customerFormSubmit');
return $form;
}
public function nb_mois($date1, $date2)
{
$date1 = str_replace('/', '-', $date1);
$date2 = str_replace('/', '-', $date2);
/*$date1 = date("Y-m-d", strtotime($date1));
$date2 = date("Y-m-d", strtotime($date2));*/
$begin = new \DateTime( $date1 );
$end = new \DateTime( $date2 );
//$end = $end->modify( '+1 month' );
$interval = \DateInterval::createFromDateString('1 day');
$period = new \DatePeriod($begin, $interval, $end);
$counter = 0;
foreach($period as $dt) {
$counter++;
}
return $counter/30;
}
public function countProductPrices($productData, $cartLeaseInMonths){
$vals = array();
$vals["cartPrice"] = 0;
$vals["cartSale"] = 0;
$vals["cartPriceTotal"] = 0;
$vals["cartSaleActive"] = false;
//second offer
//$vals["cartSale2"] = 0;
$vals["cartPriceTotal2"] = 0;
$vals["cartSaleActive2"] = false;
$months = $cartLeaseInMonths;
if($months > 0 && isset($productData->productPricePerMonth)){
//doba zapujceni je nenulova, muzeme spocitat cenu
$cartPrice = $months*$productData->productPricePerMonth;
if($productData->promotionActive == '1'){
//spocitame slevu
$sale = 0;
$salePerMonth = 0;
//prvni ale zjistime zda jsme dodrzeli min dobu pro aktivaci slevy
if($months >= $productData->promotionMinimalRentingPeriod){
//sleva aktivovana
//kolik bude sleva na jeden mesic
$salePerMonth = ($productData->promotionPercentage/100)*$productData->productPricePerMonth;
if($months >= $productData->promotionValidityPeriod){
//sleva bude rovna max sleve
$sale = $productData->promotionValidityPeriod*$salePerMonth;
}
elseif($months < $productData->promotionValidityPeriod){
//sleva bude podilove mensi
$fullSale = $productData->promotionValidityPeriod*$salePerMonth;
$sale = ($months/$productData->promotionValidityPeriod)*$fullSale;
}
$vals["cartSaleActive"] = true;
$vals["cartPrice"] = $cartPrice;
$vals["cartSale"] = $sale;
$vals["cartPriceTotal"] = $cartPrice - $sale;
}
else{
//cena je jiz konecna
$vals["cartSaleActive"] = false;
$vals["cartPrice"] = $cartPrice;
$vals["cartSale"] = 0;
$vals["cartPriceTotal"] = $cartPrice;
}
}
else{
//cena je jiz konecna
$vals["cartSaleActive"] = false;
$vals["cartPrice"] = $cartPrice;
$vals["cartSale"] = 0;
$vals["cartPriceTotal"] = $cartPrice;
}
//spocitame jeste slevu pro move in
if($months >= 2){
$sale = $cartPrice - $productData->productPricePerMonth + 1;
$vals["cartPriceTotal2"] = $sale;
$vals["cartSaleActive2"] = true;
}
else{
$vals["cartPriceTotal2"] = $cartPrice;
$vals["cartSaleActive2"] = false;
}
}
return $vals;
}
public function customerFormSubmitted($form){
if($form->isSubmitted() && $form->isValid()){
if($form['submit']->isSubmittedBy()){
$values = $form->values;
$customer_id = $this->backendModel->saveCustomer($values);
if($customer_id){
//mame zakaznika, ulozime kosik ale prvni spocitame ceny
$vals = $this->quote;
unset($vals["postalCode"]);
if(!isset($vals["leaseFrom"])||!isset($vals["leaseTo"])){
$this->flashMessage("Error, lease from and lease to date must be filled, please return to step 1.", "warning");
$this->redirect("this");
}
else{
$months = $this->nb_mois($vals["leaseFrom"], $vals["leaseTo"]);
if($months <= 0){
$this->flashMessage("Error, lease period is smaller than one day, please check filled date range.", "warning");
$this->redirect("this");
}
else{
$vals["cartLeaseInMonths"] = $months;
}
}
//ulozime kosik
$vals["leaseFrom"] = date("Y-m-d H:i:s", strtotime($vals["leaseFrom"]));
$vals["leaseTo"] = date("Y-m-d H:i:s", strtotime($vals["leaseTo"]));
$vals["customer_id"] = $customer_id;
$vals["cartAdDate"] = date ("Y-m-d H:i:s");
$cart_id = $this->backendModel->saveCart($vals);
$tpl = $this->createTemplate();
$tpl->setFile(__DIR__ ."/templates/automaticEmail1.latte");
$tpl->name = $values["customerFirstname"];
$tpl->surname = $values["customerSurname"];
$email = $values["customerEmail"];
//mail pro zaslání dodatečných informací
$mail = new Message;
$mail->setFrom("noreply@titanstorage.co.uk");
$mail->addTo($email);
$mail->setSubject('Titan Storage');
$mail->setHtmlBody($tpl->__toString());
try{
$this->mailer->send($mail);
} catch (\Exception $e) {
}
}
/*$this->backendModel->saveQuote($this->quote);
$this->backendModel->saveCustomer($values);*/
$this->redirect(":Front:Default:showPrices", $cart_id);
}
}
}
}
| weprove/titan | app/modules/Front/DefaultPresenter.php | PHP | lgpl-3.0 | 18,922 |
/* ************************************************************************
GUI for JavaScript Client for XMPP (jc4xmpp)
Copyright
2012 Dirk Woestefeld
License:
LGPL v3: http://www.gnu.org/licenses/lgpl.html
A Copy of the License can be found in the directory of this project.
Authors:
Dirk Woestefeld
************************************************************************ */
/**
* @ignore(jc4xmppConfig.*)
*/
/**
* Config-Panel general setting
*/
qx.Class.define("jc4xmpp_ui.config.GeneralConfig",
{
extend:qx.ui.tabview.Page,
/*
*****************************************************************************
CONSTRUCTOR
*****************************************************************************
*/
/**
*
*/
construct : function(){
//TODO: Show info if not connected
this.base(arguments,this.tr("General"),jc4xmpp_ui.Icons.icon16("user-desktop"));
this._cfg = jc4xmpp_ui.Application.config;
this._cfg.addListener("change", this._hdlCfgChange, this);
this.setLayout(new qx.ui.layout.VBox(10));
this._uiObj = {};
this.add(new qx.ui.basic.Label().set({
rich:true,
value:this.tr("general_config_info")
}));
var panel = new qx.ui.container.Composite(new qx.ui.layout.VBox());
var panel2 = new qx.ui.container.Composite(new qx.ui.layout.HBox());
panel.add(new qx.ui.basic.Label(this.tr("Backgroundimage")));
this._bgImg = new qx.ui.form.ComboBox();
var select = this._cfg.get("backgroundImage","");
var bgImgs = jc4xmppConfig.BackgroundImages;
for(var e in bgImgs){
if(bgImgs[e] == select){
select = e;
}
this._bgImg.add(new qx.ui.form.ListItem(e));
}
this._bgImg.setValue(select);
panel2.add(this._bgImg,{flex:1});
this._btnBgApply = new qx.ui.form.Button(null,jc4xmpp_ui.Icons.icon16("view-refresh"));
this._btnBgApply.setToolTipText(this.tr("Load selected Image"));
this._btnBgApply.addListener("execute", function(){
var val = this._bgImg.getValue();
this._cfg.set("backgroundImage",bgImgs[val] || val);
},this)
panel2.add(this._btnBgApply);
panel.add(panel2);
this.add(panel);
panel = new qx.ui.container.Composite(new qx.ui.layout.VBox());
// Position of the "taskbar"
panel.add(new qx.ui.basic.Label(this.tr("The Position of the Buttonbar")).set({alignY:"middle"}));
var posLst = { "top":{"txt":this.marktr("Top")},
"left":{"txt":this.marktr("Left")},
"right":{"txt":this.marktr("Right")},
"bottom":{"txt":this.marktr("Bottom")}
};
this.winBarPos = new qx.ui.form.SelectBox();
var select = this._cfg.get("appWinbarPosition");
for(var e in posLst){
var item = new qx.ui.form.ListItem(this.tr(posLst[e].txt));
posLst[e].item = item;
this.winBarPos.add(item);
if(e === select){
this.winBarPos.setSelection([item]);
}
}
this.winBarPos.addListener("changeSelection", function(evt) {
var item = this.winBarPos.getSelection()[0];
for(var e in posLst){
if(item == posLst[e].item){
this._cfg.set("appWinbarPosition",""+e);
}
}
},this);
this.winBarPos.setMaxWidth(150);
panel.add(this.winBarPos);
this.add(panel);
},
/*
*****************************************************************************
MEMBERS
*****************************************************************************
*/
members :{
/**
* prepare data before save
*/
_prepareSave: function(){
var val = this._bgImg.getValue();
var bgImgs = jc4xmppConfig.BackgroundImages;
this._cfg.set("backgroundImage",bgImgs[val] || val);
},
/**
* handle config change
* @param evt {jc4xmpp.Event}
*/
_hdlCfgChange: function(evt){
var name = evt["name"];
var obj = this._uiObj[name];
if(obj){
if(obj.getValue() != evt["value"]){
obj.setValue(evt["value"]);
}
}
},
/**
* Called by the dialog if the dialog is opened.
*/
_dialogOpen:function(){}
}
}); | hobbytuxer/jc4xmpp | gui/source/class/jc4xmpp_ui/config/GeneralConfig.js | JavaScript | lgpl-3.0 | 4,742 |
package nifbullet.cha;
import org.jogamp.java3d.BranchGroup;
import org.jogamp.java3d.Transform3D;
import org.jogamp.vecmath.Quat4f;
import org.jogamp.vecmath.Vector3f;
import com.bulletphysics.collision.dispatch.CollisionFlags;
import com.bulletphysics.collision.shapes.BoxShape;
import com.bulletphysics.dynamics.DynamicsWorld;
import com.bulletphysics.dynamics.RigidBody;
import com.bulletphysics.dynamics.RigidBodyConstructionInfo;
import com.bulletphysics.dynamics.character.KinematicCharacterController.CharacterPositionListener;
import com.bulletphysics.linearmath.Transform;
import nifbullet.util.NifBulletUtil;
public class NBNonControlledChar extends BranchGroup implements NifBulletChar
{
private int recordId = -1;
private float characterHeight = 1f;//notice half extents so 2m tall
private float characterWidth = 0.5f;//something odd in the shape here?
private RigidBody rigidBody;
private DynamicsWorld dynamicsWorld = null;
private CharacterPositionListener listener;
public NBNonControlledChar(Transform3D rootTrans, float mass, int recordId)
{
this.recordId = recordId;
setCapability(BranchGroup.ALLOW_DETACH);
BoxShape boxShape = new BoxShape(new Vector3f(characterWidth, characterHeight, characterWidth));
RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, null, boxShape);
rigidBody = new RigidBody(rbInfo);
rigidBody.setCollisionFlags(CollisionFlags.KINEMATIC_OBJECT);
rigidBody.setUserPointer(this);
setTransform(rootTrans);
}
public int getRecordId()
{
return recordId;
}
@Override
public void setCharacterPositionListener(CharacterPositionListener listener)
{
this.listener = listener;
}
@Override
public void setTransform(Quat4f q, Vector3f v)
{
Transform3D t = new Transform3D(q, v, 1f);
setTransform(t);
}
@Override
public void setTransform(Transform3D trans)
{
Transform worldTransform = NifBulletUtil.createTrans(trans);
rigidBody.setWorldTransform(worldTransform);
rigidBody.activate(true);
}
public void applyRelCentralForce(Vector3f linearForce)
{
//tranlate force to local coords
Transform wt = new Transform();
rigidBody.getWorldTransform(wt);
Quat4f currRotation = new Quat4f();
wt.getRotation(currRotation);
Transform3D t = new Transform3D();
t.set(currRotation);
t.transform(linearForce);
rigidBody.applyCentralForce(linearForce);
rigidBody.activate(true);
}
public void applyRelTorque(Vector3f rotationalForce)
{
//tranlate force to local coords
Transform wt = new Transform();
rigidBody.getWorldTransform(wt);
Quat4f currRotation = new Quat4f();
wt.getRotation(currRotation);
Transform3D t = new Transform3D();
t.set(currRotation);
t.transform(rotationalForce);
rigidBody.applyTorque(rotationalForce);
rigidBody.activate(true);
}
public RigidBody getRigidBody()
{
return rigidBody;
}
@Override
public void destroy()
{
if (dynamicsWorld != null)
{
new Throwable("destroy called whilst in dynamic world");
}
rigidBody.destroy();
}
/**
* Basically a set enabled true
*/
@Override
public void addToDynamicsWorld(DynamicsWorld dynamicsWorld)
{
this.dynamicsWorld = dynamicsWorld;
if (rigidBody != null)
{
if (dynamicsWorld != null)
{
synchronized (dynamicsWorld)
{
dynamicsWorld.addRigidBody(rigidBody);
}
}
}
}
/** basically a set enabled false
*
*/
@Override
public void removeFromDynamicsWorld()
{// check for double remove or no add yet
if (dynamicsWorld != null)
{
synchronized (dynamicsWorld)
{
if (rigidBody != null)
{
dynamicsWorld.removeRigidBody(rigidBody);
}
}
dynamicsWorld = null;
}
}
@Override
public String toString()
{
return "NBNoncontrollerCharModel in class of " + this.getClass();
}
}
| philjord/jnifjbullet | jnifjbullet/src/nifbullet/cha/NBNonControlledChar.java | Java | lgpl-3.0 | 3,966 |
/*
* Unitex
*
* Copyright (C) 2001-2014 Université Paris-Est Marne-la-Vallée <unitex@univ-mlv.fr>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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.
*
*/
package fr.umlv.unitex.xalign;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.ExecutionException;
import javax.swing.SwingWorker;
/**
* This is a loader for XML text files manipulated by XAlign.
*
* @author Sébastien Paumier
*/
public class XMLTextLoader {
final XMLTextModel model;
final MappedByteBuffer buffer;
public XMLTextLoader(XMLTextModel model, MappedByteBuffer buffer) {
this.model = model;
this.buffer = buffer;
}
public void load() {
final SwingWorker<Void, Sentence> worker = new SwingWorker<Void, Sentence>() {
@Override
protected Void doInBackground() throws Exception {
final int dataLength = buffer.capacity();
final StringBuilder ID = new StringBuilder();
int start, end;
for (int pos = 0; pos < dataLength; pos = pos + 1) {
if (buffer.get(pos) == '<' && buffer.get(pos + 1) == 's'
&& buffer.get(pos + 2) == ' ') {
/* If we have a sentence tag, we read its id */
do {
pos++;
} while (!(buffer.get(pos) == '"'
&& buffer.get(pos - 1) == '='
&& buffer.get(pos - 2) == 'd'
&& buffer.get(pos - 3) == 'i'
&& buffer.get(pos - 4) == ':'
&& buffer.get(pos - 5) == 'l'
&& buffer.get(pos - 6) == 'm' && buffer
.get(pos - 7) == 'x'));
ID.setLength(0);
pos++;
do {
ID.append((char) buffer.get(pos));
pos++;
} while (buffer.get(pos) != '"');
/*
* Then we look for the beginning of the sentence, i.e.
* after the '>' char
*/
while (buffer.get(pos - 1) != '>') {
pos++;
}
start = pos;
do {
pos++;
} while (buffer.get(pos - 1) != '<');
end = pos - 2;
publish(new Sentence(ID.toString(), start, end));
setProgress((int) (100. * pos / dataLength));
}
}
setProgress(100);
return null;
}
@Override
protected void process(java.util.List<Sentence> chunks) {
model.addSentences(chunks);
}
};
worker.execute();
try {
worker.get();
} catch (final InterruptedException e) {
e.printStackTrace();
} catch (final ExecutionException e) {
e.printStackTrace();
}
}
/**
* Builds and returns a read-only mapped byte buffer for the given file.
*/
public static MappedByteBuffer buildMappedByteBuffer(File file)
throws IOException {
final FileInputStream fileInputStream = new FileInputStream(file);
final FileChannel channel = fileInputStream.getChannel();
final MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_ONLY,
0, file.length());
fileInputStream.close();
return map;
}
}
| mdamis/unilabIDE | Unitex-Java/src/fr/umlv/unitex/xalign/XMLTextLoader.java | Java | lgpl-3.0 | 3,724 |
/*
* This file is part of Sledgehammer.
*
* Sledgehammer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Sledgehammer 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 Sledgehammer. If not, see <http://www.gnu.org/licenses/>.
*
* Sledgehammer is free to use and modify, ONLY for non-official third-party servers
* not affiliated with TheIndieStone, or it's immediate affiliates, or contractors.
*/
/*
* This file is part of Sledgehammer.
*
* Sledgehammer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Sledgehammer 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 Sledgehammer. If not, see <http://www.gnu.org/licenses/>.
*
* Sledgehammer is free to use and modify, ONLY for non-official third-party servers
* not affiliated with TheIndieStone, or it's immediate affiliates, or contractors.
*/
package sledgehammer.event;
import sledgehammer.event.Event;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
/**
* Event to process and handle thrown Throwables for the Sledgehammer engine.
*
* @author Jab
*/
public class ThrowableEvent extends Event {
private Throwable throwable;
/**
* Main constructor.
*
* @param throwable The Throwable that was thrown.
*/
public ThrowableEvent(Throwable throwable) {
setThrowable(throwable);
}
/** @return Returns a PrintWriter render of the Throwable. */
public String printStackTrace() {
return getStackTrace(getThrowable());
}
/** @return Returns the Throwable Object that was thrown. */
public Throwable getThrowable() {
return this.throwable;
}
/**
* (Private Method)
*
* <p>Sets the Throwable for the Event.
*
* @param throwable The Throwable to set.
*/
private void setThrowable(Throwable throwable) {
this.throwable = throwable;
}
/**
* Prints a formal StackTrace into a String.
*
* @param aThrowable The Throwable to print.
* @return Returns a printed String of the StackTrace.
*/
public static String getStackTrace(Throwable aThrowable) {
Writer stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
aThrowable.printStackTrace(printWriter);
String stackTrace = stringWriter.toString();
try {
stringWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
return stackTrace;
}
}
| JabJabJab/Sledgehammer | src/main/java/sledgehammer/event/ThrowableEvent.java | Java | lgpl-3.0 | 3,429 |
<!DOCTYPE html>
<html>
<head>
<link href="css/bootstrap.css" rel="stylesheet"/>
<link href="css/bootstrap-responsive.css" rel="stylesheet"/>
<link href="css/styles.css" rel="stylesheet"/>
<?php if (isset($title)): ?>
<title>C$50 Finance: <?= htmlspecialchars($title) ?></title>
<?php else: ?>
<title>C$50 Finance</title>
<?php endif ?>
<script src="js/jquery-1.8.2.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/scripts.js"></script>
</head>
<body>
<div class="container-fluid">
<div id="top">
<a href="/"><img alt="C$50 Finance" src="img/logo.gif"/></a>
</div>
<div id="middle">
| SudharakaP/CS50 | localhost/templates/header.php | PHP | lgpl-3.0 | 798 |
/*
* True Reality Open Source Game and Simulation Engine
* Copyright © 2021 Acid Rain Studios LLC
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3.0 of the License, or (at your option)
* any later version.
*
* 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
*
* @author Maxim Serebrennik
*/
#include "Application.h"
#include "TestActor.h"
#include "TestDirector.h"
#include <trUtil/Console/TextColor.h>
#include <trManager/SystemManager.h>
const trUtil::RefStr Application::CLASS_TYPE = trUtil::RefStr("Application");
//////////////////////////////////////////////////////////////////////////
Application::Application(const std::string& name) : BaseClass(name)
{
//Create Test Actor 1
trUtil::Console::TextColor(trUtil::Console::TXT_COLOR::BRIGHT_GREEN);
std::cerr << "Creating Test Actor. " << std::endl;
mSysMan->RegisterActor(*new TestActor());
//Create Test Director
trUtil::Console::TextColor(trUtil::Console::TXT_COLOR::BRIGHT_GREEN);
std::cerr << "Creating a Test Director. " << std::endl;
mSysMan->RegisterDirector(*new TestDirector(), trManager::DirectorPriority::NORMAL);
}
//////////////////////////////////////////////////////////////////////////
const std::string& Application::GetType() const
{
return CLASS_TYPE;
}
//////////////////////////////////////////////////////////////////////////
Application::~Application()
{
}
| acidrainstudios/TrueReality | Examples/ActorModules/Application.cpp | C++ | lgpl-3.0 | 1,942 |
<?php
/*
* $Id$
*
* 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://phing.info>.
*/
require_once 'phing/Task.php';
/**
* Executes a command on the shell.
*
* @author Andreas Aderhold <andi@binarycloud.com>
* @author Hans Lellelid <hans@xmpl.org>
* @version $Revision$
* @package phing.tasks.system
*/
class ExecTask extends Task {
/**
* Command to execute.
* @var string
*/
protected $command;
/**
* Working directory.
* @var File
*/
protected $dir;
/**
* Operating system.
* @var string
*/
protected $os;
/**
* Whether to escape shell command using escapeshellcmd().
* @var boolean
*/
protected $escape = false;
/**
* Where to direct output.
* @var File
*/
protected $output;
/**
* Whether to use PHP's passthru() function instead of exec()
* @var boolean
*/
protected $passthru = false;
/**
* Whether to log returned output as MSG_INFO instead of MSG_VERBOSE
* @var boolean
*/
protected $logOutput = false;
/**
* Logging level for status messages
* @var integer
*/
protected $logLevel = Project::MSG_VERBOSE;
/**
* Where to direct error output.
* @var File
*/
protected $error;
/**
* If spawn is set then [unix] programs will redirect stdout and add '&'.
* @var boolean
*/
protected $spawn = false;
/**
* Property name to set with return value from exec call.
*
* @var string
*/
protected $returnProperty;
/**
* Property name to set with output value from exec call.
*
* @var string
*/
protected $outputProperty;
/**
* Whether to check the return code.
* @var boolean
*/
protected $checkreturn = false;
/**
* Main method: wraps execute() command.
* @return void
*/
public function main() {
$this->execute();
}
/**
* Executes a program and returns the return code.
* Output from command is logged at INFO level.
* @return int Return code from execution.
*/
public function execute() {
// test if os match
$myos = Phing::getProperty("os.name");
$this->log("Myos = " . $myos, Project::MSG_VERBOSE);
if (($this->os !== null) && (strpos($this->os, $myos) === false)) {
// this command will be executed only on the specified OS
$this->log("Not found in " . $this->os, Project::MSG_VERBOSE);
return 0;
}
if ($this->dir !== null) {
if ($this->dir->isDirectory()) {
$currdir = getcwd();
@chdir($this->dir->getPath());
} else {
throw new BuildException("Can't chdir to:" . $this->dir->__toString());
}
}
if ($this->escape == true) {
// FIXME - figure out whether this is correct behavior
$this->command = escapeshellcmd($this->command);
}
if ($this->error !== null) {
$this->command .= ' 2> ' . $this->error->getPath();
$this->log("Writing error output to: " . $this->error->getPath(), $this->logLevel);
}
if ($this->output !== null) {
$this->command .= ' 1> ' . $this->output->getPath();
$this->log("Writing standard output to: " . $this->output->getPath(), $this->logLevel);
} elseif ($this->spawn) {
$this->command .= ' 1>/dev/null';
$this->log("Sending ouptut to /dev/null", $this->logLevel);
}
// If neither output nor error are being written to file
// then we'll redirect error to stdout so that we can dump
// it to screen below.
if ($this->output === null && $this->error === null) {
$this->command .= ' 2>&1';
}
// we ignore the spawn boolean for windows
if ($this->spawn) {
$this->command .= ' &';
}
$this->log("Executing command: " . $this->command, $this->logLevel);
$output = array();
$return = null;
if ($this->passthru)
{
passthru($this->command, $return);
}
else
{
exec($this->command, $output, $return);
}
if ($this->dir !== null) {
@chdir($currdir);
}
foreach($output as $line) {
$this->log($line, ($this->logOutput ? Project::MSG_INFO : Project::MSG_VERBOSE));
}
if ($this->returnProperty) {
$this->project->setProperty($this->returnProperty, $return);
}
if ($this->outputProperty) {
$this->project->setProperty($this->outputProperty, implode("\n", $output));
}
if($return != 0 && $this->checkreturn) {
throw new BuildException("Task exited with code $return");
}
return $return;
}
/**
* The command to use.
* @param mixed $command String or string-compatible (e.g. w/ __toString()).
*/
function setCommand($command) {
$this->command = "" . $command;
}
/**
* Whether to use escapeshellcmd() to escape command.
* @param boolean $escape
*/
function setEscape($escape) {
$this->escape = (bool) $escape;
}
/**
* Specify the working directory for executing this command.
* @param PhingFile $dir
*/
function setDir(PhingFile $dir) {
$this->dir = $dir;
}
/**
* Specify OS (or muliple OS) that must match in order to execute this command.
* @param string $os
*/
function setOs($os) {
$this->os = (string) $os;
}
/**
* File to which output should be written.
* @param PhingFile $output
*/
function setOutput(PhingFile $f) {
$this->output = $f;
}
/**
* File to which error output should be written.
* @param PhingFile $output
*/
function setError(PhingFile $f) {
$this->error = $f;
}
/**
* Whether to use PHP's passthru() function instead of exec()
* @param boolean $passthru
*/
function setPassthru($passthru) {
$this->passthru = (bool) $passthru;
}
/**
* Whether to log returned output as MSG_INFO instead of MSG_VERBOSE
* @param boolean $passthru
*/
function setLogoutput($logOutput) {
$this->logOutput = (bool) $logOutput;
}
/**
* Whether to suppress all output and run in the background.
* @param boolean $spawn
*/
function setSpawn($spawn) {
$this->spawn = (bool) $spawn;
}
/**
* Whether to check the return code.
* @param boolean $checkreturn
*/
function setCheckreturn($checkreturn) {
$this->checkreturn = (bool) $checkreturn;
}
/**
* The name of property to set to return value from exec() call.
* @param string $prop
*/
function setReturnProperty($prop) {
$this->returnProperty = $prop;
}
/**
* The name of property to set to output value from exec() call.
* @param string $prop
*/
function setOutputProperty($prop) {
$this->outputProperty = $prop;
}
/**
* Set level of log messages generated (default = verbose)
* @param string $level
*/
public function setLevel($level)
{
switch ($level)
{
case "error": $this->logLevel = Project::MSG_ERR; break;
case "warning": $this->logLevel = Project::MSG_WARN; break;
case "info": $this->logLevel = Project::MSG_INFO; break;
case "verbose": $this->logLevel = Project::MSG_VERBOSE; break;
case "debug": $this->logLevel = Project::MSG_DEBUG; break;
}
}
}
| SimpleUpdates/Phing | classes/phing/tasks/system/ExecTask.php | PHP | lgpl-3.0 | 8,763 |
package uk.ac.manchester.cs.owl.owlapi;/**
* Author: Matthew Horridge<br>
* Stanford University<br>
* Bio-Medical Informatics Research Group<br>
* Date: 20/11/2013
*/
import com.google.gwt.user.client.rpc.CustomFieldSerializer;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;
import org.semanticweb.owlapi.model.OWLClassExpression;
import org.semanticweb.owlapi.model.OWLObjectPropertyExpression;
/**
* A server side implementation of CustomFieldSerilizer for serializing {@link uk.ac.manchester.cs.owl.owlapi.OWLObjectMinCardinalityImpl}
* objects.
*/
public class OWLObjectMinCardinalityImpl_CustomFieldSerializer extends CustomFieldSerializer<OWLObjectMinCardinalityImpl> {
/**
* @return <code>true</code> if a specialist {@link #instantiateInstance} is
* implemented; <code>false</code> otherwise
*/
@Override
public boolean hasCustomInstantiateInstance() {
return true;
}
/**
* Instantiates an object from the {@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
* <p/>
* Most of the time, this can be left unimplemented and the framework
* will instantiate the instance itself. This is typically used when the
* object being deserialized is immutable, hence it has to be created with
* its state already set.
* <p/>
* If this is overridden, the {@link #hasCustomInstantiateInstance} method
* must return <code>true</code> in order for the framework to know to call
* it.
*
* @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
* object's content from
* @return an object that has been loaded from the
* {@link com.google.gwt.user.client.rpc.SerializationStreamReader}
* @throws com.google.gwt.user.client.rpc.SerializationException
* if the instantiation operation is not
* successful
*/
@Override
public OWLObjectMinCardinalityImpl instantiateInstance(SerializationStreamReader streamReader) throws SerializationException {
return instantiate(streamReader);
}
public static OWLObjectMinCardinalityImpl instantiate(SerializationStreamReader streamReader) throws SerializationException {
int cardinality = streamReader.readInt();
OWLObjectPropertyExpression property = (OWLObjectPropertyExpression) streamReader.readObject();
OWLClassExpression filler = (OWLClassExpression) streamReader.readObject();
return new OWLObjectMinCardinalityImpl(property, cardinality, filler);
}
/**
* Serializes the content of the object into the
* {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
*
* @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
* object's content to
* @param instance the object instance to serialize
* @throws com.google.gwt.user.client.rpc.SerializationException
* if the serialization operation is not
* successful
*/
@Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLObjectMinCardinalityImpl instance) throws SerializationException {
serialize(streamWriter, instance);
}
public static void serialize(SerializationStreamWriter streamWriter, OWLObjectMinCardinalityImpl instance) throws SerializationException {
streamWriter.writeInt(instance.getCardinality());
streamWriter.writeObject(instance.getProperty());
streamWriter.writeObject(instance.getFiller());
}
/**
* Deserializes the content of the object from the
* {@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
*
* @param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
* object's content from
* @param instance the object instance to deserialize
* @throws com.google.gwt.user.client.rpc.SerializationException
* if the deserialization operation is not
* successful
*/
@Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLObjectMinCardinalityImpl instance) throws SerializationException {
deserialize(streamReader, instance);
}
public static void deserialize(SerializationStreamReader streamReader, OWLObjectMinCardinalityImpl instance) throws SerializationException {
}
}
| matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLObjectMinCardinalityImpl_CustomFieldSerializer.java | Java | lgpl-3.0 | 4,685 |
package edu.chip.carranet.sitemap;
import edu.chip.carranet.carradatapipeline.sitemap.ISiteMap;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
* @author Justin Quan
* @link http://chip.org
* Date: 3/17/11
*/
public class MockSiteMap implements ISiteMap {
private Map<String, MockConnectionInfo> connectionMap;
public MockSiteMap(Map<String, MockConnectionInfo> siteMap) {
this.connectionMap = siteMap;
}
public static class MockConnectionInfo {
private String connectionString;
private String user;
private String password;
public MockConnectionInfo(String connectionString, String user, String password) {
this.connectionString = connectionString;
this.user = user;
this.password = password;
}
public Connection makeConnection() throws SQLException {
return DriverManager.getConnection(this.connectionString, this.user, this.password);
}
}
@Override
public Connection getConnection(String identifier) throws SQLException {
return connectionMap.get(identifier).makeConnection();
}
}
| chb/i2b2-ssr | data_import/CarranetDataPipeline/src/test/java/edu/chip/carranet/sitemap/MockSiteMap.java | Java | lgpl-3.0 | 1,241 |
package org.energy_home.jemma.ah.zigbee.zcl.cluster.closures;
import org.energy_home.jemma.ah.cluster.zigbee.closures.SetYearDayScheduleResponse;
import org.energy_home.jemma.ah.zigbee.IZclFrame;
import org.energy_home.jemma.ah.zigbee.zcl.ZclValidationException;
import org.energy_home.jemma.ah.zigbee.zcl.lib.types.ZclDataTypeUI8;
public class ZclSetYearDayScheduleResponse {
public static SetYearDayScheduleResponse zclParse(IZclFrame zclFrame)
throws ZclValidationException
{
SetYearDayScheduleResponse r = new SetYearDayScheduleResponse();
r.Status = ZclDataTypeUI8 .zclParse(zclFrame);
return r;
}
public static void zclSerialize(IZclFrame zclFrame, SetYearDayScheduleResponse r)
throws ZclValidationException
{
ZclDataTypeUI8 .zclSerialize(zclFrame, r.Status);
}
public static int zclSize(SetYearDayScheduleResponse r)
throws ZclValidationException
{
int size = 0;
size += ZclDataTypeUI8 .zclSize(r.Status);
return size;
}
}
| elifesy/jemma | jemma.osgi.ah.zigbee/src/main/java/org/energy_home/jemma/ah/zigbee/zcl/cluster/closures/ZclSetYearDayScheduleResponse.java | Java | lgpl-3.0 | 1,055 |
#include "stdafx.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include "ls.h"
using namespace std;
void lsInit(vector<vector<int> > &costs, map<int, string> &NumToHost, map<string, struct RouterTab> &Table, struct Host &host) {
int len = costs.size();
for (int i = 0; i < len; i++) {
RouterTab tab = {};
string dst = "";
double cost = 0;
dst = NumToHost[i];
cost = costs[host.index][i];
tab.dst = dst;
if (cost == LS_MAX || cost == 0) {
continue;
}
else
tab.cost = cost;
tab.hop = dst;
Table[dst] = tab;
}host.vectorNum = Table.size();
}
void lsSendHello(map<string, struct RouterTab> &adjTable, string &hostname, string &content) {
ostringstream oss;
oss << "Hello" << endl;
oss << hostname << endl;
oss << adjTable.size() << endl;
for (auto it : adjTable) {
oss << it.second.dst << endl;
}content = oss.str();
}
void lsReceiveHello(string &content, string &hostname, map<string, struct RouterTab> &adjTable) {
istringstream iss(content);
string temp;
int vnum;
iss >> temp;
iss >> hostname;
iss >> vnum;
while (vnum--) {
RouterTab tab;
iss >> tab.dst;
tab.hop = tab.dst;
adjTable[tab.dst] = tab;
}
}
void lsSend(map<string, struct RouterTab> &adjTable, string &content, int &seqNum, struct Host &host) {
ostringstream oss;
oss << "Link State" << endl;
oss << host.name << endl;
oss << adjTable.size() << endl;
oss << seqNum << endl;
oss << 16 << endl;
map<string, struct RouterTab>::iterator it = adjTable.begin();
for (; it != adjTable.end(); it++) {
oss << (it->second).dst << ' ' << (it->second).hop << ' ' << (it->second).cost << '\n';
}
content = oss.str();
seqNum++;
}
void lsReceive(string &content, struct BufEntry &srcEntry) {
istringstream iss(content);
string tmp1, tmp2;
int vectorNum;
iss >> tmp1 >> tmp2;
iss >> srcEntry.src;
iss >> vectorNum;
iss >> srcEntry.seq >> srcEntry.age;
while (vectorNum--) {
RouterTab tab;
iss >> tab.dst >> tab.hop >> tab.cost;
srcEntry.Neighbors[tab.dst] = tab;
}
}
void lsUpdate(vector<vector<int> > &costs, struct BufEntry &entry, map<string, struct Host> &vHost) {
int neighbor_index = vHost[entry.src].index;
// merge neighbor's router_table into cost;
costs[neighbor_index] = vector<int>(costs.size(), LS_MAX);
int s = costs.size();
for (int i = 0; i < s; ++i) {
costs[i][neighbor_index] = LS_MAX;
}costs[neighbor_index][neighbor_index] = 0;
for (auto it : entry.Neighbors) {
costs[neighbor_index][vHost[it.first].index] = (it.second).cost;
costs[vHost[it.first].index][neighbor_index] = costs[neighbor_index][vHost[it.first].index];
}
}
void lsDijkstra(vector<vector<int> > &costs, map<string, RouterTab> &table, int srcIndex, map<int, string> &NumToHost) {
int VSIZE = costs.size();
int* dist = new int[VSIZE];
int* prev = new int[VSIZE];
bool* S = new bool[VSIZE];
for (int i = 0; i < VSIZE; i++) {
dist[i] = costs[srcIndex][i];
S[i] = false;
if (dist[i] == LS_MAX)
prev[i] = -1;
else
prev[i] = srcIndex;
}
dist[srcIndex] = 0;
S[srcIndex] = true;
for (int i = 2; i <= VSIZE; i++) {
int mindist = LS_MAX;
int u = srcIndex;
for (int j = 0; j < VSIZE; j++) {
if ((!S[j]) && dist[j] < mindist) {
u = j;
mindist = dist[j];
}
}
S[u] = true;
for (int j = 0; j < VSIZE; j++) {
if ((!S[j]) && costs[u][j] < LS_MAX) {
if (dist[u] + costs[u][j] < dist[j]) {
dist[j] = dist[u] + costs[u][j];
prev[j] = u;
}
}
}
}
table.clear();
for (int i = 0; i < VSIZE; i++) {
if (prev[i] != -1) {
int u = i;
while (prev[u] != srcIndex)
u = prev[u];
string dst = NumToHost[i];
string hop = NumToHost[u];
int newCost = dist[i];
table[dst].dst = dst;
table[dst].hop = hop;
table[dst].cost = newCost;
}
}
delete[] dist;
delete[] S;
delete[] prev;
} | VioletWind/Virtual-Routing | ls.cpp | C++ | lgpl-3.0 | 3,985 |
/*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.qualityprofile.ws;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.qualityprofile.BulkChangeResult;
import org.sonar.server.qualityprofile.QProfileRules;
import org.sonar.server.rule.index.RuleQuery;
import org.sonar.server.rule.ws.RuleQueryFactory;
import org.sonar.server.user.UserSession;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_03;
import static org.sonar.server.qualityprofile.ws.BulkChangeWsResponse.writeResponse;
import static org.sonar.server.qualityprofile.ws.QProfileReference.fromKey;
import static org.sonar.server.rule.ws.RuleWsSupport.defineGenericRuleSearchParameters;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.ACTION_ACTIVATE_RULES;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_TARGET_KEY;
import static org.sonarqube.ws.client.qualityprofile.QualityProfileWsParameters.PARAM_TARGET_SEVERITY;
public class ActivateRulesAction implements QProfileWsAction {
private final RuleQueryFactory ruleQueryFactory;
private final UserSession userSession;
private final QProfileRules qProfileRules;
private final DbClient dbClient;
private final QProfileWsSupport wsSupport;
public ActivateRulesAction(RuleQueryFactory ruleQueryFactory, UserSession userSession, QProfileRules qProfileRules, QProfileWsSupport wsSupport, DbClient dbClient) {
this.ruleQueryFactory = ruleQueryFactory;
this.userSession = userSession;
this.qProfileRules = qProfileRules;
this.dbClient = dbClient;
this.wsSupport = wsSupport;
}
public void define(WebService.NewController controller) {
WebService.NewAction activate = controller
.createAction(ACTION_ACTIVATE_RULES)
.setDescription("Bulk-activate rules on one quality profile.<br> " +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer Quality Profiles'</li>" +
" <li>Edit right on the specified quality profile</li>" +
"</ul>")
.setPost(true)
.setSince("4.4")
.setHandler(this);
defineGenericRuleSearchParameters(activate);
activate.createParam(PARAM_TARGET_KEY)
.setDescription("Quality Profile key on which the rule activation is done. To retrieve a quality profile key please see <code>api/qualityprofiles/search</code>")
.setDeprecatedKey("profile_key", "6.5")
.setRequired(true)
.setExampleValue(UUID_EXAMPLE_03);
activate.createParam(PARAM_TARGET_SEVERITY)
.setDescription("Severity to set on the activated rules")
.setDeprecatedKey("activation_severity", "6.5")
.setPossibleValues(Severity.ALL);
}
@Override
public void handle(Request request, Response response) throws Exception {
String qualityProfileKey = request.mandatoryParam(PARAM_TARGET_KEY);
userSession.checkLoggedIn();
BulkChangeResult result;
try (DbSession dbSession = dbClient.openSession(false)) {
QProfileDto profile = wsSupport.getProfile(dbSession, fromKey(qualityProfileKey));
OrganizationDto organization = wsSupport.getOrganization(dbSession, profile);
wsSupport.checkCanEdit(dbSession, organization, profile);
wsSupport.checkNotBuiltIn(profile);
RuleQuery ruleQuery = ruleQueryFactory.createRuleQuery(dbSession, request);
ruleQuery.setIncludeExternal(false);
result = qProfileRules.bulkActivateAndCommit(dbSession, profile, ruleQuery, request.param(PARAM_TARGET_SEVERITY));
}
writeResponse(result, response);
}
}
| Godin/sonar | server/sonar-server/src/main/java/org/sonar/server/qualityprofile/ws/ActivateRulesAction.java | Java | lgpl-3.0 | 4,656 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.03.18 at 12:10:58 PM EET
//
@javax.xml.bind.annotation.XmlSchema(namespace = "http://echa.europa.eu/schemas/iuclid5/20130101", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package eu.europa.echa.schemas.iuclid5._20130101.studyrecord.PHOTOCATALYTIC_ACTIVITY_SECTION;
| ideaconsult/i5 | iuclid_5_5-io/src/main/java/eu/europa/echa/schemas/iuclid5/_20130101/studyrecord/PHOTOCATALYTIC_ACTIVITY_SECTION/package-info.java | Java | lgpl-3.0 | 610 |
# -*- coding: utf-8 -*-
module Vnet::NodeApi
class SecurityGroupInterface < EventBase
class << self
include Vnet::Helpers::Event
def destroy_where(filter)
count = 0
model_class.dataset.where(filter).all.each { |model|
next if model.destroy.nil?
count += 1
dispatch_deleted_item_events(model)
}
count
end
#
# Internal methods:
#
private
def dispatch_created_item_events(model)
group = model.security_group
dispatch_event(ADDED_INTERFACE_TO_SG,
id: group.id,
interface_id: model.interface_id,
interface_cookie_id: group.interface_cookie_id(model.interface_id))
dispatch_update_sg_ip_addresses(group)
end
def dispatch_deleted_item_events(model)
group = model.security_group
dispatch_event(REMOVED_INTERFACE_FROM_SG,
id: group.id,
interface_id: model.interface_id)
dispatch_update_sg_ip_addresses(group)
# no dependencies
end
end
end
end
| akirapop/openvnet | vnet/lib/vnet/node_api/security_group_interface.rb | Ruby | lgpl-3.0 | 1,159 |
<?php
// settings for the READ server
$CFG->R_HOST = 'localhost';
$CFG->R_USER = 'ianseo';
$CFG->R_PASS = 'ianseo';
// settings for the WRITE Server
$CFG->W_HOST = 'localhost';
$CFG->W_USER = 'ianseo';
$CFG->W_PASS = 'ianseo';
/* DB Name */
$CFG->DB_NAME = 'ianseo';
// set the root directory
$CFG->ROOT_DIR = '/';
?> | brian-nelson/ianseo | src/config.inc.php | PHP | lgpl-3.0 | 322 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.duplications.statement.matcher;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import java.util.List;
import org.junit.Test;
import org.sonar.duplications.token.Token;
import org.sonar.duplications.token.TokenQueue;
public class OptTokenMatcherTest {
@Test(expected = IllegalArgumentException.class)
public void shouldNotAcceptNull() {
new OptTokenMatcher(null);
}
@Test
public void shouldMatch() {
TokenQueue tokenQueue = spy(new TokenQueue());
TokenMatcher delegate = mock(TokenMatcher.class);
OptTokenMatcher matcher = new OptTokenMatcher(delegate);
List<Token> output = mock(List.class);
assertThat(matcher.matchToken(tokenQueue, output), is(true));
verify(delegate).matchToken(tokenQueue, output);
verifyNoMoreInteractions(delegate);
verifyNoMoreInteractions(tokenQueue);
verifyNoMoreInteractions(output);
}
}
| SonarSource/sonarqube | sonar-duplications/src/test/java/org/sonar/duplications/statement/matcher/OptTokenMatcherTest.java | Java | lgpl-3.0 | 1,957 |
namespace OoMapper.Tests
{
using Xunit;
public class DeepMappingFacts : TestBase
{
[Fact]
public void Test()
{
Mapper.CreateMap<ComplexSourceChild, ComplexDestinationChild>();
Mapper.CreateMap<ComplexSource, ComplexDestination>();
var source = new ComplexSource
{
Some = new ComplexSourceChild {Property = "hello world"}
};
ComplexDestination map =
Mapper.Map<ComplexSource, ComplexDestination>(source);
Assert.Equal("hello world", map.Some.Property);
}
public class ComplexSource
{
public ComplexSourceChild Some { get; set; }
}
public class ComplexSourceChild
{
public string Property { get; set; }
}
public class ComplexDestinationChild
{
public string Property { get; set; }
}
public class ComplexDestination
{
public ComplexDestinationChild Some { get; set; }
}
}
} | hazzik/OoMapper | src/OoMapper.Tests/DeepMappingFacts.cs | C# | lgpl-3.0 | 905 |
/**
* Created by LABS on 30.08.2016.
*/
$('document').ready(function(){
$('#alerts').jplist({
itemsBox: '.list'
,itemPath: '.list-item'
,panelPath: '.jplist-panel'
});
});
function send_ajax_post_request(cve_id, software_id, option) {
$.ajax({
type: "POST",
url: "alerts.html",
data: {
csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
cve_id: cve_id,
software_id: software_id,
option: option
},
success: function (result) { location.reload(); }
});
}
function set_cve_as_negative(cve_id, software_id) {
send_ajax_post_request(cve_id, software_id, 'set_cve_as_negative');
}
function notify(cve_id, sw_id, sw) {
show_element('sending');
hide_element('sent_email_failed');
hide_element('sent_email_ok');
$('#sending').html('<div class="info-msg">sending alert for ' + sw + '</div>');
$.ajax({
type: "POST",
url: "alerts.html",
data: {
csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
software_id: sw_id,
option: 'notify'
},
success: function (result) {
if (result == 'failed') {
show_element('sent_email_failed');
$("#sent_email_failed").html('<div class="error-msg">failed to sent alert for ' + sw + '</div>');
} else {
location.reload();
}
hide_element('sending')
}
});
}
| fkie-cad/iva | frontend/iva/static/iva/js/alerts.js | JavaScript | lgpl-3.0 | 1,532 |
/* $Id$
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: .......
*
* File Description:
* .......
*
* Remark:
* This code was originally generated by application DATATOOL
* using the following specifications:
* 'blast.asn'.
*/
// standard includes
#include <ncbi_pch.hpp>
// generated includes
#include <objects/blast/Blast4_finish_params_reply.hpp>
// generated classes
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
END_objects_SCOPE // namespace ncbi::objects::
END_NCBI_SCOPE
/* Original file checksum: lines: 52, chars: 1693, CRC32: 7790ffb3 */
| kyungtaekLIM/PSI-BLASTexB | src/ncbi-blast-2.5.0+/c++/src/objects/blast/Blast4_finish_params_reply.cpp | C++ | lgpl-3.0 | 1,815 |
// Copyright 2015 The go-earthdollar Authors
// This file is part of the go-earthdollar library.
//
// The go-earthdollar library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-earthdollar 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 the go-earthdollar library. If not, see <http://www.gnu.org/licenses/>.
// Package tests implements execution of Earthdollar JSON tests.
package tests
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
)
var (
baseDir = filepath.Join(".", "files")
blockTestDir = filepath.Join(baseDir, "BlockchainTests")
stateTestDir = filepath.Join(baseDir, "StateTests")
transactionTestDir = filepath.Join(baseDir, "TransactionTests")
vmTestDir = filepath.Join(baseDir, "VMTests")
rlpTestDir = filepath.Join(baseDir, "RLPTests")
BlockSkipTests = []string{
// These tests are not valid, as they are out of scope for RLP and
// the consensus protocol.
"BLOCK__RandomByteAtTheEnd",
"TRANSCT__RandomByteAtTheEnd",
"BLOCK__ZeroByteAtTheEnd",
"TRANSCT__ZeroByteAtTheEnd",
"ChainAtoChainB_blockorder2",
"ChainAtoChainB_blockorder1",
}
/* Go client does not support transaction (account) nonces above 2^64. This
technically breaks consensus but is regarded as "reasonable
engineering constraint" as accounts cannot easily reach such high
nonce values in practice
*/
TransSkipTests = []string{"TransactionWithHihghNonce256"}
StateSkipTests = []string{}
VmSkipTests = []string{}
)
func readJson(reader io.Reader, value interface{}) error {
data, err := ioutil.ReadAll(reader)
if err != nil {
return fmt.Errorf("error reading JSON file: %v", err)
}
if err = json.Unmarshal(data, &value); err != nil {
if syntaxerr, ok := err.(*json.SyntaxError); ok {
line := findLine(data, syntaxerr.Offset)
return fmt.Errorf("JSON syntax error at line %v: %v", line, err)
}
return fmt.Errorf("JSON unmarshal error: %v", err)
}
return nil
}
func readJsonFile(fn string, value interface{}) error {
file, err := os.Open(fn)
if err != nil {
return err
}
defer file.Close()
err = readJson(file, value)
if err != nil {
return fmt.Errorf("%s in file %s", err.Error(), fn)
}
return nil
}
// findLine returns the line number for the given offset into data.
func findLine(data []byte, offset int64) (line int) {
line = 1
for i, r := range string(data) {
if int64(i) >= offset {
return
}
if r == '\n' {
line++
}
}
return
}
| Tzunami/go-earthdollar | tests/init.go | GO | lgpl-3.0 | 2,966 |
/*
* This file is part of MyPet
*
* Copyright © 2011-2016 Keyle
* MyPet is licensed under the GNU Lesser General Public License.
*
* MyPet is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MyPet 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.Keyle.MyPet.compat.v1_9_R2.entity.types;
import com.google.common.base.Optional;
import de.Keyle.MyPet.api.Configuration;
import de.Keyle.MyPet.api.entity.EntitySize;
import de.Keyle.MyPet.api.entity.MyPet;
import de.Keyle.MyPet.api.entity.types.MyWolf;
import de.Keyle.MyPet.compat.v1_9_R2.entity.EntityMyPet;
import net.minecraft.server.v1_9_R2.*;
import org.bukkit.DyeColor;
import java.util.UUID;
@EntitySize(width = 0.6F, height = 0.64f)
public class EntityMyWolf extends EntityMyPet {
private static final DataWatcherObject<Boolean> ageWatcher = DataWatcher.a(EntityMyWolf.class, DataWatcherRegistry.h);
protected static final DataWatcherObject<Byte> sitWatcher = DataWatcher.a(EntityMyWolf.class, DataWatcherRegistry.a);
protected static final DataWatcherObject<Optional<UUID>> ownerWatcher = DataWatcher.a(EntityMyWolf.class, DataWatcherRegistry.m);
private static final DataWatcherObject<Float> tailWatcher = DataWatcher.a(EntityMyWolf.class, DataWatcherRegistry.c);
private static final DataWatcherObject<Boolean> watcher = DataWatcher.a(EntityMyWolf.class, DataWatcherRegistry.h);
private static final DataWatcherObject<Integer> collarWatcher = DataWatcher.a(EntityMyWolf.class, DataWatcherRegistry.b);
protected boolean shaking;
protected boolean isWet;
protected float shakeCounter;
public EntityMyWolf(World world, MyPet myPet) {
super(world, myPet);
}
public void applySitting(boolean sitting) {
int i = this.datawatcher.get(sitWatcher);
if (sitting) {
this.datawatcher.set(sitWatcher, (byte) (i | 0x1));
} else {
this.datawatcher.set(sitWatcher, (byte) (i & 0xFFFFFFFE));
}
}
@Override
protected String getDeathSound() {
return "entity.wolf.death";
}
@Override
protected String getHurtSound() {
return "entity.wolf.hurt";
}
protected String getLivingSound() {
return this.random.nextInt(5) == 0 ? (getHealth() * 100 / getMaxHealth() <= 25 ? "entity.wolf.whine" : "entity.wolf.pant") : "entity.wolf.ambient";
}
public boolean handlePlayerInteraction(EntityHuman entityhuman, EnumHand enumhand, ItemStack itemStack) {
if (super.handlePlayerInteraction(entityhuman, enumhand, itemStack)) {
return true;
}
if (getOwner().equals(entityhuman)) {
if (itemStack != null && canUseItem()) {
if (itemStack.getItem() == Items.DYE && itemStack.getData() != getMyPet().getCollarColor().getWoolData()) {
if (itemStack.getData() <= 15) {
if (getOwner().getPlayer().isSneaking()) {
getMyPet().setCollarColor(DyeColor.getByWoolData((byte) itemStack.getData()));
if (!entityhuman.abilities.canInstantlyBuild) {
if (--itemStack.count <= 0) {
entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null);
}
}
return true;
} else {
this.datawatcher.set(collarWatcher, 0);
updateVisuals();
return false;
}
}
} else if (Configuration.MyPet.Wolf.GROW_UP_ITEM.compare(itemStack) && getMyPet().isBaby() && getOwner().getPlayer().isSneaking()) {
if (!entityhuman.abilities.canInstantlyBuild) {
if (--itemStack.count <= 0) {
entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, null);
}
}
getMyPet().setBaby(false);
return true;
}
}
}
return false;
}
protected void initDatawatcher() {
super.initDatawatcher();
this.datawatcher.register(ageWatcher, false); // age
this.datawatcher.register(sitWatcher, (byte) 0); // tamed/angry/sitting
this.datawatcher.register(ownerWatcher, Optional.absent()); // owner
this.datawatcher.register(tailWatcher, 20F); // tail height
this.datawatcher.register(watcher, false); // N/A
this.datawatcher.register(collarWatcher, 14); // collar color
}
@Override
public void updateVisuals() {
this.datawatcher.set(ageWatcher, getMyPet().isBaby());
byte b0 = this.datawatcher.get(sitWatcher);
if (getMyPet().isTamed()) {
this.datawatcher.set(sitWatcher, (byte) (b0 | 0x4));
} else {
this.datawatcher.set(sitWatcher, (byte) (b0 & 0xFFFFFFFB));
}
b0 = this.datawatcher.get(sitWatcher);
if (getMyPet().isAngry()) {
this.datawatcher.set(sitWatcher, (byte) (b0 | 0x2));
} else {
this.datawatcher.set(sitWatcher, (byte) (b0 & 0xFFFFFFFD));
}
this.datawatcher.set(collarWatcher, (int) getMyPet().getCollarColor().getWoolData());
}
@Override
public void onLivingUpdate() {
super.onLivingUpdate();
if (this.isWet && !this.shaking && this.onGround) {
this.shaking = true;
this.shakeCounter = 0.0F;
this.world.broadcastEntityEffect(this, (byte) 8);
}
if (isInWater()) // -> is in water
{
this.isWet = true;
this.shaking = false;
this.shakeCounter = 0.0F;
} else if ((this.isWet || this.shaking) && this.shaking) {
if (this.shakeCounter == 0.0F) {
makeSound("entity.wolf.shake", 1.0F, (this.random.nextFloat() - this.random.nextFloat()) * 0.2F + 1.0F);
}
this.shakeCounter += 0.05F;
if (this.shakeCounter - 0.05F >= 2.0F) {
this.isWet = false;
this.shaking = false;
this.shakeCounter = 0.0F;
}
if (this.shakeCounter > 0.4F) {
float locY = (float) this.getBoundingBox().b;
int i = (int) (MathHelper.sin((this.shakeCounter - 0.4F) * 3.141593F) * 7.0F);
for (; i >= 0; i--) {
float offsetX = (this.random.nextFloat() * 2.0F - 1.0F) * this.width * 0.5F;
float offsetZ = (this.random.nextFloat() * 2.0F - 1.0F) * this.width * 0.5F;
this.world.addParticle(EnumParticle.WATER_SPLASH, this.locX + offsetX, locY + 0.8F, this.locZ + offsetZ, this.motX, this.motY, this.motZ);
}
}
}
float tailHeight = 20F * (getHealth() / getMaxHealth());
if (this.datawatcher.get(tailWatcher) != tailHeight) {
this.datawatcher.set(tailWatcher, tailHeight); // update tail height
}
}
@Override
public void playPetStepSound() {
makeSound("entity.wolf.step", 0.15F, 1.0F);
}
public void setHealth(float i) {
super.setHealth(i);
float tailHeight = 20F * (i / getMaxHealth());
this.datawatcher.set(tailWatcher, tailHeight);
}
public MyWolf getMyPet() {
return (MyWolf) myPet;
}
} | jjm223/MyPet | modules/v1_9_R2/src/main/java/de/Keyle/MyPet/compat/v1_9_R2/entity/types/EntityMyWolf.java | Java | lgpl-3.0 | 8,147 |
/*
* This file is part of CasADi.
*
* CasADi -- A symbolic framework for dynamic optimization.
* Copyright (C) 2010-2014 Joel Andersson, Joris Gillis, Moritz Diehl,
* K.U. Leuven. All rights reserved.
* Copyright (C) 2011-2014 Greg Horn
*
* CasADi is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* CasADi 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 CasADi; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "linear_interpolant.hpp"
using namespace std;
namespace casadi {
extern "C"
int CASADI_INTERPOLANT_LINEAR_EXPORT
casadi_register_interpolant_linear(Interpolant::Plugin* plugin) {
plugin->creator = LinearInterpolant::creator;
plugin->name = "linear";
plugin->doc = LinearInterpolant::meta_doc.c_str();
plugin->version = CASADI_VERSION;
plugin->options = &LinearInterpolant::options_;
return 0;
}
extern "C"
void CASADI_INTERPOLANT_LINEAR_EXPORT casadi_load_interpolant_linear() {
Interpolant::registerPlugin(casadi_register_interpolant_linear);
}
Options LinearInterpolant::options_
= {{&Interpolant::options_},
{{"lookup_mode",
{OT_STRINGVECTOR,
"Sets, for each grid dimenion, the lookup algorithm used to find the correct index. "
"'linear' uses a for-loop + break; "
"'exact' uses floored division (only for uniform grids)."}}
}
};
LinearInterpolant::
LinearInterpolant(const string& name,
const std::vector<double>& grid,
const std::vector<casadi_int>& offset,
const vector<double>& values,
casadi_int m)
: Interpolant(name, grid, offset, values, m) {
}
LinearInterpolant::~LinearInterpolant() {
}
void LinearInterpolant::init(const Dict& opts) {
// Call the base class initializer
Interpolant::init(opts);
lookup_mode_ = Interpolant::interpret_lookup_mode(lookup_modes_, grid_, offset_);
// Needed by casadi_interpn
alloc_w(ndim_, true);
alloc_iw(2*ndim_, true);
}
int LinearInterpolant::
eval(const double** arg, double** res, casadi_int* iw, double* w, void* mem) const {
if (res[0]) {
casadi_interpn(res[0], ndim_, get_ptr(grid_), get_ptr(offset_),
get_ptr(values_), arg[0], get_ptr(lookup_mode_), m_, iw, w);
}
return 0;
}
void LinearInterpolant::codegen_body(CodeGenerator& g) const {
g << " if (res[0]) {\n"
<< " " << g.interpn("res[0]", ndim_, g.constant(grid_), g.constant(offset_),
g.constant(values_), "arg[0]", g.constant(lookup_mode_), m_, "iw", "w") << "\n"
<< " }\n";
}
Function LinearInterpolant::
get_jacobian(const std::string& name,
const std::vector<std::string>& inames,
const std::vector<std::string>& onames,
const Dict& opts) const {
Function ret;
ret.own(new LinearInterpolantJac(name));
ret->construct(opts);
return ret;
}
Function LinearInterpolantJac::
get_jacobian(const std::string& name,
const std::vector<std::string>& inames,
const std::vector<std::string>& onames,
const Dict& opts) const {
std::vector<MX> args = mx_in();
std::vector<MX> res(n_out_);
for (casadi_int i=0;i<n_out_;++i)
res[i] = DM(size1_out(i), size2_out(i));
Function f("f", args, res);
return f->get_jacobian(name, inames, onames, Dict());
}
void LinearInterpolantJac::init(const Dict& opts) {
// Call the base class initializer
FunctionInternal::init(opts);
// Needed by casadi_interpn
auto m = derivative_of_.get<LinearInterpolant>();
alloc_w(2*m->ndim_ + m->m_, true);
alloc_iw(2*m->ndim_, true);
}
int LinearInterpolantJac::
eval(const double** arg, double** res, casadi_int* iw, double* w, void* mem) const {
auto m = derivative_of_.get<LinearInterpolant>();
casadi_interpn_grad(res[0], m->ndim_, get_ptr(m->grid_), get_ptr(m->offset_),
get_ptr(m->values_), arg[0], get_ptr(m->lookup_mode_), m->m_, iw, w);
return 0;
}
void LinearInterpolantJac::codegen_body(CodeGenerator& g) const {
auto m = derivative_of_.get<LinearInterpolant>();
g << " " << g.interpn_grad("res[0]", m->ndim_,
g.constant(m->grid_), g.constant(m->offset_), g.constant(m->values_),
"arg[0]", g.constant(m->lookup_mode_), m->m_, "iw", "w") << "\n";
}
} // namespace casadi
| ghorn/casadi | casadi/solvers/linear_interpolant.cpp | C++ | lgpl-3.0 | 5,093 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import classNames from 'classnames';
import { sortBy } from 'lodash';
import * as React from 'react';
import { Profile } from '../../../api/quality-profiles';
import DocumentationTooltip from '../../../components/common/DocumentationTooltip';
import FacetBox from '../../../components/facet/FacetBox';
import FacetHeader from '../../../components/facet/FacetHeader';
import FacetItem from '../../../components/facet/FacetItem';
import FacetItemsList from '../../../components/facet/FacetItemsList';
import { translate } from '../../../helpers/l10n';
import { Dict } from '../../../types/types';
import { FacetKey, Query } from '../query';
interface Props {
activation: boolean | undefined;
compareToProfile: string | undefined;
languages: string[];
onChange: (changes: Partial<Query>) => void;
onToggle: (facet: FacetKey) => void;
open: boolean;
referencedProfiles: Dict<Profile>;
value: string | undefined;
}
export default class ProfileFacet extends React.PureComponent<Props> {
handleItemClick = (selected: string) => {
const newValue = this.props.value === selected ? '' : selected;
this.props.onChange({
activation: this.props.activation === undefined ? true : this.props.activation,
compareToProfile: undefined,
profile: newValue
});
};
handleHeaderClick = () => this.props.onToggle('profile');
handleClear = () =>
this.props.onChange({
activation: undefined,
activationSeverities: [],
compareToProfile: undefined,
inheritance: undefined,
profile: undefined
});
handleActiveClick = (event: React.SyntheticEvent<HTMLElement>) => {
this.stopPropagation(event);
this.props.onChange({ activation: true, compareToProfile: undefined });
};
handleInactiveClick = (event: React.SyntheticEvent<HTMLElement>) => {
this.stopPropagation(event);
this.props.onChange({ activation: false, compareToProfile: undefined });
};
stopPropagation = (event: React.SyntheticEvent<HTMLElement>) => {
event.preventDefault();
event.stopPropagation();
event.currentTarget.blur();
};
getTextValue = () => {
const { referencedProfiles, value } = this.props;
if (value) {
const profile = referencedProfiles[value];
const name = (profile && `${profile.name} ${profile.languageName}`) || value;
return [name];
} else {
return [];
}
};
getTooltip = (profile: Profile) => {
const base = `${profile.name} ${profile.languageName}`;
return profile.isBuiltIn ? `${base} (${translate('quality_profiles.built_in')})` : base;
};
renderName = (profile: Profile) => (
<>
{profile.name}
<span className="note little-spacer-left">
{profile.languageName}
{profile.isBuiltIn && ` (${translate('quality_profiles.built_in')})`}
</span>
</>
);
renderActivation = (profile: Profile) => {
const isCompare = profile.key === this.props.compareToProfile;
const activation = isCompare ? true : this.props.activation;
return (
<>
<span
aria-checked={activation}
className={classNames('js-active', 'facet-toggle', 'facet-toggle-green', {
'facet-toggle-active': activation
})}
onClick={isCompare ? this.stopPropagation : this.handleActiveClick}
role="radio"
tabIndex={-1}>
active
</span>
<span
aria-checked={!activation}
className={classNames('js-inactive', 'facet-toggle', 'facet-toggle-red', {
'facet-toggle-active': !activation
})}
onClick={isCompare ? this.stopPropagation : this.handleInactiveClick}
role="radio"
tabIndex={-1}>
inactive
</span>
</>
);
};
renderItem = (profile: Profile) => {
const active = [this.props.value, this.props.compareToProfile].includes(profile.key);
return (
<FacetItem
active={active}
className={this.props.compareToProfile === profile.key ? 'compare' : undefined}
key={profile.key}
name={this.renderName(profile)}
onClick={this.handleItemClick}
stat={this.renderActivation(profile)}
tooltip={this.getTooltip(profile)}
value={profile.key}
/>
);
};
render() {
const { languages, referencedProfiles } = this.props;
let profiles = Object.values(referencedProfiles);
if (languages.length > 0) {
profiles = profiles.filter(profile => languages.includes(profile.language));
}
profiles = sortBy(
profiles,
profile => profile.name.toLowerCase(),
profile => profile.languageName
);
return (
<FacetBox property="profile">
<FacetHeader
name={translate('coding_rules.facet.qprofile')}
onClear={this.handleClear}
onClick={this.handleHeaderClick}
open={this.props.open}
values={this.getTextValue()}>
<DocumentationTooltip
className="spacer-left"
content={translate('coding_rules.facet.qprofile.help')}
links={[
{
href: '/documentation/instance-administration/quality-profiles/',
label: translate('coding_rules.facet.qprofile.link')
}
]}
/>
</FacetHeader>
{this.props.open && <FacetItemsList>{profiles.map(this.renderItem)}</FacetItemsList>}
</FacetBox>
);
}
}
| SonarSource/sonarqube | server/sonar-web/src/main/js/apps/coding-rules/components/ProfileFacet.tsx | TypeScript | lgpl-3.0 | 6,313 |
package uk.co.shadeddimensions.library.gui;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import uk.co.shadeddimensions.library.gui.element.ElementBase;
import uk.co.shadeddimensions.library.gui.element.ElementBaseContainer;
import uk.co.shadeddimensions.library.gui.element.ElementCrafting;
import uk.co.shadeddimensions.library.gui.element.ElementScrollPanel;
import uk.co.shadeddimensions.library.gui.element.ElementText;
/***
* Turns a string into multiple GUI elements for use within a {@link ElementBaseContainer} or {@link ElementScrollPanel}.
*
* @author Alz454
*/
public class Parser
{
FontRenderer fontRenderer;
IGuiBase parentGui;
ArrayList<ElementBase> parsedElements;
int maxWidth, currentX, currentY;
public Parser(IGuiBase parent)
{
parsedElements = new ArrayList<ElementBase>();
parentGui = parent;
maxWidth = -1;
currentX = currentY = 0;
fontRenderer = Minecraft.getMinecraft().fontRenderer;
}
public ArrayList<ElementBase> parse(String string)
{
// testing, for now
parsedElements.add(new ElementCrafting(parentGui, maxWidth / 2 - 5, currentY, 0).addAllGridSlots(new ItemStack[] { new ItemStack(Block.stone), new ItemStack(Block.stone), null, new ItemStack(Block.stone), new ItemStack(Block.stone), null, null, null, null }).addOutputSlot(new ItemStack(Block.stoneBrick)));
parsedElements.add(new ElementCrafting(parentGui, 0, currentY, 1).addBothFurnaceSlots(new ItemStack[] { new ItemStack(Block.cobblestone), new ItemStack(Item.coal) }).addOutputSlot(new ItemStack(Block.stone)));
currentY += parsedElements.get(parsedElements.size() - 1).getHeight() + 5;
parseText(string);
currentY += 5;
parsedElements.add(new ElementCrafting(parentGui, maxWidth / 2 - 5, currentY, 0).addAllGridSlots(new ItemStack[] { new ItemStack(Block.stone), new ItemStack(Block.stone), null, new ItemStack(Block.stone), new ItemStack(Block.stone), null, null, null, null }).addOutputSlot(new ItemStack(Block.stoneBrick)));
parsedElements.add(new ElementCrafting(parentGui, 0, currentY, 1).addBothFurnaceSlots(new ItemStack[] { new ItemStack(Block.cobblestone), new ItemStack(Item.coal) }).addOutputSlot(new ItemStack(Block.stone)));
currentY += parsedElements.get(parsedElements.size() - 1).getHeight() + 5;
parseText("And that's how you make Stone Bricks!");
return parsedElements;
}
@SuppressWarnings("unchecked")
private void parseText(String string)
{
if (maxWidth != -1 && fontRenderer.getStringWidth(string) > maxWidth)
{
List<String> list = fontRenderer.listFormattedStringToWidth(string, maxWidth);
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); currentY += fontRenderer.FONT_HEIGHT)
{
parsedElements.add(new ElementText(parentGui, currentX, currentY, iterator.next(), null, 0xFFFFFF, false));
}
}
else
{
parsedElements.add(new ElementText(parentGui, currentX, currentY, string, null, 0xFFFFFF, false));
currentX += fontRenderer.getStringWidth(string);
}
}
public Parser setMaxWidth(int width)
{
maxWidth = width;
return this;
}
}
| tterrag1098/library | common/uk/co/shadeddimensions/library/gui/Parser.java | Java | lgpl-3.0 | 3,540 |
require 'spec_helper'
require 'fortnox/api'
require 'fortnox/api/mappers/default_delivery_types'
require 'fortnox/api/mappers/examples/mapper'
describe Fortnox::API::Mapper::DefaultDeliveryTypes do
key_map = {}
it_behaves_like 'mapper', key_map do
let(:mapper){ described_class.new }
end
end
| ehannes/fortnox-api | spec/fortnox/api/mappers/default_delivery_types_spec.rb | Ruby | lgpl-3.0 | 304 |
using MemAnalyzer;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace MemAnalyzer_uTest
{
[TestClass]
public class ProcessRenamerTests
{
[TestMethod]
public void Can_Round_Trip()
{
XmlSerializer ser = new XmlSerializer(typeof(ProcessRenamer));
ProcessRenamer renamer = new ProcessRenamer();
renamer.ProcessRenamers.Add(new ProcessRenamer.RenameRule("w3wp.exe", new List<string> { "First" }, new List<string> { "Not" }, "NewW3wp.exe"));
var mem = new MemoryStream();
ser.Serialize(mem, renamer);
mem.Position = 0;
Console.WriteLine(Encoding.UTF8.GetString(mem.ToArray()));
ProcessRenamer renNew = (ProcessRenamer)ser.Deserialize(mem);
Assert.AreEqual(renamer.ProcessRenamers.Count, renNew.ProcessRenamers.Count);
Assert.AreEqual(renamer.ProcessRenamers[0].CmdLineSubstrings.Count, renNew.ProcessRenamers[0].CmdLineSubstrings.Count);
Assert.AreEqual(renamer.ProcessRenamers[0].CmdLineSubstrings[0], renNew.ProcessRenamers[0].CmdLineSubstrings[0]);
Assert.AreEqual(renamer.ProcessRenamers[0].ExeName, renNew.ProcessRenamers[0].ExeName);
Assert.AreEqual(renamer.ProcessRenamers[0].NewExeName, renNew.ProcessRenamers[0].NewExeName);
Assert.AreEqual(renamer.ProcessRenamers[0].NotCmdLineSubstrings.Count, renNew.ProcessRenamers[0].NotCmdLineSubstrings.Count);
Assert.AreEqual(renamer.ProcessRenamers[0].NotCmdLineSubstrings[0], renNew.ProcessRenamers[0].NotCmdLineSubstrings[0]);
}
[TestMethod]
public void Keep_Name_When_Empty()
{
ProcessRenamer ren = new ProcessRenamer();
Assert.AreEqual("exe", ren.Rename("exe", "args"));
}
[TestMethod]
public void Substring_Match_Forces_Rename()
{
ProcessRenamer ren = new ProcessRenamer();
ren.ProcessRenamers.Add(new ProcessRenamer.RenameRule("exe", new List<string> { "ind" }, null, "NewExe"));
Assert.AreEqual("NewExe", ren.Rename("exe", "-index"));
Assert.AreEqual("somethingElse", ren.Rename("somethingElse", "-index"));
}
[TestMethod]
public void Substring_Match_Is_And_Wise()
{
ProcessRenamer ren = new ProcessRenamer();
ren.ProcessRenamers.Add(new ProcessRenamer.RenameRule("exe", new List<string> { "-index", "-second" }, null, "NewExe"));
Assert.AreEqual("exe", ren.Rename("exe", "-index"));
Assert.AreEqual("exe", ren.Rename("exe", "-second"));
Assert.AreEqual("NewExe", ren.Rename("exe", "-second -index"));
}
[TestMethod]
public void Substring_Not_Match_Is_Or_Wise()
{
ProcessRenamer ren = new ProcessRenamer();
ren.ProcessRenamers.Add(new ProcessRenamer.RenameRule("exe", new List<string> { "-i", "-s" },
new List<string> { "-index", "-second" }, "NewExe"));
Assert.AreEqual("NewExe", ren.Rename("exe", "-i -s"));
Assert.AreEqual("NewExe", ren.Rename("exe", "-i -s"));
Assert.AreEqual("exe", ren.Rename("exe", "-i -s -index"));
Assert.AreEqual("exe", ren.Rename("exe", "-i -s -second"));
Assert.AreEqual("exe", ren.Rename("exe", "-i -s -second -index"));
}
}
}
| Alois-xx/MemAnalyzer | MemAnalyzer_uTest/ProcessRenamerTests.cs | C# | lgpl-3.0 | 3,591 |
<?php
namespace Iotize\Bundle\UserBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('sym_fo_col_user');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| ewidance/IoTize-server | src/Iotize/Bundle/UserBundle/DependencyInjection/Configuration.php | PHP | lgpl-3.0 | 888 |
// <copyright file="InvoiceVersion.cs" company="Allors bvba">
// Copyright (c) Allors bvba. All rights reserved.
// Licensed under the LGPL license. See LICENSE file in the project root for full license information.
// </copyright>
namespace Allors.Repository
{
using System;
using Allors.Repository.Attributes;
#region Allors
[Id("683DF770-70BE-4E31-830A-B9DD9031030D")]
#endregion
public partial interface InvoiceVersion : Version
{
#region Allors
[Id("3C21D07A-3723-4D0C-BCDF-2A699DB6794F")]
[AssociationId("2DF9BA58-5405-4205-8368-4C4F26437A22")]
[RoleId("42E7DA43-55F7-44F4-9FED-82EA966BBADB")]
[Indexed]
#endregion
[Size(-1)]
[Workspace]
string Comment { get; set; }
#region Allors
[Id("85356434-312C-4147-8D32-D27BE1B103B6")]
[AssociationId("0C448664-2CAC-4899-9F19-BA88AEE229E7")]
[RoleId("39F59849-515F-45F4-8668-237D8907E513")]
[Indexed]
#endregion
[Multiplicity(Multiplicity.ManyToOne)]
[Workspace]
User CreatedBy { get; set; }
#region Allors
[Id("1E73052D-5404-4D10-B353-493906CED780")]
[AssociationId("0704502C-5A65-4E44-9743-3879DD25207E")]
[RoleId("3B4F3C0D-B711-4BB7-8C79-BA99388645B9")]
#endregion
[Workspace]
DateTime CreationDate { get; set; }
#region Allors
[Id("93C86CD1-0329-4303-8EC4-DAAB6BF451C1")]
[AssociationId("FADD905C-1682-4307-8DD0-9B231279A37C")]
[RoleId("CCBD503A-9424-4571-A266-D8F54DDADC67")]
#endregion
[Workspace]
DateTime LastModifiedDate { get; set; }
#region Allors
[Id("3A694B6A-A891-418C-9A7C-3709978B7761")]
[AssociationId("C1422EA3-1FD4-4082-9768-CBBD955062C5")]
[RoleId("6C9A4674-0ACC-4279-B23F-7F20AFA50391")]
#endregion
[Workspace]
[Size(-1)]
string InternalComment { get; set; }
#region Allors
[Id("2B43A67D-2E2A-4D10-B4A7-024C85B5FC74")]
[AssociationId("FC35C74E-471C-4FBD-98F9-A303B812AA23")]
[RoleId("34225276-6C0C-4D34-A158-00420DACD434")]
#endregion
[Multiplicity(Multiplicity.ManyToOne)]
[Workspace]
[Indexed]
Currency AssignedCurrency { get; set; }
#region Allors
[Id("6F65890E-B409-4A70-887A-778C6703AEFB")]
[AssociationId("95E25BDE-EB9A-4F15-8092-2ED4CE05F58C")]
[RoleId("41CF0543-FE36-44A4-ACF1-8277D08274E3")]
#endregion
[Size(-1)]
[Workspace]
string Description { get; set; }
#region Allors
[Id("56151707-E3E4-4CE0-AB6A-63C64DD42DC6")]
[AssociationId("1D735AD7-491F-412F-BECB-D9385357FF3D")]
[RoleId("FF2EB983-450D-443C-8D34-4D28A2AEFB71")]
#endregion
[Size(-1)]
[Workspace]
string CustomerReference { get; set; }
#region Allors
[Id("6C96867C-D07F-4AB4-BD7D-5E622A5B55BE")]
[AssociationId("1E852B92-0AA6-4AD8-85E0-73A6C70DD4AA")]
[RoleId("4F49FCB5-46A2-434A-9A91-AB5500365DCE")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal AmountPaid { get; set; }
#region Allors
[Id("CCFACA15-C8BC-4260-AA9E-0B4739281590")]
[AssociationId("4CDD5CE8-8825-421E-A5DB-1D6A0E2F26CD")]
[RoleId("6ADC6E83-0FA4-4F66-AE3F-96DEF30979FE")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal TotalDiscount { get; set; }
#region Allors
[Id("49FA267E-4801-4347-852C-BFA556FDB4B5")]
[AssociationId("78991711-4EE5-4DD7-AF14-5915B8B0585D")]
[RoleId("E93F4651-8D75-49B7-ACE1-0D93A5C6F702")]
#endregion
[Multiplicity(Multiplicity.ManyToOne)]
[Indexed]
[Workspace]
BillingAccount BillingAccount { get; set; }
#region Allors
[Id("5913C137-F2C7-4C77-B005-2935853CE2A8")]
[AssociationId("4409ED13-4614-4069-ACBF-5ED52DC53F77")]
[RoleId("9E266B19-DE3E-4FC6-9B7A-E999139A8A3E")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal TotalIncVat { get; set; }
#region Allors
[Id("D17019EC-A2AB-4063-B862-EF95A867CE61")]
[AssociationId("04DA9D01-91A1-403B-988F-43BA2DF9FB16")]
[RoleId("043FDAFA-32BE-42B9-B9C5-38DA573AB680")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal TotalSurcharge { get; set; }
#region Allors
[Id("3D03D4F2-E82C-4802-BABC-ADD692925C44")]
[AssociationId("996AFC47-7239-488B-A558-6E67BD4BC38C")]
[RoleId("82B5CD63-FC62-4C1C-9FB6-046C8731B333")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal TotalBasePrice { get; set; }
#region Allors
[Id("d60855bf-af6c-4871-927f-9e1ac689979a")]
[AssociationId("203ffebd-4cd6-40ad-96c1-d1e46b2b91f3")]
[RoleId("87ad1baa-4dd1-494d-8eab-8bf6319fa18c")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal GrandTotal { get; set; }
#region Allors
[Id("4F0BDB92-1D82-4489-AF4B-35000DC8EA6A")]
[AssociationId("684D2BBF-CACB-4256-AE82-CBA65A03D054")]
[RoleId("EC9CDE94-354A-4850-A10B-2B0845CB567C")]
#endregion
[Workspace]
DateTime InvoiceDate { get; set; }
#region Allors
[Id("F4B96308-2791-4A0B-A83D-462D22141968")]
[AssociationId("683FCC67-EA7F-4E1A-8C88-8914E761A9B4")]
[RoleId("AC3E7EFC-6FB8-45B5-8D6B-67618E522591")]
#endregion
[Workspace]
DateTime EntryDate { get; set; }
#region Allors
[Id("D5A20009-50CC-4605-AAA1-554C6B478931")]
[AssociationId("701CE24A-A0B6-4503-B773-615F083AC733")]
[RoleId("6FEAB01B-F73F-4336-A62E-5ECA563F9A50")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal TotalShippingAndHandling { get; set; }
#region Allors
[Id("2B3F165E-27C4-461B-9A0B-6107CEC37200")]
[AssociationId("E7809A02-A053-4C6F-9734-B7730A7BF965")]
[RoleId("76DE0F8E-339B-4A93-8254-15D641180F3D")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal TotalExVat { get; set; }
#region Allors
[Id("1a9136c4-1d51-4db7-a434-97e4d87bdba1")]
[AssociationId("54118780-6f82-4d58-9c99-9ec2a5419bc5")]
[RoleId("08326ef0-2802-488e-9d12-67c4ee7e13a7")]
#endregion
[Multiplicity(Multiplicity.OneToMany)]
[Workspace]
[Indexed]
OrderAdjustment[] OrderAdjustments { get; set; }
#region Allors
[Id("E6F77579-FB47-42B1-8A0C-D699A491AA18")]
[AssociationId("4E76262F-31BB-42D2-9406-7E3BFC118609")]
[RoleId("C6D16AC9-A816-469D-BBB8-C864FE556E3A")]
#endregion
[Multiplicity(Multiplicity.ManyToMany)]
[Indexed]
[Workspace]
SalesTerm[] SalesTerms { get; set; }
#region Allors
[Id("05D98EF9-5464-4C37-A833-47B76DA57F24")]
[AssociationId("B74F0010-BFA5-4B5D-8C3D-589C899BE378")]
[RoleId("E43CA923-899B-4CDF-BA96-5A69A795BDD1")]
#endregion
[Size(256)]
[Workspace]
string InvoiceNumber { get; set; }
#region Allors
[Id("CCCAFE62-A111-4000-852C-1621B5B009EA")]
[AssociationId("13D86579-A0A5-46C5-BC95-25EA54F985CC")]
[RoleId("F09B1D69-462F-4A0C-A0F5-2F7D1F10EBB4")]
#endregion
[Size(-1)]
[Workspace]
string Message { get; set; }
#region Allors
[Id("141D8BBF-5EE1-4521-BFBC-34D9F69BEADA")]
[AssociationId("EA626F7E-A89E-4BA4-A5AE-A01FF4514567")]
[RoleId("65F299CF-5D23-4C72-95AB-548F20437364")]
#endregion
[Multiplicity(Multiplicity.ManyToOne)]
[Indexed]
[Workspace]
VatRegime AssignedVatRegime { get; set; }
#region Allors
[Id("850af264-a601-4070-ae75-1c608aacb0dc")]
[AssociationId("b5172607-a7f5-41f8-aabc-d0e376369781")]
[RoleId("a8b85fbf-54e7-4f37-a8e8-b026700d374e")]
#endregion
[Multiplicity(Multiplicity.ManyToOne)]
[Indexed]
[Workspace]
VatRegime DerivedVatRegime { get; set; }
#region Allors
[Id("613afd54-e378-4998-ba2d-777f691c0cf7")]
[AssociationId("78ebb5ae-c1a3-4734-b0e0-339c2d3c5c11")]
[RoleId("dfb8b271-1a14-41d8-b50b-863b3bcf0fa7")]
#endregion
[Multiplicity(Multiplicity.ManyToOne)]
[Indexed]
[Workspace]
IrpfRegime AssignedIrpfRegime { get; set; }
#region Allors
[Id("c7f5396d-026c-4036-916c-c3b91b7fa288")]
[AssociationId("0190d571-9dc2-43f1-87fb-79c35e49d3fd")]
[RoleId("15845da0-c31e-418b-839b-8642619a0732")]
#endregion
[Multiplicity(Multiplicity.ManyToOne)]
[Indexed]
[Workspace]
IrpfRegime DerivedIrpfRegime { get; set; }
#region Allors
[Id("070DDB3E-F6F6-42C1-B723-4D8C406BD2E8")]
[AssociationId("13275A3E-C5ED-4A21-8854-998FB57414F0")]
[RoleId("93A2735C-0C71-40D5-A1C2-392141C2367F")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal TotalVat { get; set; }
#region Allors
[Id("7E572C4E-C2B5-4008-93CC-D9F909EAF0C6")]
[AssociationId("B1CF18D5-623E-47F8-A518-385425D32144")]
[RoleId("82BE11EF-4994-4F76-997E-4779C72690C8")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal TotalFee { get; set; }
#region Allors
[Id("e1528797-7ff6-41cc-aa0e-b043d7a1f1c4")]
[AssociationId("043f1aae-660e-4dac-b1ff-74c75cbfa357")]
[RoleId("1163b076-01a1-4758-a2f7-c4c4a37a1431")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal TotalExtraCharge { get; set; }
#region Allors
[Id("862aef24-b641-4425-830e-04fd811373d7")]
[AssociationId("eb7065d2-48a9-459b-a6fe-a10048df45c2")]
[RoleId("0b54c320-41e8-4440-b545-9fd9a3393525")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal TotalIrpfInPreferredCurrency { get; set; }
#region Allors
[Id("91dadffb-0ba9-43bb-9ba5-1f5b25b50018")]
[AssociationId("e85ac811-ff89-46cb-8cf2-a2e761df94d8")]
[RoleId("cfbcc1ad-20c2-4052-b064-8306c77ae9e2")]
#endregion
[Workspace]
[Precision(19)]
[Scale(2)]
decimal TotalExVatInPreferredCurrency { get; set; }
#region Allors
[Id("5a1ee643-f4b1-439f-bdde-1c8248605776")]
[AssociationId("46c24f24-f373-4432-8ddf-aa1b4508f4ed")]
[RoleId("d44118a1-9067-4124-9ce1-0f0db4eba92f")]
#endregion
[Workspace]
[Precision(19)]
[Scale(2)]
decimal TotalVatInPreferredCurrency { get; set; }
#region Allors
[Id("23353331-a3d7-47fd-948c-47a8db4e098c")]
[AssociationId("56ffca17-babd-4faa-87cc-c122db1bcfa5")]
[RoleId("403a51b1-c13a-4351-8238-9278bfe6abbd")]
#endregion
[Workspace]
[Precision(19)]
[Scale(2)]
decimal TotalIncVatInPreferredCurrency { get; set; }
#region Allors
[Id("1a88e51f-5d7c-401d-b5c2-ca743cdd5a28")]
[AssociationId("9a7b194e-d2b5-43d8-b389-58d614f04c90")]
[RoleId("e2ba2dd8-cf6e-4222-b812-96fa8ca6bcd3")]
#endregion
[Workspace]
[Precision(19)]
[Scale(2)]
decimal TotalSurchargeInPreferredCurrency { get; set; }
#region Allors
[Id("7edd9403-628e-4f41-bb2f-eb8deef4f852")]
[AssociationId("ebf97891-a8f1-4d41-a71b-6b1243bdee90")]
[RoleId("82761f13-a776-4038-ad6e-8f7b46df27b2")]
#endregion
[Workspace]
[Precision(19)]
[Scale(2)]
decimal TotalDiscountInPreferredCurrency { get; set; }
#region Allors
[Id("c7805ce6-a43c-4066-9f66-c6b3cd7aed18")]
[AssociationId("5b9996e1-fe20-49bb-b37a-44f9947551c5")]
[RoleId("abdbea6c-7fc9-4045-bc88-68b287790433")]
#endregion
[Workspace]
[Precision(19)]
[Scale(2)]
decimal TotalShippingAndHandlingInPreferredCurrency { get; set; }
#region Allors
[Id("1948e9db-05aa-42f0-a6c1-7ac31a7616f5")]
[AssociationId("f8a8edf2-e020-44e1-b008-7e18422373db")]
[RoleId("60297674-8a00-4763-9ece-2a48b85f357b")]
#endregion
[Workspace]
[Precision(19)]
[Scale(2)]
decimal TotalFeeInPreferredCurrency { get; set; }
#region Allors
[Id("642ff657-fffb-45d3-a55e-a57ab14ca5ad")]
[AssociationId("cfaf5838-6169-4d60-af71-b1c91c256fa3")]
[RoleId("b4a110a5-d438-4898-a809-ea39a950f615")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal TotalExtraChargeInPreferredCurrency { get; set; }
#region Allors
[Id("c066b0b9-df6b-423d-91b4-7f070cbce3f9")]
[AssociationId("4521ce7e-f4b9-470f-b823-536ba1e16434")]
[RoleId("624ae960-fd8e-4319-a027-ee468c5d211b")]
#endregion
[Workspace]
[Precision(19)]
[Scale(2)]
decimal TotalBasePriceInPreferredCurrency { get; set; }
#region Allors
[Id("0f23fc4b-a49d-4169-b3a2-c1c43e66c0c0")]
[AssociationId("715a1d32-ca17-4d75-8be7-84860db99921")]
[RoleId("392de37e-82ca-48ea-bc11-3663be30d44a")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal TotalListPriceInPreferredCurrency { get; set; }
#region Allors
[Id("66bbd222-3700-48f9-aa74-3f292d9ca1f0")]
[AssociationId("9bacc03f-5994-4a2a-982f-9f4588348554")]
[RoleId("7f155aa9-09df-4322-8d1e-dd4cf96946d0")]
#endregion
[Precision(19)]
[Scale(2)]
[Workspace]
decimal GrandTotalInPreferredCurrency { get; set; }
}
}
| Allors/allors2 | Base/Repository/Domain/Base/InvoiceVersion.cs | C# | lgpl-3.0 | 14,232 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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 program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.batch.index;
import com.google.common.collect.Iterables;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.batch.index.Cache.Entry;
import static org.assertj.core.api.Assertions.assertThat;
public class CacheTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
Caches caches;
@Before
public void start() {
caches = CachesTest.createCacheOnTemp(temp);
caches.start();
}
@After
public void stop() {
caches.stop();
}
@Test
public void one_part_key() {
Cache<String> cache = caches.createCache("capitals");
assertThat(cache.get("france")).isNull();
cache.put("france", "paris");
cache.put("italy", "rome");
assertThat(cache.get("france")).isEqualTo("paris");
assertThat(cache.keySet()).containsOnly("france", "italy");
assertThat(cache.keySet("france")).isEmpty();
Iterable<String> values = cache.values();
assertThat(values).containsOnly("paris", "rome");
assertThat(values).containsOnly("paris", "rome");
assertThat(cache.containsKey("france")).isTrue();
Iterable<Entry<String>> iterable = cache.entries();
Cache.Entry[] entries = Iterables.toArray(iterable, Cache.Entry.class);
assertThat(entries).hasSize(2);
assertThat(iterable).hasSize(2);
assertThat(entries[0].key()[0]).isEqualTo("france");
assertThat(entries[0].value()).isEqualTo("paris");
assertThat(entries[1].key()[0]).isEqualTo("italy");
assertThat(entries[1].value()).isEqualTo("rome");
cache.remove("france");
assertThat(cache.get("france")).isNull();
assertThat(cache.get("italy")).isEqualTo("rome");
assertThat(cache.keySet()).containsOnly("italy");
assertThat(cache.keySet("france")).isEmpty();
assertThat(cache.containsKey("france")).isFalse();
assertThat(cache.containsKey("italy")).isTrue();
assertThat(values).containsOnly("rome");
cache.clear();
assertThat(values).isEmpty();
}
@Test
public void test_key_being_prefix_of_another_key() throws Exception {
Cache<String> cache = caches.createCache("components");
cache.put("struts-el:org.apache.strutsel.taglib.html.ELButtonTag", "the Tag");
cache.put("struts-el:org.apache.strutsel.taglib.html.ELButtonTagBeanInfo", "the BeanInfo");
assertThat(cache.get("struts-el:org.apache.strutsel.taglib.html.ELButtonTag")).isEqualTo("the Tag");
assertThat(cache.get("struts-el:org.apache.strutsel.taglib.html.ELButtonTagBeanInfo")).isEqualTo("the BeanInfo");
}
@Test
public void two_parts_key() {
Cache<String> cache = caches.createCache("capitals");
assertThat(cache.get("europe", "france")).isNull();
cache.put("europe", "france", "paris");
cache.put("europe", "italy", "rome");
cache.put("asia", "china", "pekin");
assertThat(cache.get("europe")).isNull();
assertThat(cache.get("europe", "france")).isEqualTo("paris");
assertThat(cache.get("europe", "italy")).isEqualTo("rome");
assertThat(cache.get("europe")).isNull();
assertThat(cache.keySet("europe")).containsOnly("france", "italy");
assertThat(cache.keySet()).containsOnly("europe", "asia");
assertThat(cache.containsKey("europe")).isFalse();
assertThat(cache.containsKey("europe", "france")).isTrue();
assertThat(cache.containsKey("europe", "spain")).isFalse();
assertThat(cache.values()).containsOnly("paris", "rome", "pekin");
assertThat(cache.values("america")).isEmpty();
assertThat(cache.values("europe")).containsOnly("paris", "rome");
assertThat(cache.values("oceania")).isEmpty();
Iterable<Entry<String>> iterable = cache.entries();
Cache.Entry[] allEntries = Iterables.toArray(iterable, Cache.Entry.class);
assertThat(allEntries).hasSize(3);
assertThat(iterable).hasSize(3);
assertThat(allEntries[0].key()).isEqualTo(new String[] {"asia", "china"});
assertThat(allEntries[0].value()).isEqualTo("pekin");
assertThat(allEntries[1].key()).isEqualTo(new String[] {"europe", "france"});
assertThat(allEntries[1].value()).isEqualTo("paris");
assertThat(allEntries[2].key()).isEqualTo(new String[] {"europe", "italy"});
assertThat(allEntries[2].value()).isEqualTo("rome");
Iterable<Entry<String>> iterable2 = cache.entries("europe");
Cache.Entry[] subEntries = Iterables.toArray(iterable2, Cache.Entry.class);
assertThat(subEntries).hasSize(2);
assertThat(iterable2).hasSize(2);
assertThat(subEntries[0].key()).isEqualTo(new String[] {"europe", "france"});
assertThat(subEntries[0].value()).isEqualTo("paris");
assertThat(subEntries[1].key()).isEqualTo(new String[] {"europe", "italy"});
assertThat(subEntries[1].value()).isEqualTo("rome");
cache.remove("europe", "france");
assertThat(cache.values()).containsOnly("rome", "pekin");
assertThat(cache.get("europe", "france")).isNull();
assertThat(cache.get("europe", "italy")).isEqualTo("rome");
assertThat(cache.containsKey("europe", "france")).isFalse();
assertThat(cache.keySet("europe")).containsOnly("italy");
cache.clear("america");
assertThat(cache.keySet()).containsOnly("europe", "asia");
cache.clear();
assertThat(cache.keySet()).isEmpty();
}
@Test
public void three_parts_key() {
Cache<String> cache = caches.createCache("places");
assertThat(cache.get("europe", "france", "paris")).isNull();
cache.put("europe", "france", "paris", "eiffel tower");
cache.put("europe", "france", "annecy", "lake");
cache.put("europe", "france", "poitiers", "notre dame");
cache.put("europe", "italy", "rome", "colosseum");
cache.put("europe2", "ukrania", "kiev", "dunno");
cache.put("asia", "china", "pekin", "great wall");
cache.put("america", "us", "new york", "empire state building");
assertThat(cache.get("europe")).isNull();
assertThat(cache.get("europe", "france")).isNull();
assertThat(cache.get("europe", "france", "paris")).isEqualTo("eiffel tower");
assertThat(cache.get("europe", "france", "annecy")).isEqualTo("lake");
assertThat(cache.get("europe", "italy", "rome")).isEqualTo("colosseum");
assertThat(cache.keySet()).containsOnly("europe", "asia", "america", "europe2");
assertThat(cache.keySet("europe")).containsOnly("france", "italy");
assertThat(cache.keySet("europe", "france")).containsOnly("annecy", "paris", "poitiers");
assertThat(cache.containsKey("europe")).isFalse();
assertThat(cache.containsKey("europe", "france")).isFalse();
assertThat(cache.containsKey("europe", "france", "annecy")).isTrue();
assertThat(cache.containsKey("europe", "france", "biarritz")).isFalse();
assertThat(cache.values()).containsOnly("eiffel tower", "lake", "colosseum", "notre dame", "great wall", "empire state building", "dunno");
assertThat(cache.values("europe")).containsOnly("eiffel tower", "lake", "colosseum", "notre dame");
assertThat(cache.values("europe", "france")).containsOnly("eiffel tower", "lake", "notre dame");
Iterable<Entry<String>> iterable = cache.entries();
Cache.Entry[] allEntries = Iterables.toArray(iterable, Cache.Entry.class);
assertThat(allEntries).hasSize(7);
assertThat(iterable).hasSize(7);
assertThat(allEntries[0].key()).isEqualTo(new String[] {"america", "us", "new york"});
assertThat(allEntries[0].value()).isEqualTo("empire state building");
assertThat(allEntries[1].key()).isEqualTo(new String[] {"asia", "china", "pekin"});
assertThat(allEntries[1].value()).isEqualTo("great wall");
assertThat(allEntries[2].key()).isEqualTo(new String[] {"europe", "france", "annecy"});
assertThat(allEntries[2].value()).isEqualTo("lake");
assertThat(allEntries[3].key()).isEqualTo(new String[] {"europe", "france", "paris"});
assertThat(allEntries[3].value()).isEqualTo("eiffel tower");
assertThat(allEntries[4].key()).isEqualTo(new String[] {"europe", "france", "poitiers"});
assertThat(allEntries[4].value()).isEqualTo("notre dame");
assertThat(allEntries[5].key()).isEqualTo(new String[] {"europe", "italy", "rome"});
assertThat(allEntries[5].value()).isEqualTo("colosseum");
Iterable<Entry<String>> iterable2 = cache.entries("europe");
Cache.Entry[] subEntries = Iterables.toArray(iterable2, Cache.Entry.class);
assertThat(subEntries).hasSize(4);
assertThat(iterable2).hasSize(4);
assertThat(subEntries[0].key()).isEqualTo(new String[] {"europe", "france", "annecy"});
assertThat(subEntries[0].value()).isEqualTo("lake");
assertThat(subEntries[1].key()).isEqualTo(new String[] {"europe", "france", "paris"});
assertThat(subEntries[1].value()).isEqualTo("eiffel tower");
assertThat(subEntries[2].key()).isEqualTo(new String[] {"europe", "france", "poitiers"});
assertThat(subEntries[2].value()).isEqualTo("notre dame");
assertThat(subEntries[3].key()).isEqualTo(new String[] {"europe", "italy", "rome"});
assertThat(subEntries[3].value()).isEqualTo("colosseum");
cache.remove("europe", "france", "annecy");
assertThat(cache.values()).containsOnly("eiffel tower", "colosseum", "notre dame", "great wall", "empire state building", "dunno");
assertThat(cache.values("europe")).containsOnly("eiffel tower", "colosseum", "notre dame");
assertThat(cache.values("europe", "france")).containsOnly("eiffel tower", "notre dame");
assertThat(cache.get("europe", "france", "annecy")).isNull();
assertThat(cache.get("europe", "italy", "rome")).isEqualTo("colosseum");
assertThat(cache.containsKey("europe", "france")).isFalse();
cache.clear("europe", "italy");
assertThat(cache.values()).containsOnly("eiffel tower", "notre dame", "great wall", "empire state building", "dunno");
cache.clear("europe");
assertThat(cache.values()).containsOnly("great wall", "empire state building", "dunno");
cache.clear();
assertThat(cache.values()).isEmpty();
}
@Test
public void remove_versus_clear() {
Cache<String> cache = caches.createCache("capitals");
cache.put("europe", "france", "paris");
cache.put("europe", "italy", "rome");
// remove("europe") does not remove sub-keys
cache.remove("europe");
assertThat(cache.values()).containsOnly("paris", "rome");
// clear("europe") removes sub-keys
cache.clear("europe");
assertThat(cache.values()).isEmpty();
}
@Test
public void empty_cache() {
Cache<String> cache = caches.createCache("empty");
assertThat(cache.get("foo")).isNull();
assertThat(cache.get("foo", "bar")).isNull();
assertThat(cache.get("foo", "bar", "baz")).isNull();
assertThat(cache.keySet()).isEmpty();
assertThat(cache.keySet("foo")).isEmpty();
assertThat(cache.containsKey("foo")).isFalse();
assertThat(cache.containsKey("foo", "bar")).isFalse();
assertThat(cache.containsKey("foo", "bar", "baz")).isFalse();
assertThat(cache.values()).isEmpty();
assertThat(cache.values("foo")).isEmpty();
// do not fail
cache.remove("foo");
cache.remove("foo", "bar");
cache.remove("foo", "bar", "baz");
cache.clear("foo");
cache.clear("foo", "bar");
cache.clear("foo", "bar", "baz");
cache.clear();
}
}
| jblievremont/sonarqube | sonar-batch/src/test/java/org/sonar/batch/index/CacheTest.java | Java | lgpl-3.0 | 12,143 |
// Copyright (C) 2009 by Thomas Moulard, AIST, CNRS, INRIA.
//
// This file is part of the roboptim.
//
// roboptim is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// roboptim 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 roboptim. If not, see <http://www.gnu.org/licenses/>.
#ifndef ROBOPTIM_CORE_PORTABILITY_HH
# define ROBOPTIM_CORE_PORTABILITY_HH
// Note: DLL macros are defined in config.hh as ROBOPTIM_CORE_DLL*, and were
// defined here as ROBOPTIM_DLL*. We renamed them in roboptim-core, and include
// config.hh for backwards compatibility.
# include <roboptim/core/config.hh>
// Extra useful attributes
#if defined _WIN32 || defined __CYGWIN__
#define ROBOPTIM_UNUSED
#else
// On Linux, for GCC >= 4
#if __GNUC__ >= 4
#define ROBOPTIM_UNUSED __attribute__((unused))
#else
// Otherwise (GCC < 4 or another compiler is used)
#define ROBOPTIM_UNUSED
#endif // __GNUC__ >= 4
#endif // defined _WIN32 || defined __CYGWIN__
// On Microsoft Windows
#if defined _WIN32 || defined __CYGWIN__
#define ROBOPTIM_ALLOW_DEPRECATED_ON \
/* Disable deprecated warning */ \
__pragma(warning(push)) \
__pragma(warning(disable : 4996))
#define ROBOPTIM_ALLOW_DEPRECATED_OFF \
/* Re-enable deprecated warning */ \
__pragma(warning(pop))
// TODO: update for Windows if relevant
#define ROBOPTIM_ALLOW_ATTRIBUTES_ON
#define ROBOPTIM_ALLOW_ATTRIBUTES_OFF
#elif !defined (__CUDACC__)
// Otherwise (on Linux/OSX with GCC/Clang)
#define ROBOPTIM_ALLOW_DEPRECATED_ON \
/* Disable deprecated warning */ \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
#define ROBOPTIM_ALLOW_DEPRECATED_OFF \
/* Re-enable deprecated warning */ \
_Pragma ("GCC diagnostic pop")
#ifdef __GNUC__
#define ROBOPTIM_ALLOW_ATTRIBUTES_ON \
/* Disable attributes warning */ \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wattributes\"")
#define ROBOPTIM_ALLOW_ATTRIBUTES_OFF \
/* Re-enable attributes warning */ \
_Pragma ("GCC diagnostic pop")
#else
#define ROBOPTIM_ALLOW_ATTRIBUTES_ON
#define ROBOPTIM_ALLOW_ATTRIBUTES_OFF
#endif
#else
#define ROBOPTIM_ALLOW_DEPRECATED_ON
#define ROBOPTIM_ALLOW_DEPRECATED_OFF
#define ROBOPTIM_ALLOW_ATTRIBUTES_ON
#define ROBOPTIM_ALLOW_ATTRIBUTES_OFF
#endif
// Work around for explicit template instantation in GCC, see #111 for
// more details
# if defined(ROBOPTIM_PRECOMPILED_DENSE_SPARSE) && \
__GNUC__ >= 4 && !defined(__clang__)
# define ROBOPTIM_GCC_ETI_WORKAROUND ROBOPTIM_CORE_DLLAPI
# else
# define ROBOPTIM_GCC_ETI_WORKAROUND
# endif
#endif //! ROBOPTIM_CORE_PORTABILITY_HH
| roboptim/roboptim-core | include/roboptim/core/portability.hh | C++ | lgpl-3.0 | 3,213 |
#pragma once
#include <deal.II/fe/fe_system.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/numerics/data_out.h>
#include <Spacy/zeroVectorCreator.hh>
#include "init.hh"
#include "util.hh"
#include "vector.hh"
#include "vectorSpace.hh"
#include <ostream>
#include <fstream>
#include <string>
namespace Spacy
{
namespace dealII
{
template <int dim, class VariableDims = VariableDim<1> >
void writeVTK(const Vector& x, const std::string& fileName)
{
auto fe_system = get_finite_element_system<dim,VariableDims>(x.space());
dealii::DoFHandler<dim> dof_handler(creator< VectorCreator<dim,GetDim<0,VariableDims>::value> >(extractSubSpace(x.space(),0)).triangulation());
dof_handler.distribute_dofs(fe_system);
dealii::DataOut<dim> data_out;
data_out.attach_dof_handler(dof_handler);
data_out.add_data_vector(get(x), fileName);
data_out.build_patches();
std::ofstream stream(fileName + ".vtk");
data_out.write_vtk(stream);
}
}
}
| lubkoll/FSA | Spacy/Adapter/dealII/writeVTK.hh | C++ | lgpl-3.0 | 1,093 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Nullable;
import org.junit.Test;
import static com.google.common.collect.ImmutableList.of;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
public class ViewsVisitorsCrawlerWithPathAwareVisitorTest {
private static final int ROOT_REF = 1;
private static final ViewsComponent SOME_TREE_ROOT = ViewsComponent.builder(VIEW, ROOT_REF)
.addChildren(
ViewsComponent.builder(SUBVIEW, 11)
.addChildren(
ViewsComponent.builder(SUBVIEW, 111)
.addChildren(
ViewsComponent.builder(PROJECT_VIEW, 1111).build(),
ViewsComponent.builder(PROJECT_VIEW, 1112).build())
.build(),
ViewsComponent.builder(SUBVIEW, 112)
.addChildren(
ViewsComponent.builder(PROJECT_VIEW, 1121).build())
.build())
.build(),
ViewsComponent.builder(SUBVIEW, 12)
.addChildren(
ViewsComponent.builder(SUBVIEW, 121)
.addChildren(
ViewsComponent.builder(SUBVIEW, 1211)
.addChildren(
ViewsComponent.builder(PROJECT_VIEW, 12111).build())
.build())
.build())
.build())
.build();
@Test
public void verify_preOrder_visit_call_when_visit_tree_with_depth_PROJECT_VIEW() {
CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.PROJECT_VIEW, PRE_ORDER);
VisitorsCrawler underTest = newVisitorsCrawler(visitor);
underTest.visit(SOME_TREE_ROOT);
Iterator<PathAwareCallRecord> expected = of(
viewsCallRecord("visitAny", 1, null, of(1)),
viewsCallRecord("visitView", 1, null, of(1)),
viewsCallRecord("visitAny", 11, 1, of(11, 1)),
viewsCallRecord("visitSubView", 11, 1, of(11, 1)),
viewsCallRecord("visitAny", 111, 11, of(111, 11, 1)),
viewsCallRecord("visitSubView", 111, 11, of(111, 11, 1)),
viewsCallRecord("visitAny", 1111, 111, of(1111, 111, 11, 1)),
viewsCallRecord("visitProjectView", 1111, 111, of(1111, 111, 11, 1)),
viewsCallRecord("visitAny", 1112, 111, of(1112, 111, 11, 1)),
viewsCallRecord("visitProjectView", 1112, 111, of(1112, 111, 11, 1)),
viewsCallRecord("visitAny", 112, 11, of(112, 11, 1)),
viewsCallRecord("visitSubView", 112, 11, of(112, 11, 1)),
viewsCallRecord("visitAny", 1121, 112, of(1121, 112, 11, 1)),
viewsCallRecord("visitProjectView", 1121, 112, of(1121, 112, 11, 1)),
viewsCallRecord("visitAny", 12, 1, of(12, 1)),
viewsCallRecord("visitSubView", 12, 1, of(12, 1)),
viewsCallRecord("visitAny", 121, 12, of(121, 12, 1)),
viewsCallRecord("visitSubView", 121, 12, of(121, 12, 1)),
viewsCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)),
viewsCallRecord("visitSubView", 1211, 121, of(1211, 121, 12, 1)),
viewsCallRecord("visitAny", 12111, 1211, of(12111, 1211, 121, 12, 1)),
viewsCallRecord("visitProjectView", 12111, 1211, of(12111, 1211, 121, 12, 1))).iterator();
verifyCallRecords(expected, visitor.callsRecords.iterator());
}
@Test
public void verify_preOrder_visit_call_when_visit_tree_with_depth_SUBVIEW() {
CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.SUBVIEW, PRE_ORDER);
VisitorsCrawler underTest = newVisitorsCrawler(visitor);
underTest.visit(SOME_TREE_ROOT);
Iterator<PathAwareCallRecord> expected = of(
viewsCallRecord("visitAny", 1, null, of(1)),
viewsCallRecord("visitView", 1, null, of(1)),
viewsCallRecord("visitAny", 11, 1, of(11, 1)),
viewsCallRecord("visitSubView", 11, 1, of(11, 1)),
viewsCallRecord("visitAny", 111, 11, of(111, 11, 1)),
viewsCallRecord("visitSubView", 111, 11, of(111, 11, 1)),
viewsCallRecord("visitAny", 112, 11, of(112, 11, 1)),
viewsCallRecord("visitSubView", 112, 11, of(112, 11, 1)),
viewsCallRecord("visitAny", 12, 1, of(12, 1)),
viewsCallRecord("visitSubView", 12, 1, of(12, 1)),
viewsCallRecord("visitAny", 121, 12, of(121, 12, 1)),
viewsCallRecord("visitSubView", 121, 12, of(121, 12, 1)),
viewsCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)),
viewsCallRecord("visitSubView", 1211, 121, of(1211, 121, 12, 1))).iterator();
verifyCallRecords(expected, visitor.callsRecords.iterator());
}
@Test
public void verify_preOrder_visit_call_when_visit_tree_with_depth_VIEW() {
CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.VIEW, PRE_ORDER);
VisitorsCrawler underTest = newVisitorsCrawler(visitor);
underTest.visit(SOME_TREE_ROOT);
Iterator<PathAwareCallRecord> expected = of(
viewsCallRecord("visitAny", 1, null, of(1)),
viewsCallRecord("visitView", 1, null, of(1))).iterator();
verifyCallRecords(expected, visitor.callsRecords.iterator());
}
@Test
public void verify_postOrder_visit_call_when_visit_tree_with_depth_PROJECT_VIEW() {
CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.PROJECT_VIEW, POST_ORDER);
VisitorsCrawler underTest = newVisitorsCrawler(visitor);
underTest.visit(SOME_TREE_ROOT);
Iterator<PathAwareCallRecord> expected = of(
viewsCallRecord("visitAny", 1111, 111, of(1111, 111, 11, 1)),
viewsCallRecord("visitProjectView", 1111, 111, of(1111, 111, 11, 1)),
viewsCallRecord("visitAny", 1112, 111, of(1112, 111, 11, 1)),
viewsCallRecord("visitProjectView", 1112, 111, of(1112, 111, 11, 1)),
viewsCallRecord("visitAny", 111, 11, of(111, 11, 1)),
viewsCallRecord("visitSubView", 111, 11, of(111, 11, 1)),
viewsCallRecord("visitAny", 1121, 112, of(1121, 112, 11, 1)),
viewsCallRecord("visitProjectView", 1121, 112, of(1121, 112, 11, 1)),
viewsCallRecord("visitAny", 112, 11, of(112, 11, 1)),
viewsCallRecord("visitSubView", 112, 11, of(112, 11, 1)),
viewsCallRecord("visitAny", 11, 1, of(11, 1)),
viewsCallRecord("visitSubView", 11, 1, of(11, 1)),
viewsCallRecord("visitAny", 12111, 1211, of(12111, 1211, 121, 12, 1)),
viewsCallRecord("visitProjectView", 12111, 1211, of(12111, 1211, 121, 12, 1)),
viewsCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)),
viewsCallRecord("visitSubView", 1211, 121, of(1211, 121, 12, 1)),
viewsCallRecord("visitAny", 121, 12, of(121, 12, 1)),
viewsCallRecord("visitSubView", 121, 12, of(121, 12, 1)),
viewsCallRecord("visitAny", 12, 1, of(12, 1)),
viewsCallRecord("visitSubView", 12, 1, of(12, 1)),
viewsCallRecord("visitAny", 1, null, of(1)),
viewsCallRecord("visitView", 1, null, of(1))).iterator();
verifyCallRecords(expected, visitor.callsRecords.iterator());
}
@Test
public void verify_postOrder_visit_call_when_visit_tree_with_depth_SUBVIEW() {
CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.SUBVIEW, POST_ORDER);
VisitorsCrawler underTest = newVisitorsCrawler(visitor);
underTest.visit(SOME_TREE_ROOT);
Iterator<PathAwareCallRecord> expected = of(
viewsCallRecord("visitAny", 111, 11, of(111, 11, 1)),
viewsCallRecord("visitSubView", 111, 11, of(111, 11, 1)),
viewsCallRecord("visitAny", 112, 11, of(112, 11, 1)),
viewsCallRecord("visitSubView", 112, 11, of(112, 11, 1)),
viewsCallRecord("visitAny", 11, 1, of(11, 1)),
viewsCallRecord("visitSubView", 11, 1, of(11, 1)),
viewsCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)),
viewsCallRecord("visitSubView", 1211, 121, of(1211, 121, 12, 1)),
viewsCallRecord("visitAny", 121, 12, of(121, 12, 1)),
viewsCallRecord("visitSubView", 121, 12, of(121, 12, 1)),
viewsCallRecord("visitAny", 12, 1, of(12, 1)),
viewsCallRecord("visitSubView", 12, 1, of(12, 1)),
viewsCallRecord("visitAny", 1, null, of(1)),
viewsCallRecord("visitView", 1, null, of(1))).iterator();
verifyCallRecords(expected, visitor.callsRecords.iterator());
}
@Test
public void verify_postOrder_visit_call_when_visit_tree_with_depth_VIEW() {
CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.VIEW, POST_ORDER);
VisitorsCrawler underTest = newVisitorsCrawler(visitor);
underTest.visit(SOME_TREE_ROOT);
Iterator<PathAwareCallRecord> expected = of(
viewsCallRecord("visitAny", 1, null, of(1)),
viewsCallRecord("visitView", 1, null, of(1))).iterator();
verifyCallRecords(expected, visitor.callsRecords.iterator());
}
private static void verifyCallRecords(Iterator<PathAwareCallRecord> expected, Iterator<PathAwareCallRecord> actual) {
while (expected.hasNext()) {
assertThat(actual.next()).isEqualTo(expected.next());
}
}
private static PathAwareCallRecord viewsCallRecord(String method, int currentRef, @Nullable Integer parentRef, List<Integer> path) {
return PathAwareCallRecord.viewsCallRecord(method, String.valueOf(currentRef), currentRef, parentRef, ROOT_REF, path);
}
private static VisitorsCrawler newVisitorsCrawler(ComponentVisitor componentVisitor) {
return new VisitorsCrawler(Arrays.asList(componentVisitor));
}
}
| SonarSource/sonarqube | server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerWithPathAwareVisitorTest.java | Java | lgpl-3.0 | 10,635 |
namespace JocysCom.Password.Generator.Controls
{
partial class OptionsControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.LocalUserFolderTextBox = new System.Windows.Forms.TextBox();
this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
this.AutoOptionsGroupBox = new System.Windows.Forms.GroupBox();
this.label1 = new System.Windows.Forms.Label();
this.ResetButton = new System.Windows.Forms.Button();
this.nudAutoGenerateTimerSeconds = new System.Windows.Forms.NumericUpDown();
this.GenerateOnCopyCheckBox = new System.Windows.Forms.CheckBox();
this.CopyOnGenerateCheckBox = new System.Windows.Forms.CheckBox();
this.CopyPasswordWhenStartCheckBox = new System.Windows.Forms.CheckBox();
this.GeneratePasswordOnStartCheckBox = new System.Windows.Forms.CheckBox();
this.OpenPasswordListFileAfterSaveCheckBox = new System.Windows.Forms.CheckBox();
this.GenerateTimerCheckBox = new System.Windows.Forms.CheckBox();
this.SaveProgramSettingsCheckBox = new System.Windows.Forms.CheckBox();
this.ProgramStartGroupBox = new System.Windows.Forms.GroupBox();
this.StartWithWindowsStateComboBox = new System.Windows.Forms.ComboBox();
this.MinimizeOnCloseCheckBox = new System.Windows.Forms.CheckBox();
this.AllowOnlyOneCopyCheckBox = new System.Windows.Forms.CheckBox();
this.MinimizeToTrayCheckBox = new System.Windows.Forms.CheckBox();
this.StartWithWindowsCheckBox = new System.Windows.Forms.CheckBox();
this.AlwaysOnTopCheckBox = new System.Windows.Forms.CheckBox();
this.DataAndConfigurationGroupBox = new System.Windows.Forms.GroupBox();
this.LocalUserFolderOpenButton = new System.Windows.Forms.Button();
this.LocalUserFolderLabel = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.FavPreset3ComboBox = new System.Windows.Forms.ComboBox();
this.FavPreset2ComboBox = new System.Windows.Forms.ComboBox();
this.FavPreset1ComboBox = new System.Windows.Forms.ComboBox();
this.FavPreset3TextBox = new System.Windows.Forms.TextBox();
this.FavPreset2TextBox = new System.Windows.Forms.TextBox();
this.FavPreset1TextBox = new System.Windows.Forms.TextBox();
this.AutoOptionsGroupBox.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudAutoGenerateTimerSeconds)).BeginInit();
this.ProgramStartGroupBox.SuspendLayout();
this.DataAndConfigurationGroupBox.SuspendLayout();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// LocalUserFolderTextBox
//
this.LocalUserFolderTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.LocalUserFolderTextBox.Location = new System.Drawing.Point(6, 32);
this.LocalUserFolderTextBox.Name = "LocalUserFolderTextBox";
this.LocalUserFolderTextBox.ReadOnly = true;
this.LocalUserFolderTextBox.Size = new System.Drawing.Size(424, 20);
this.LocalUserFolderTextBox.TabIndex = 0;
//
// AutoOptionsGroupBox
//
this.AutoOptionsGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.AutoOptionsGroupBox.Controls.Add(this.label1);
this.AutoOptionsGroupBox.Controls.Add(this.ResetButton);
this.AutoOptionsGroupBox.Controls.Add(this.nudAutoGenerateTimerSeconds);
this.AutoOptionsGroupBox.Controls.Add(this.GenerateOnCopyCheckBox);
this.AutoOptionsGroupBox.Controls.Add(this.CopyOnGenerateCheckBox);
this.AutoOptionsGroupBox.Controls.Add(this.CopyPasswordWhenStartCheckBox);
this.AutoOptionsGroupBox.Controls.Add(this.GeneratePasswordOnStartCheckBox);
this.AutoOptionsGroupBox.Controls.Add(this.OpenPasswordListFileAfterSaveCheckBox);
this.AutoOptionsGroupBox.Controls.Add(this.GenerateTimerCheckBox);
this.AutoOptionsGroupBox.Controls.Add(this.SaveProgramSettingsCheckBox);
this.AutoOptionsGroupBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.AutoOptionsGroupBox.Location = new System.Drawing.Point(146, 176);
this.AutoOptionsGroupBox.Name = "AutoOptionsGroupBox";
this.AutoOptionsGroupBox.Size = new System.Drawing.Size(374, 242);
this.AutoOptionsGroupBox.TabIndex = 107;
this.AutoOptionsGroupBox.TabStop = false;
this.AutoOptionsGroupBox.Text = "Auto Options:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(87, 168);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(175, 13);
this.label1.TabIndex = 70;
this.label1.Text = "- reset all presets to default settings:";
//
// ResetButton
//
this.ResetButton.Location = new System.Drawing.Point(6, 163);
this.ResetButton.Name = "ResetButton";
this.ResetButton.Size = new System.Drawing.Size(75, 23);
this.ResetButton.TabIndex = 69;
this.ResetButton.Text = "Reset";
this.ResetButton.UseVisualStyleBackColor = true;
this.ResetButton.Click += new System.EventHandler(this.ResetButton_Click);
//
// nudAutoGenerateTimerSeconds
//
this.nudAutoGenerateTimerSeconds.Enabled = false;
this.nudAutoGenerateTimerSeconds.Location = new System.Drawing.Point(147, 192);
this.nudAutoGenerateTimerSeconds.Maximum = new decimal(new int[] {
1000000,
0,
0,
0});
this.nudAutoGenerateTimerSeconds.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.nudAutoGenerateTimerSeconds.Name = "nudAutoGenerateTimerSeconds";
this.nudAutoGenerateTimerSeconds.Size = new System.Drawing.Size(48, 20);
this.nudAutoGenerateTimerSeconds.TabIndex = 49;
this.nudAutoGenerateTimerSeconds.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.nudAutoGenerateTimerSeconds.Value = new decimal(new int[] {
2,
0,
0,
0});
this.nudAutoGenerateTimerSeconds.Visible = false;
//
// GenerateOnCopyCheckBox
//
this.GenerateOnCopyCheckBox.AutoSize = true;
this.GenerateOnCopyCheckBox.Checked = global::JocysCom.Password.Generator.Properties.Settings.Default.GenerateOnCopy;
this.GenerateOnCopyCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.GenerateOnCopyCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::JocysCom.Password.Generator.Properties.Settings.Default, "GenerateOnCopy", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.GenerateOnCopyCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.GenerateOnCopyCheckBox.Location = new System.Drawing.Point(6, 67);
this.GenerateOnCopyCheckBox.Name = "GenerateOnCopyCheckBox";
this.GenerateOnCopyCheckBox.Size = new System.Drawing.Size(194, 18);
this.GenerateOnCopyCheckBox.TabIndex = 68;
this.GenerateOnCopyCheckBox.Text = "Generate after [Copy] button press";
//
// CopyOnGenerateCheckBox
//
this.CopyOnGenerateCheckBox.AutoSize = true;
this.CopyOnGenerateCheckBox.Checked = global::JocysCom.Password.Generator.Properties.Settings.Default.CopyOnGenerate;
this.CopyOnGenerateCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.CopyOnGenerateCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::JocysCom.Password.Generator.Properties.Settings.Default, "CopyOnGenerate", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.CopyOnGenerateCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.CopyOnGenerateCheckBox.Location = new System.Drawing.Point(6, 19);
this.CopyOnGenerateCheckBox.Name = "CopyOnGenerateCheckBox";
this.CopyOnGenerateCheckBox.Size = new System.Drawing.Size(183, 18);
this.CopyOnGenerateCheckBox.TabIndex = 67;
this.CopyOnGenerateCheckBox.Text = "Copy to clipboard after generate";
//
// CopyPasswordWhenStartCheckBox
//
this.CopyPasswordWhenStartCheckBox.AutoSize = true;
this.CopyPasswordWhenStartCheckBox.Checked = global::JocysCom.Password.Generator.Properties.Settings.Default.CopyPasswordWhenStart;
this.CopyPasswordWhenStartCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::JocysCom.Password.Generator.Properties.Settings.Default, "CopyPasswordWhenStart", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.CopyPasswordWhenStartCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.CopyPasswordWhenStartCheckBox.Location = new System.Drawing.Point(6, 139);
this.CopyPasswordWhenStartCheckBox.Name = "CopyPasswordWhenStartCheckBox";
this.CopyPasswordWhenStartCheckBox.Size = new System.Drawing.Size(156, 18);
this.CopyPasswordWhenStartCheckBox.TabIndex = 67;
this.CopyPasswordWhenStartCheckBox.Text = "Copy password when start";
//
// GeneratePasswordOnStartCheckBox
//
this.GeneratePasswordOnStartCheckBox.AutoSize = true;
this.GeneratePasswordOnStartCheckBox.Checked = global::JocysCom.Password.Generator.Properties.Settings.Default.GeneratePasswordOnStart;
this.GeneratePasswordOnStartCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.GeneratePasswordOnStartCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::JocysCom.Password.Generator.Properties.Settings.Default, "GeneratePasswordOnStart", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.GeneratePasswordOnStartCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.GeneratePasswordOnStartCheckBox.Location = new System.Drawing.Point(6, 115);
this.GeneratePasswordOnStartCheckBox.Name = "GeneratePasswordOnStartCheckBox";
this.GeneratePasswordOnStartCheckBox.Size = new System.Drawing.Size(176, 18);
this.GeneratePasswordOnStartCheckBox.TabIndex = 67;
this.GeneratePasswordOnStartCheckBox.Text = "Generate password when start";
//
// OpenPasswordListFileAfterSaveCheckBox
//
this.OpenPasswordListFileAfterSaveCheckBox.AutoSize = true;
this.OpenPasswordListFileAfterSaveCheckBox.Checked = global::JocysCom.Password.Generator.Properties.Settings.Default.OpenPasswordListFileAfterSave;
this.OpenPasswordListFileAfterSaveCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.OpenPasswordListFileAfterSaveCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::JocysCom.Password.Generator.Properties.Settings.Default, "OpenPasswordListFileAfterSave", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.OpenPasswordListFileAfterSaveCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.OpenPasswordListFileAfterSaveCheckBox.Location = new System.Drawing.Point(6, 43);
this.OpenPasswordListFileAfterSaveCheckBox.Name = "OpenPasswordListFileAfterSaveCheckBox";
this.OpenPasswordListFileAfterSaveCheckBox.Size = new System.Drawing.Size(187, 18);
this.OpenPasswordListFileAfterSaveCheckBox.TabIndex = 67;
this.OpenPasswordListFileAfterSaveCheckBox.Text = "Open password list file after save";
//
// GenerateTimerCheckBox
//
this.GenerateTimerCheckBox.AutoSize = true;
this.GenerateTimerCheckBox.Checked = global::JocysCom.Password.Generator.Properties.Settings.Default.GenerateTimer;
this.GenerateTimerCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::JocysCom.Password.Generator.Properties.Settings.Default, "GenerateTimer", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.GenerateTimerCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.GenerateTimerCheckBox.Location = new System.Drawing.Point(6, 192);
this.GenerateTimerCheckBox.Name = "GenerateTimerCheckBox";
this.GenerateTimerCheckBox.Size = new System.Drawing.Size(250, 18);
this.GenerateTimerCheckBox.TabIndex = 67;
this.GenerateTimerCheckBox.Text = "Generate password every seconds";
this.GenerateTimerCheckBox.Visible = false;
//
// SaveProgramSettingsCheckBox
//
this.SaveProgramSettingsCheckBox.AutoSize = true;
this.SaveProgramSettingsCheckBox.Checked = global::JocysCom.Password.Generator.Properties.Settings.Default.SaveProgramSettings;
this.SaveProgramSettingsCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.SaveProgramSettingsCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::JocysCom.Password.Generator.Properties.Settings.Default, "SaveProgramSettings", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.SaveProgramSettingsCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.SaveProgramSettingsCheckBox.Location = new System.Drawing.Point(6, 91);
this.SaveProgramSettingsCheckBox.Name = "SaveProgramSettingsCheckBox";
this.SaveProgramSettingsCheckBox.Size = new System.Drawing.Size(171, 18);
this.SaveProgramSettingsCheckBox.TabIndex = 67;
this.SaveProgramSettingsCheckBox.Text = "Save program settings on exit";
this.SaveProgramSettingsCheckBox.CheckedChanged += new System.EventHandler(this.SaveProgramSettingsCheckBox_CheckedChanged);
//
// ProgramStartGroupBox
//
this.ProgramStartGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.ProgramStartGroupBox.Controls.Add(this.StartWithWindowsStateComboBox);
this.ProgramStartGroupBox.Controls.Add(this.MinimizeOnCloseCheckBox);
this.ProgramStartGroupBox.Controls.Add(this.AllowOnlyOneCopyCheckBox);
this.ProgramStartGroupBox.Controls.Add(this.MinimizeToTrayCheckBox);
this.ProgramStartGroupBox.Controls.Add(this.StartWithWindowsCheckBox);
this.ProgramStartGroupBox.Controls.Add(this.AlwaysOnTopCheckBox);
this.ProgramStartGroupBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.ProgramStartGroupBox.Location = new System.Drawing.Point(3, 176);
this.ProgramStartGroupBox.Name = "ProgramStartGroupBox";
this.ProgramStartGroupBox.Size = new System.Drawing.Size(137, 242);
this.ProgramStartGroupBox.TabIndex = 104;
this.ProgramStartGroupBox.TabStop = false;
this.ProgramStartGroupBox.Text = "Program Start:";
//
// StartWithWindowsStateComboBox
//
this.StartWithWindowsStateComboBox.DataBindings.Add(new System.Windows.Forms.Binding("Text", global::JocysCom.Password.Generator.Properties.Settings.Default, "StartWithWindowsState", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.StartWithWindowsStateComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.StartWithWindowsStateComboBox.FormattingEnabled = true;
this.StartWithWindowsStateComboBox.Items.AddRange(new object[] {
"Maximized",
"Normal",
"Minimized"});
this.StartWithWindowsStateComboBox.Location = new System.Drawing.Point(18, 43);
this.StartWithWindowsStateComboBox.Name = "StartWithWindowsStateComboBox";
this.StartWithWindowsStateComboBox.Size = new System.Drawing.Size(90, 21);
this.StartWithWindowsStateComboBox.TabIndex = 93;
this.StartWithWindowsStateComboBox.SelectedIndexChanged += new System.EventHandler(this.StartWithWindowsStateComboBox_SelectedIndexChanged);
//
// MinimizeOnCloseCheckBox
//
this.MinimizeOnCloseCheckBox.AutoSize = true;
this.MinimizeOnCloseCheckBox.Checked = global::JocysCom.Password.Generator.Properties.Settings.Default.MinimizeOnClose;
this.MinimizeOnCloseCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::JocysCom.Password.Generator.Properties.Settings.Default, "MinimizeOnClose", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.MinimizeOnCloseCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.MinimizeOnCloseCheckBox.Location = new System.Drawing.Point(6, 142);
this.MinimizeOnCloseCheckBox.Name = "MinimizeOnCloseCheckBox";
this.MinimizeOnCloseCheckBox.Size = new System.Drawing.Size(116, 18);
this.MinimizeOnCloseCheckBox.TabIndex = 92;
this.MinimizeOnCloseCheckBox.Text = "Minimize on Close";
this.MinimizeOnCloseCheckBox.Visible = false;
//
// AllowOnlyOneCopyCheckBox
//
this.AllowOnlyOneCopyCheckBox.AutoSize = true;
this.AllowOnlyOneCopyCheckBox.Checked = global::JocysCom.Password.Generator.Properties.Settings.Default.AllowOnlyOneCopy;
this.AllowOnlyOneCopyCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.AllowOnlyOneCopyCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::JocysCom.Password.Generator.Properties.Settings.Default, "AllowOnlyOneCopy", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.AllowOnlyOneCopyCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.AllowOnlyOneCopyCheckBox.Location = new System.Drawing.Point(6, 118);
this.AllowOnlyOneCopyCheckBox.Name = "AllowOnlyOneCopyCheckBox";
this.AllowOnlyOneCopyCheckBox.Size = new System.Drawing.Size(126, 18);
this.AllowOnlyOneCopyCheckBox.TabIndex = 92;
this.AllowOnlyOneCopyCheckBox.Text = "Allow only one copy";
this.AllowOnlyOneCopyCheckBox.CheckedChanged += new System.EventHandler(this.AllowOnlyOneCopyCheckBox_CheckedChanged);
//
// MinimizeToTrayCheckBox
//
this.MinimizeToTrayCheckBox.AutoSize = true;
this.MinimizeToTrayCheckBox.Checked = true;
this.MinimizeToTrayCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.MinimizeToTrayCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.MinimizeToTrayCheckBox.Location = new System.Drawing.Point(6, 94);
this.MinimizeToTrayCheckBox.Name = "MinimizeToTrayCheckBox";
this.MinimizeToTrayCheckBox.Size = new System.Drawing.Size(108, 18);
this.MinimizeToTrayCheckBox.TabIndex = 92;
this.MinimizeToTrayCheckBox.Text = "Minimize to Tray";
//
// StartWithWindowsCheckBox
//
this.StartWithWindowsCheckBox.AutoSize = true;
this.StartWithWindowsCheckBox.Checked = true;
this.StartWithWindowsCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.StartWithWindowsCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.StartWithWindowsCheckBox.Location = new System.Drawing.Point(6, 19);
this.StartWithWindowsCheckBox.Name = "StartWithWindowsCheckBox";
this.StartWithWindowsCheckBox.Size = new System.Drawing.Size(123, 18);
this.StartWithWindowsCheckBox.TabIndex = 67;
this.StartWithWindowsCheckBox.Text = "Start with Windows";
this.StartWithWindowsCheckBox.CheckedChanged += new System.EventHandler(this.StartWithWindowsCheckBox_CheckedChanged);
//
// AlwaysOnTopCheckBox
//
this.AlwaysOnTopCheckBox.AutoSize = true;
this.AlwaysOnTopCheckBox.Checked = global::JocysCom.Password.Generator.Properties.Settings.Default.AlwaysOnTop;
this.AlwaysOnTopCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.AlwaysOnTopCheckBox.DataBindings.Add(new System.Windows.Forms.Binding("Checked", global::JocysCom.Password.Generator.Properties.Settings.Default, "AlwaysOnTop", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
this.AlwaysOnTopCheckBox.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.AlwaysOnTopCheckBox.Location = new System.Drawing.Point(6, 70);
this.AlwaysOnTopCheckBox.Name = "AlwaysOnTopCheckBox";
this.AlwaysOnTopCheckBox.Size = new System.Drawing.Size(102, 18);
this.AlwaysOnTopCheckBox.TabIndex = 91;
this.AlwaysOnTopCheckBox.Text = "Always on Top";
this.AlwaysOnTopCheckBox.CheckedChanged += new System.EventHandler(this.AlwaysOnTopCheckBox_CheckedChanged);
//
// DataAndConfigurationGroupBox
//
this.DataAndConfigurationGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.DataAndConfigurationGroupBox.Controls.Add(this.LocalUserFolderOpenButton);
this.DataAndConfigurationGroupBox.Controls.Add(this.LocalUserFolderLabel);
this.DataAndConfigurationGroupBox.Controls.Add(this.LocalUserFolderTextBox);
this.DataAndConfigurationGroupBox.Location = new System.Drawing.Point(3, 3);
this.DataAndConfigurationGroupBox.Name = "DataAndConfigurationGroupBox";
this.DataAndConfigurationGroupBox.Size = new System.Drawing.Size(517, 61);
this.DataAndConfigurationGroupBox.TabIndex = 105;
this.DataAndConfigurationGroupBox.TabStop = false;
this.DataAndConfigurationGroupBox.Text = "Data and Configuration";
//
// LocalUserFolderOpenButton
//
this.LocalUserFolderOpenButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.LocalUserFolderOpenButton.Location = new System.Drawing.Point(436, 30);
this.LocalUserFolderOpenButton.Name = "LocalUserFolderOpenButton";
this.LocalUserFolderOpenButton.Size = new System.Drawing.Size(75, 23);
this.LocalUserFolderOpenButton.TabIndex = 93;
this.LocalUserFolderOpenButton.Text = "Open...";
this.LocalUserFolderOpenButton.UseVisualStyleBackColor = true;
this.LocalUserFolderOpenButton.Click += new System.EventHandler(this.LocalUserFolderOpenButton_Click);
//
// LocalUserFolderLabel
//
this.LocalUserFolderLabel.AutoSize = true;
this.LocalUserFolderLabel.Location = new System.Drawing.Point(6, 16);
this.LocalUserFolderLabel.Name = "LocalUserFolderLabel";
this.LocalUserFolderLabel.Size = new System.Drawing.Size(308, 13);
this.LocalUserFolderLabel.TabIndex = 92;
this.LocalUserFolderLabel.Text = "Current User Local Data - local to the user on this computer only";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.FavPreset3ComboBox);
this.groupBox1.Controls.Add(this.FavPreset2ComboBox);
this.groupBox1.Controls.Add(this.FavPreset1ComboBox);
this.groupBox1.Controls.Add(this.FavPreset3TextBox);
this.groupBox1.Controls.Add(this.FavPreset2TextBox);
this.groupBox1.Controls.Add(this.FavPreset1TextBox);
this.groupBox1.Location = new System.Drawing.Point(3, 70);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(517, 100);
this.groupBox1.TabIndex = 108;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Favorite Presets:";
//
// FavPreset3ComboBox
//
this.FavPreset3ComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.FavPreset3ComboBox.FormattingEnabled = true;
this.FavPreset3ComboBox.Location = new System.Drawing.Point(68, 73);
this.FavPreset3ComboBox.Name = "FavPreset3ComboBox";
this.FavPreset3ComboBox.Size = new System.Drawing.Size(180, 21);
this.FavPreset3ComboBox.TabIndex = 1;
this.FavPreset3ComboBox.SelectedIndexChanged += new System.EventHandler(this.FavPreset3ComboBox_SelectedIndexChanged);
//
// FavPreset2ComboBox
//
this.FavPreset2ComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.FavPreset2ComboBox.FormattingEnabled = true;
this.FavPreset2ComboBox.Location = new System.Drawing.Point(68, 46);
this.FavPreset2ComboBox.Name = "FavPreset2ComboBox";
this.FavPreset2ComboBox.Size = new System.Drawing.Size(180, 21);
this.FavPreset2ComboBox.TabIndex = 1;
this.FavPreset2ComboBox.SelectedIndexChanged += new System.EventHandler(this.FavPreset2ComboBox_SelectedIndexChanged);
//
// FavPreset1ComboBox
//
this.FavPreset1ComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.FavPreset1ComboBox.FormattingEnabled = true;
this.FavPreset1ComboBox.Location = new System.Drawing.Point(68, 19);
this.FavPreset1ComboBox.Name = "FavPreset1ComboBox";
this.FavPreset1ComboBox.Size = new System.Drawing.Size(180, 21);
this.FavPreset1ComboBox.TabIndex = 1;
this.FavPreset1ComboBox.SelectedIndexChanged += new System.EventHandler(this.FavPreset1ComboBox_SelectedIndexChanged);
//
// FavPreset3TextBox
//
this.FavPreset3TextBox.Location = new System.Drawing.Point(6, 73);
this.FavPreset3TextBox.Name = "FavPreset3TextBox";
this.FavPreset3TextBox.Size = new System.Drawing.Size(56, 20);
this.FavPreset3TextBox.TabIndex = 0;
this.FavPreset3TextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.FavPreset3TextBox.TextChanged += new System.EventHandler(this.FavPreset3TextBox_Changed);
//
// FavPreset2TextBox
//
this.FavPreset2TextBox.Location = new System.Drawing.Point(6, 46);
this.FavPreset2TextBox.Name = "FavPreset2TextBox";
this.FavPreset2TextBox.Size = new System.Drawing.Size(56, 20);
this.FavPreset2TextBox.TabIndex = 0;
this.FavPreset2TextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.FavPreset2TextBox.TextChanged += new System.EventHandler(this.FavPreset2TextBox_Changed);
//
// FavPreset1TextBox
//
this.FavPreset1TextBox.Location = new System.Drawing.Point(6, 19);
this.FavPreset1TextBox.Name = "FavPreset1TextBox";
this.FavPreset1TextBox.Size = new System.Drawing.Size(56, 20);
this.FavPreset1TextBox.TabIndex = 0;
this.FavPreset1TextBox.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.FavPreset1TextBox.TextChanged += new System.EventHandler(this.FavPreset1TextBox_Changed);
//
// OptionsControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.DataAndConfigurationGroupBox);
this.Controls.Add(this.ProgramStartGroupBox);
this.Controls.Add(this.AutoOptionsGroupBox);
this.Name = "OptionsControl";
this.Size = new System.Drawing.Size(523, 578);
this.AutoOptionsGroupBox.ResumeLayout(false);
this.AutoOptionsGroupBox.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nudAutoGenerateTimerSeconds)).EndInit();
this.ProgramStartGroupBox.ResumeLayout(false);
this.ProgramStartGroupBox.PerformLayout();
this.DataAndConfigurationGroupBox.ResumeLayout(false);
this.DataAndConfigurationGroupBox.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
internal System.Windows.Forms.CheckBox GeneratePasswordOnStartCheckBox;
internal System.Windows.Forms.CheckBox MinimizeToTrayCheckBox;
internal System.Windows.Forms.CheckBox AlwaysOnTopCheckBox;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
internal System.Windows.Forms.GroupBox AutoOptionsGroupBox;
internal System.Windows.Forms.NumericUpDown nudAutoGenerateTimerSeconds;
internal System.Windows.Forms.CheckBox GenerateOnCopyCheckBox;
internal System.Windows.Forms.CheckBox CopyOnGenerateCheckBox;
internal System.Windows.Forms.CheckBox OpenPasswordListFileAfterSaveCheckBox;
internal System.Windows.Forms.CheckBox GenerateTimerCheckBox;
internal System.Windows.Forms.CheckBox SaveProgramSettingsCheckBox;
internal System.Windows.Forms.GroupBox ProgramStartGroupBox;
internal System.Windows.Forms.GroupBox DataAndConfigurationGroupBox;
private System.Windows.Forms.Label LocalUserFolderLabel;
public System.Windows.Forms.CheckBox AllowOnlyOneCopyCheckBox;
public System.Windows.Forms.ComboBox StartWithWindowsStateComboBox;
public System.Windows.Forms.CheckBox StartWithWindowsCheckBox;
public System.Windows.Forms.CheckBox MinimizeOnCloseCheckBox;
private System.Windows.Forms.Button LocalUserFolderOpenButton;
public System.Windows.Forms.TextBox LocalUserFolderTextBox;
private System.Windows.Forms.Button ResetButton;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox groupBox1;
public System.Windows.Forms.TextBox FavPreset1TextBox;
public System.Windows.Forms.TextBox FavPreset3TextBox;
public System.Windows.Forms.TextBox FavPreset2TextBox;
public System.Windows.Forms.ComboBox FavPreset3ComboBox;
public System.Windows.Forms.ComboBox FavPreset2ComboBox;
public System.Windows.Forms.ComboBox FavPreset1ComboBox;
internal System.Windows.Forms.CheckBox CopyPasswordWhenStartCheckBox;
}
}
| JocysCom/PassGen | Generator/Controls/OptionsControl.Designer.cs | C# | lgpl-3.0 | 29,600 |