text
stringlengths
8
6.88M
// Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Prs3d_Drawer_HeaderFile #define _Prs3d_Drawer_HeaderFile #include <Standard.hxx> #include <Standard_Integer.hxx> #include <Aspect_TypeOfDeflection.hxx> #include <Graphic3d_GroupAspect.hxx> #include <Graphic3d_PresentationAttributes.hxx> #include <Graphic3d_ShaderProgram.hxx> #include <Standard_Real.hxx> #include <Prs3d_VertexDrawMode.hxx> #include <Prs3d_DimensionUnits.hxx> #include <Prs3d_TypeOfHLR.hxx> #include <Standard_Transient.hxx> #include <GeomAbs_Shape.hxx> class Prs3d_IsoAspect; class Prs3d_LineAspect; class Prs3d_TextAspect; class Prs3d_ShadingAspect; class Prs3d_PointAspect; class Prs3d_PlaneAspect; class Prs3d_ArrowAspect; class Prs3d_DatumAspect; class Prs3d_DimensionAspect; class TCollection_AsciiString; DEFINE_STANDARD_HANDLE(Prs3d_Drawer, Graphic3d_PresentationAttributes) //! A graphic attribute manager which governs how //! objects such as color, width, line thickness and deflection are displayed. //! A drawer includes an instance of the Aspect classes with particular default values. class Prs3d_Drawer : public Graphic3d_PresentationAttributes { DEFINE_STANDARD_RTTIEXT(Prs3d_Drawer, Graphic3d_PresentationAttributes) public: //! Default constructor. Standard_EXPORT Prs3d_Drawer(); //! Setup all own aspects with default values. Standard_EXPORT void SetupOwnDefaults(); //! Sets the type of chordal deflection. //! This indicates whether the deflection value is absolute or relative to the size of the object. Standard_EXPORT void SetTypeOfDeflection (const Aspect_TypeOfDeflection theTypeOfDeflection); //! Returns the type of chordal deflection. //! This indicates whether the deflection value is absolute or relative to the size of the object. Aspect_TypeOfDeflection TypeOfDeflection() const { return myHasOwnTypeOfDeflection || myLink.IsNull() ? myTypeOfDeflection : myLink->TypeOfDeflection(); } //! Returns true if the drawer has a type of deflection setting active. Standard_Boolean HasOwnTypeOfDeflection() const { return myHasOwnTypeOfDeflection; } //! Resets HasOwnTypeOfDeflection() flag, e.g. undoes SetTypeOfDeflection(). void UnsetOwnTypeOfDeflection() { myHasOwnTypeOfDeflection = false; myTypeOfDeflection = Aspect_TOD_RELATIVE; } //! Defines the maximal chordial deviation when drawing any curve. //! Even if the type of deviation is set to TOD_Relative, this value is used by: //! Prs3d_DeflectionCurve //! Prs3d_WFDeflectionSurface //! Prs3d_WFDeflectionRestrictedFace void SetMaximalChordialDeviation (const Standard_Real theChordialDeviation) { myChordialDeviation = theChordialDeviation; } //! Returns the maximal chordal deviation. The default value is 0.0001. //! Drawings of curves or patches are made with respect to an absolute maximal chordal deviation. Standard_Real MaximalChordialDeviation() const { return myChordialDeviation > 0.0 ? myChordialDeviation : (!myLink.IsNull() ? myLink->MaximalChordialDeviation() : 0.0001); } //! Returns true if the drawer has a maximal chordial deviation setting active. Standard_Boolean HasOwnMaximalChordialDeviation() const { return myChordialDeviation > 0.0; } //! Resets HasOwnMaximalChordialDeviation() flag, e.g. undoes SetMaximalChordialDeviation(). void UnsetOwnMaximalChordialDeviation() { myChordialDeviation = -1.0; } //! Sets the type of HLR algorithm used by drawer's interactive objects Standard_EXPORT void SetTypeOfHLR (const Prs3d_TypeOfHLR theTypeOfHLR); //! Returns the type of HLR algorithm currently in use. Standard_EXPORT Prs3d_TypeOfHLR TypeOfHLR() const; //! Returns true if the type of HLR is not equal to Prs3d_TOH_NotSet. Standard_Boolean HasOwnTypeOfHLR() const { return (myTypeOfHLR != Prs3d_TOH_NotSet); } //! Defines the maximum value allowed for the first and last //! parameters of an infinite curve. void SetMaximalParameterValue (const Standard_Real theValue) { myMaximalParameterValue = theValue; } //! Sets the maximum value allowed for the first and last parameters of an infinite curve. //! By default, this value is 500000. Standard_Real MaximalParameterValue() const { return myMaximalParameterValue > 0.0 ? myMaximalParameterValue : (!myLink.IsNull() ? myLink->MaximalParameterValue() : 500000.0); } //! Returns true if the drawer has a maximum value allowed for the first and last //! parameters of an infinite curve setting active. Standard_Boolean HasOwnMaximalParameterValue() const { return myMaximalParameterValue > 0.0; } //! Resets HasOwnMaximalParameterValue() flag, e.g. undoes SetMaximalParameterValue(). void UnsetOwnMaximalParameterValue() { myMaximalParameterValue = -1.0; } //! Sets IsoOnPlane on or off by setting the parameter theIsEnabled to true or false. Standard_EXPORT void SetIsoOnPlane (const Standard_Boolean theIsEnabled); //! Returns True if the drawing of isos on planes is enabled. Standard_Boolean IsoOnPlane() const { return myHasOwnIsoOnPlane || myLink.IsNull() ? myIsoOnPlane : myLink->IsoOnPlane(); } //! Returns true if the drawer has IsoOnPlane setting active. Standard_Boolean HasOwnIsoOnPlane() const { return myHasOwnIsoOnPlane; } //! Resets HasOwnIsoOnPlane() flag, e.g. undoes SetIsoOnPlane(). void UnsetOwnIsoOnPlane() { myHasOwnIsoOnPlane = false; myIsoOnPlane = false; } //! Returns True if the drawing of isos on triangulation is enabled. Standard_Boolean IsoOnTriangulation() const { return myHasOwnIsoOnTriangulation || myLink.IsNull() ? myIsoOnTriangulation : myLink->IsoOnTriangulation(); } //! Returns true if the drawer has IsoOnTriangulation setting active. Standard_Boolean HasOwnIsoOnTriangulation() const { return myHasOwnIsoOnTriangulation; } //! Resets HasOwnIsoOnTriangulation() flag, e.g. undoes SetIsoOnTriangulation(). void UnsetOwnIsoOnTriangulation() { myHasOwnIsoOnTriangulation = false; myIsoOnTriangulation = false; } //! Enables or disables isolines on triangulation by setting the parameter theIsEnabled to true or false. Standard_EXPORT void SetIsoOnTriangulation (const Standard_Boolean theToEnable); //! Sets the discretisation parameter theValue. void SetDiscretisation (const Standard_Integer theValue) { myNbPoints = theValue; } //! Returns the discretisation setting. Standard_Integer Discretisation() const { return myNbPoints != -1 ? myNbPoints : (!myLink.IsNull() ? myLink->Discretisation() : 30); } //! Returns true if the drawer has discretisation setting active. Standard_Boolean HasOwnDiscretisation() const { return myNbPoints != -1; } //! Resets HasOwnDiscretisation() flag, e.g. undoes SetDiscretisation(). void UnsetOwnDiscretisation() { myNbPoints = -1; } //! Sets the deviation coefficient theCoefficient. //! Also sets the hasOwnDeviationCoefficient flag to Standard_True and myPreviousDeviationCoefficient Standard_EXPORT void SetDeviationCoefficient (const Standard_Real theCoefficient); //! Returns the deviation coefficient. //! Drawings of curves or patches are made with respect //! to a maximal chordal deviation. A Deviation coefficient //! is used in the shading display mode. The shape is //! seen decomposed into triangles. These are used to //! calculate reflection of light from the surface of the //! object. The triangles are formed from chords of the //! curves in the shape. The deviation coefficient gives //! the highest value of the angle with which a chord can //! deviate from a tangent to a curve. If this limit is //! reached, a new triangle is begun. //! This deviation is absolute and is set through the //! method: SetMaximalChordialDeviation. The default value is 0.001. //! In drawing shapes, however, you are allowed to ask //! for a relative deviation. This deviation will be: //! SizeOfObject * DeviationCoefficient. Standard_Real DeviationCoefficient() const { return myDeviationCoefficient > 0.0 ? myDeviationCoefficient : (!myLink.IsNull() ? myLink->DeviationCoefficient() : 0.001); } //! Resets HasOwnDeviationCoefficient() flag, e.g. undoes previous SetDeviationCoefficient(). void SetDeviationCoefficient() { myDeviationCoefficient = -1.0; } //! Returns true if there is a local setting for deviation //! coefficient in this framework for a specific interactive object. Standard_Boolean HasOwnDeviationCoefficient() const { return myDeviationCoefficient > 0.0; } //! Saves the previous value used for the chordal //! deviation coefficient. Standard_Real PreviousDeviationCoefficient() const { return HasOwnDeviationCoefficient() ? myPreviousDeviationCoefficient : 0.0; } //! Updates the previous value used for the chordal deviation coefficient to the current state. void UpdatePreviousDeviationCoefficient() { if (HasOwnDeviationCoefficient()) { myPreviousDeviationCoefficient = DeviationCoefficient(); } } //! Sets the deviation angle theAngle. //! Also sets the hasOwnDeviationAngle flag to Standard_True, and myPreviousDeviationAngle. Standard_EXPORT void SetDeviationAngle (const Standard_Real theAngle); //! Returns the value for deviation angle in radians, 20 * M_PI / 180 by default. Standard_Real DeviationAngle() const { return myDeviationAngle > 0.0 ? myDeviationAngle : (!myLink.IsNull() ? myLink->DeviationAngle() : 20.0 * M_PI / 180.0); } //! Resets HasOwnDeviationAngle() flag, e.g. undoes previous SetDeviationAngle(). void SetDeviationAngle() { myDeviationAngle = -1.0; } //! Returns true if there is a local setting for deviation //! angle in this framework for a specific interactive object. Standard_Boolean HasOwnDeviationAngle() const { return myDeviationAngle > 0.0; } //! Returns the previous deviation angle Standard_Real PreviousDeviationAngle() const { return HasOwnDeviationAngle() ? myPreviousDeviationAngle : 0.0; } //! Updates the previous deviation angle to the current value void UpdatePreviousDeviationAngle() { if (HasOwnDeviationAngle()) { myPreviousDeviationAngle = DeviationAngle(); } } //! Sets IsAutoTriangulated on or off by setting the parameter theIsEnabled to true or false. //! If this flag is True automatic re-triangulation with deflection-check logic will be applied. //! Else this feature will be disable and triangulation is expected to be computed by application itself //! and no shading presentation at all if unavailable. Standard_EXPORT void SetAutoTriangulation (const Standard_Boolean theIsEnabled); //! Returns True if automatic triangulation is enabled. Standard_Boolean IsAutoTriangulation() const { return myHasOwnIsAutoTriangulated || myLink.IsNull() ? myIsAutoTriangulated : myLink->IsAutoTriangulation(); } //! Returns true if the drawer has IsoOnPlane setting active. Standard_Boolean HasOwnIsAutoTriangulation() const { return myHasOwnIsAutoTriangulated; } //! Resets HasOwnIsAutoTriangulation() flag, e.g. undoes SetAutoTriangulation(). void UnsetOwnIsAutoTriangulation() { myHasOwnIsAutoTriangulated = false; myIsAutoTriangulated = true; } //! Defines own attributes for drawing an U isoparametric curve of a face, //! settings from linked Drawer or NULL if neither was set. //! //! These attributes are used by the following algorithms: //! Prs3d_WFDeflectionSurface //! Prs3d_WFDeflectionRestrictedFace Standard_EXPORT const Handle(Prs3d_IsoAspect)& UIsoAspect() const; void SetUIsoAspect (const Handle(Prs3d_IsoAspect)& theAspect) { myUIsoAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! UIso aspect that overrides the one in the link. Standard_Boolean HasOwnUIsoAspect() const { return !myUIsoAspect.IsNull(); } //! Defines own attributes for drawing an V isoparametric curve of a face, //! settings from linked Drawer or NULL if neither was set. //! //! These attributes are used by the following algorithms: //! Prs3d_WFDeflectionSurface //! Prs3d_WFDeflectionRestrictedFace Standard_EXPORT const Handle(Prs3d_IsoAspect)& VIsoAspect() const; //! Sets the appearance of V isoparameters - theAspect. void SetVIsoAspect (const Handle(Prs3d_IsoAspect)& theAspect) { myVIsoAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! VIso aspect that overrides the one in the link. Standard_Boolean HasOwnVIsoAspect() const { return !myVIsoAspect.IsNull(); } //! Returns own wire aspect settings, settings from linked Drawer or NULL if neither was set. //! These attributes are used by the algorithm Prs3d_WFShape. Standard_EXPORT const Handle(Prs3d_LineAspect)& WireAspect() const; //! Sets the parameter theAspect for display of wires. void SetWireAspect (const Handle(Prs3d_LineAspect)& theAspect) { myWireAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! wire aspect that overrides the one in the link. Standard_Boolean HasOwnWireAspect() const { return !myWireAspect.IsNull(); } //! Sets WireDraw on or off by setting the parameter theIsEnabled to true or false. Standard_EXPORT void SetWireDraw(const Standard_Boolean theIsEnabled); //! Returns True if the drawing of the wire is enabled. Standard_Boolean WireDraw() const { return myHasOwnWireDraw || myLink.IsNull() ? myWireDraw : myLink->WireDraw(); } //! Returns true if the drawer has its own attribute for //! "draw wires" flag that overrides the one in the link. Standard_Boolean HasOwnWireDraw() const { return myHasOwnWireDraw; } //! Resets HasOwnWireDraw() flag, e.g. undoes SetWireDraw(). void UnsetOwnWireDraw() { myHasOwnWireDraw = false; myWireDraw = true; } //! Returns own point aspect setting, settings from linked Drawer or NULL if neither was set. //! These attributes are used by the algorithms Prs3d_Point. Standard_EXPORT const Handle(Prs3d_PointAspect)& PointAspect() const; //! Sets the parameter theAspect for display attributes of points void SetPointAspect (const Handle(Prs3d_PointAspect)& theAspect) { myPointAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! point aspect that overrides the one in the link. Standard_Boolean HasOwnPointAspect() const { return !myPointAspect.IsNull(); } //! Sets own point aspect, which is a yellow Aspect_TOM_PLUS marker by default. //! Returns FALSE if the drawer already has its own attribute for point aspect. Standard_EXPORT Standard_Boolean SetupOwnPointAspect (const Handle(Prs3d_Drawer)& theDefaults = Handle(Prs3d_Drawer)()); //! Returns own settings for line aspects, settings from linked Drawer or NULL if neither was set. //! These attributes are used by the following algorithms: //! Prs3d_Curve //! Prs3d_Line //! Prs3d_HLRShape Standard_EXPORT const Handle(Prs3d_LineAspect)& LineAspect() const; //! Sets the parameter theAspect for display attributes of lines. void SetLineAspect (const Handle(Prs3d_LineAspect)& theAspect) { myLineAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! line aspect that overrides the one in the link. Standard_Boolean HasOwnLineAspect() const { return !myLineAspect.IsNull(); } //! Sets own line aspects, which are //! single U and single V gray75 solid isolines (::UIsoAspect(), ::VIsoAspect()), //! red wire (::WireAspect()), yellow line (::LineAspect()), //! yellow seen line (::SeenLineAspect()), dashed yellow hidden line (::HiddenLineAspect()), //! green free boundary (::FreeBoundaryAspect()), yellow unfree boundary (::UnFreeBoundaryAspect()). //! Returns FALSE if own line aspect are already set. Standard_EXPORT Standard_Boolean SetOwnLineAspects (const Handle(Prs3d_Drawer)& theDefaults = Handle(Prs3d_Drawer)()); //! Sets own line aspects for datums. //! Returns FALSE if own line for datums are already set. Standard_EXPORT Standard_Boolean SetOwnDatumAspects (const Handle(Prs3d_Drawer)& theDefaults = Handle(Prs3d_Drawer)()); //! Returns own settings for text aspect, settings from linked Drawer or NULL if neither was set. Standard_EXPORT const Handle(Prs3d_TextAspect)& TextAspect() const; //! Sets the parameter theAspect for display attributes of text. void SetTextAspect (const Handle(Prs3d_TextAspect)& theAspect) { myTextAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! text aspect that overrides the one in the link. Standard_Boolean HasOwnTextAspect() const { return !myTextAspect.IsNull(); } //! Returns own settings for shading aspects, settings from linked Drawer or NULL if neither was set. Standard_EXPORT const Handle(Prs3d_ShadingAspect)& ShadingAspect() const; //! Sets the parameter theAspect for display attributes of shading. void SetShadingAspect (const Handle(Prs3d_ShadingAspect)& theAspect) { myShadingAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! shading aspect that overrides the one in the link. Standard_Boolean HasOwnShadingAspect() const { return !myShadingAspect.IsNull(); } //! Sets own shading aspect, which is Graphic3d_NameOfMaterial_Brass material by default. //! Returns FALSE if the drawer already has its own attribute for shading aspect. Standard_EXPORT Standard_Boolean SetupOwnShadingAspect (const Handle(Prs3d_Drawer)& theDefaults = Handle(Prs3d_Drawer)()); //! Returns own settings for seen line aspects, settings of linked Drawer or NULL if neither was set. Standard_EXPORT const Handle(Prs3d_LineAspect)& SeenLineAspect() const; //! Sets the parameter theAspect for the display of seen lines in hidden line removal mode. void SetSeenLineAspect (const Handle(Prs3d_LineAspect)& theAspect) { mySeenLineAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! seen line aspect that overrides the one in the link. Standard_Boolean HasOwnSeenLineAspect() const { return !mySeenLineAspect.IsNull(); } //! Returns own settings for the appearance of planes, settings from linked Drawer or NULL if neither was set. Standard_EXPORT const Handle(Prs3d_PlaneAspect)& PlaneAspect() const; //! Sets the parameter theAspect for the display of planes. void SetPlaneAspect (const Handle(Prs3d_PlaneAspect)& theAspect) { myPlaneAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! plane aspect that overrides the one in the link. Standard_Boolean HasOwnPlaneAspect() const { return !myPlaneAspect.IsNull(); } //! Returns own attributes for display of arrows, settings from linked Drawer or NULL if neither was set. Standard_EXPORT const Handle(Prs3d_ArrowAspect)& ArrowAspect() const; //! Sets the parameter theAspect for display attributes of arrows. void SetArrowAspect (const Handle(Prs3d_ArrowAspect)& theAspect) { myArrowAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! arrow aspect that overrides the one in the link. Standard_Boolean HasOwnArrowAspect() const { return !myArrowAspect.IsNull(); } //! Enables the drawing of an arrow at the end of each line. //! By default the arrows are not drawn. Standard_EXPORT void SetLineArrowDraw (const Standard_Boolean theIsEnabled); //! Returns True if drawing an arrow at the end of each edge is enabled //! and False otherwise (the default). Standard_Boolean LineArrowDraw() const { return myHasOwnLineArrowDraw || myLink.IsNull() ? myLineArrowDraw : myLink->LineArrowDraw(); } //! Returns true if the drawer has its own attribute for //! "draw arrow" flag that overrides the one in the link. Standard_Boolean HasOwnLineArrowDraw() const { return myHasOwnLineArrowDraw; } //! Reset HasOwnLineArrowDraw() flag, e.g. undoes SetLineArrowDraw(). void UnsetOwnLineArrowDraw() { myHasOwnLineArrowDraw = false; myLineArrowDraw = false; } //! Returns own settings for hidden line aspects, settings from linked Drawer or NULL if neither was set. Standard_EXPORT const Handle(Prs3d_LineAspect)& HiddenLineAspect() const; //! Sets the parameter theAspect for the display of hidden lines in hidden line removal mode. void SetHiddenLineAspect (const Handle(Prs3d_LineAspect)& theAspect) { myHiddenLineAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! hidden lines aspect that overrides the one in the link. Standard_Boolean HasOwnHiddenLineAspect() const { return !myHiddenLineAspect.IsNull(); } //! Returns Standard_True if the hidden lines are to be drawn. //! By default the hidden lines are not drawn. Standard_Boolean DrawHiddenLine() const { return myHasOwnDrawHiddenLine || myLink.IsNull() ? myDrawHiddenLine : myLink->DrawHiddenLine(); } //! Enables the DrawHiddenLine function. Standard_EXPORT void EnableDrawHiddenLine(); //! Disables the DrawHiddenLine function. Standard_EXPORT void DisableDrawHiddenLine(); //! Returns true if the drawer has its own attribute for //! "draw hidden lines" flag that overrides the one in the link. Standard_Boolean HasOwnDrawHiddenLine() const { return myHasOwnDrawHiddenLine; } //! Resets HasOwnDrawHiddenLine() flag, e.g. unsets EnableDrawHiddenLine()/DisableDrawHiddenLine(). void UnsetOwnDrawHiddenLine() { myHasOwnDrawHiddenLine = false; myDrawHiddenLine = false; } //! Returns own settings for the appearance of vectors, settings from linked Drawer or NULL if neither was set. Standard_EXPORT const Handle(Prs3d_LineAspect)& VectorAspect() const; //! Sets the modality theAspect for the display of vectors. void SetVectorAspect (const Handle(Prs3d_LineAspect)& theAspect) { myVectorAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! vector aspect that overrides the one in the link. Standard_Boolean HasOwnVectorAspect() const { return !myVectorAspect.IsNull(); } //! Sets the mode of visualization of vertices of a TopoDS_Shape instance. //! By default, only stand-alone vertices (not belonging topologically to an edge) are drawn, //! that corresponds to Prs3d_VDM_Standalone mode. //! Switching to Prs3d_VDM_Standalone mode makes all shape's vertices visible. //! To inherit this parameter from the global drawer instance ("the link") when it is present, //! Prs3d_VDM_Inherited value should be used. Standard_EXPORT void SetVertexDrawMode (const Prs3d_VertexDrawMode theMode); //! Returns the current mode of visualization of vertices of a TopoDS_Shape instance. Standard_EXPORT Prs3d_VertexDrawMode VertexDrawMode() const; //! Returns true if the vertex draw mode is not equal to <b>Prs3d_VDM_Inherited</b>. //! This means that individual vertex draw mode value (i.e. not inherited from the global //! drawer) is used for a specific interactive object. Standard_Boolean HasOwnVertexDrawMode() const { return (myVertexDrawMode != Prs3d_VDM_Inherited); } //! Returns own settings for the appearance of datums, settings from linked Drawer or NULL if neither was set. Standard_EXPORT const Handle(Prs3d_DatumAspect)& DatumAspect() const; //! Sets the modality theAspect for the display of datums. void SetDatumAspect (const Handle(Prs3d_DatumAspect)& theAspect) { myDatumAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! datum aspect that overrides the one in the link. Standard_Boolean HasOwnDatumAspect() const { return !myDatumAspect.IsNull(); } //! Returns own LineAspect for section wire, settings from linked Drawer or NULL if neither was set. //! These attributes are used by the algorithm Prs3d_WFShape. Standard_EXPORT const Handle(Prs3d_LineAspect)& SectionAspect() const; //! Sets the parameter theAspect for display attributes of sections. void SetSectionAspect (const Handle(Prs3d_LineAspect)& theAspect) { mySectionAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! section aspect that overrides the one in the link. Standard_Boolean HasOwnSectionAspect() const { return !mySectionAspect.IsNull(); } //! Sets the parameter theAspect for the display of free boundaries. //! The method sets aspect owned by the drawer that will be used during //! visualization instead of the one set in link. void SetFreeBoundaryAspect (const Handle(Prs3d_LineAspect)& theAspect) { myFreeBoundaryAspect = theAspect; } //! Returns own settings for presentation of free boundaries, settings from linked Drawer or NULL if neither was set. //! In other words, this settings affect boundaries which are not shared. //! These attributes are used by the algorithm Prs3d_WFShape Standard_EXPORT const Handle(Prs3d_LineAspect)& FreeBoundaryAspect() const; //! Returns true if the drawer has its own attribute for //! free boundaries aspect that overrides the one in the link. Standard_Boolean HasOwnFreeBoundaryAspect() const { return !myFreeBoundaryAspect.IsNull(); } //! Enables or disables drawing of free boundaries for shading presentations. //! The method sets drawing flag owned by the drawer that will be used during //! visualization instead of the one set in link. //! theIsEnabled is a boolean flag indicating whether the free boundaries should be //! drawn or not. Standard_EXPORT void SetFreeBoundaryDraw (const Standard_Boolean theIsEnabled); //! Returns True if the drawing of the free boundaries is enabled //! True is the default setting. Standard_Boolean FreeBoundaryDraw() const { return myHasOwnFreeBoundaryDraw || myLink.IsNull() ? myFreeBoundaryDraw : myLink->FreeBoundaryDraw(); } //! Returns true if the drawer has its own attribute for //! "draw free boundaries" flag that overrides the one in the link. Standard_Boolean HasOwnFreeBoundaryDraw() const { return myHasOwnFreeBoundaryDraw; } //! Resets HasOwnFreeBoundaryDraw() flag, e.g. undoes SetFreeBoundaryDraw(). void UnsetOwnFreeBoundaryDraw() { myHasOwnFreeBoundaryDraw = false; myFreeBoundaryDraw = true; } //! Sets the parameter theAspect for the display of shared boundaries. //! The method sets aspect owned by the drawer that will be used during //! visualization instead of the one set in link. void SetUnFreeBoundaryAspect (const Handle(Prs3d_LineAspect)& theAspect) { myUnFreeBoundaryAspect = theAspect; } //! Returns own settings for shared boundary line aspects, settings from linked Drawer or NULL if neither was set. //! These attributes are used by the algorithm Prs3d_WFShape Standard_EXPORT const Handle(Prs3d_LineAspect)& UnFreeBoundaryAspect() const; //! Returns true if the drawer has its own attribute for //! unfree boundaries aspect that overrides the one in the link. Standard_Boolean HasOwnUnFreeBoundaryAspect() const { return !myUnFreeBoundaryAspect.IsNull(); } //! Enables or disables drawing of shared boundaries for shading presentations. //! The method sets drawing flag owned by the drawer that will be used during //! visualization instead of the one set in link. //! theIsEnabled is a boolean flag indicating whether the shared boundaries should be drawn or not. Standard_EXPORT void SetUnFreeBoundaryDraw (const Standard_Boolean theIsEnabled); //! Returns True if the drawing of the shared boundaries is enabled. //! True is the default setting. Standard_Boolean UnFreeBoundaryDraw() const { return myHasOwnUnFreeBoundaryDraw || myLink.IsNull() ? myUnFreeBoundaryDraw : myLink->UnFreeBoundaryDraw(); } //! Returns true if the drawer has its own attribute for //! "draw shared boundaries" flag that overrides the one in the link. Standard_Boolean HasOwnUnFreeBoundaryDraw() const { return myHasOwnUnFreeBoundaryDraw; } //! Resets HasOwnUnFreeBoundaryDraw() flag, e.g. undoes SetUnFreeBoundaryDraw(). void UnsetOwnUnFreeBoundaryDraw() { myHasOwnUnFreeBoundaryDraw = false; myUnFreeBoundaryDraw = true; } //! Sets line aspect for face boundaries. //! The method sets line aspect owned by the drawer that will be used during //! visualization instead of the one set in link. //! theAspect is the line aspect that determines the look of the face boundaries. void SetFaceBoundaryAspect (const Handle(Prs3d_LineAspect)& theAspect) { myFaceBoundaryAspect = theAspect; } //! Returns own line aspect of face boundaries, settings from linked Drawer or NULL if neither was set. Standard_EXPORT const Handle(Prs3d_LineAspect)& FaceBoundaryAspect() const; //! Returns true if the drawer has its own attribute for //! face boundaries aspect that overrides the one in the link. Standard_Boolean HasOwnFaceBoundaryAspect() const { return !myFaceBoundaryAspect.IsNull(); } //! Sets own face boundary aspect, which is a black solid line by default. //! Returns FALSE if the drawer already has its own attribute for face boundary aspect. Standard_EXPORT Standard_Boolean SetupOwnFaceBoundaryAspect (const Handle(Prs3d_Drawer)& theDefaults = Handle(Prs3d_Drawer)()); //! Enables or disables face boundary drawing for shading presentations. //! The method sets drawing flag owned by the drawer that will be used during //! visualization instead of the one set in link. //! theIsEnabled is a boolean flag indicating whether the face boundaries should be drawn or not. Standard_EXPORT void SetFaceBoundaryDraw (const Standard_Boolean theIsEnabled); //! Checks whether the face boundary drawing is enabled or not. Standard_Boolean FaceBoundaryDraw() const { return myHasOwnFaceBoundaryDraw || myLink.IsNull() ? myFaceBoundaryDraw : myLink->FaceBoundaryDraw(); } //! Returns true if the drawer has its own attribute for //! "draw face boundaries" flag that overrides the one in the link. Standard_Boolean HasOwnFaceBoundaryDraw() const { return myHasOwnFaceBoundaryDraw; } //! Resets HasOwnFaceBoundaryDraw() flag, e.g. undoes SetFaceBoundaryDraw(). void UnsetOwnFaceBoundaryDraw() { myHasOwnFaceBoundaryDraw = false; myFaceBoundaryDraw = false; } //! Returns true if the drawer has its own attribute for face boundaries upper edge continuity class that overrides the one in the link. Standard_Boolean HasOwnFaceBoundaryUpperContinuity() const { return myFaceBoundaryUpperContinuity != -1; } //! Get the most edge continuity class; GeomAbs_CN by default (all edges). GeomAbs_Shape FaceBoundaryUpperContinuity() const { return HasOwnFaceBoundaryUpperContinuity() ? (GeomAbs_Shape )myFaceBoundaryUpperContinuity : (!myLink.IsNull() ? myLink->FaceBoundaryUpperContinuity() : GeomAbs_CN); } //! Set the most edge continuity class for face boundaries. void SetFaceBoundaryUpperContinuity (GeomAbs_Shape theMostAllowedEdgeClass) { myFaceBoundaryUpperContinuity = theMostAllowedEdgeClass; } //! Unset the most edge continuity class for face boundaries. void UnsetFaceBoundaryUpperContinuity() { myFaceBoundaryUpperContinuity = -1; } //! Returns own settings for the appearance of dimensions, settings from linked Drawer or NULL if neither was set. Standard_EXPORT const Handle(Prs3d_DimensionAspect)& DimensionAspect() const; //! Sets the settings for the appearance of dimensions. //! The method sets aspect owned by the drawer that will be used during //! visualization instead of the one set in link. void SetDimensionAspect (const Handle(Prs3d_DimensionAspect)& theAspect) { myDimensionAspect = theAspect; } //! Returns true if the drawer has its own attribute for //! the appearance of dimensions that overrides the one in the link. Standard_Boolean HasOwnDimensionAspect() const { return !myDimensionAspect.IsNull(); } //! Sets dimension length model units for computing of dimension presentation. //! The method sets value owned by the drawer that will be used during //! visualization instead of the one set in link. Standard_EXPORT void SetDimLengthModelUnits (const TCollection_AsciiString& theUnits); //! Sets dimension angle model units for computing of dimension presentation. //! The method sets value owned by the drawer that will be used during //! visualization instead of the one set in link. Standard_EXPORT void SetDimAngleModelUnits (const TCollection_AsciiString& theUnits); //! Returns length model units for the dimension presentation. const TCollection_AsciiString& DimLengthModelUnits() const { return myHasOwnDimLengthModelUnits || myLink.IsNull() ? myDimensionModelUnits.GetLengthUnits() : myLink->DimLengthModelUnits(); } //! Returns angle model units for the dimension presentation. const TCollection_AsciiString& DimAngleModelUnits() const { return myHasOwnDimAngleModelUnits || myLink.IsNull() ? myDimensionModelUnits.GetAngleUnits() : myLink->DimAngleModelUnits(); } //! Returns true if the drawer has its own attribute for //! dimension length model units that overrides the one in the link. Standard_Boolean HasOwnDimLengthModelUnits() const { return myHasOwnDimLengthModelUnits; } //! Resets HasOwnDimLengthModelUnits() flag, e.g. undoes SetDimLengthModelUnits(). void UnsetOwnDimLengthModelUnits() { myHasOwnDimLengthModelUnits = false; myDimensionModelUnits.SetLengthUnits ("m"); } //! Returns true if the drawer has its own attribute for //! dimension angle model units that overrides the one in the link. Standard_Boolean HasOwnDimAngleModelUnits() const { return myHasOwnDimAngleModelUnits; } //! Resets HasOwnDimAngleModelUnits() flag, e.g. undoes SetDimAngleModelUnits(). void UnsetOwnDimAngleModelUnits() { myHasOwnDimAngleModelUnits = false; myDimensionModelUnits.SetAngleUnits ("rad"); } //! Sets length units in which value for dimension presentation is displayed. //! The method sets value owned by the drawer that will be used during //! visualization instead of the one set in link. Standard_EXPORT void SetDimLengthDisplayUnits (const TCollection_AsciiString& theUnits); //! Sets angle units in which value for dimension presentation is displayed. //! The method sets value owned by the drawer that will be used during //! visualization instead of the one set in link. Standard_EXPORT void SetDimAngleDisplayUnits (const TCollection_AsciiString& theUnits); //! Returns length units in which dimension presentation is displayed. const TCollection_AsciiString& DimLengthDisplayUnits() const { return myHasOwnDimLengthDisplayUnits || myLink.IsNull() ? myDimensionDisplayUnits.GetLengthUnits() : myLink->DimLengthDisplayUnits(); } //! Returns angle units in which dimension presentation is displayed. const TCollection_AsciiString& DimAngleDisplayUnits() const { return myHasOwnDimAngleDisplayUnits || myLink.IsNull() ? myDimensionDisplayUnits.GetAngleUnits() : myLink->DimAngleDisplayUnits(); } //! Returns true if the drawer has its own attribute for //! length units in which dimension presentation is displayed //! that overrides the one in the link. Standard_Boolean HasOwnDimLengthDisplayUnits() const { return myHasOwnDimLengthDisplayUnits; } //! Resets HasOwnDimLengthModelUnits() flag, e.g. undoes SetDimLengthDisplayUnits(). void UnsetOwnDimLengthDisplayUnits() { myHasOwnDimLengthDisplayUnits = false; myDimensionDisplayUnits.SetLengthUnits ("m"); } //! Returns true if the drawer has its own attribute for //! angle units in which dimension presentation is displayed //! that overrides the one in the link. Standard_Boolean HasOwnDimAngleDisplayUnits() const { return myHasOwnDimAngleDisplayUnits; } //! Resets HasOwnDimAngleDisplayUnits() flag, e.g. undoes SetDimLengthDisplayUnits(). void UnsetOwnDimAngleDisplayUnits() { myHasOwnDimAngleDisplayUnits = false; myDimensionDisplayUnits.SetAngleUnits ("deg"); } public: //! Returns the drawer to which the current object references. const Handle(Prs3d_Drawer)& Link() const { return myLink; } //! Returns true if the current object has a link on the other drawer. Standard_Boolean HasLink() const { return !myLink.IsNull(); } //! Sets theDrawer as a link to which the current object references. void Link (const Handle(Prs3d_Drawer)& theDrawer) { SetLink (theDrawer); } //! Sets theDrawer as a link to which the current object references. void SetLink (const Handle(Prs3d_Drawer)& theDrawer) { myLink = theDrawer; } //! Removes local attributes. Standard_EXPORT void ClearLocalAttributes(); //! Assign shader program for specified type of primitives. //! @param theProgram new program to set (might be NULL) //! @param theAspect the type of primitives //! @param theToOverrideDefaults if true then non-overridden attributes using defaults will be allocated and copied from the Link; //! otherwise, only already customized attributes will be changed //! @return TRUE if presentation should be recomputed after creating aspects not previously customized (if theToOverrideDefaults is also TRUE) Standard_EXPORT bool SetShaderProgram (const Handle(Graphic3d_ShaderProgram)& theProgram, const Graphic3d_GroupAspect theAspect, const bool theToOverrideDefaults = false); //! Sets Shading Model type for the shading aspect. Standard_EXPORT bool SetShadingModel (Graphic3d_TypeOfShadingModel theModel, bool theToOverrideDefaults = false); //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE; public: //! @name deprecated methods Standard_DEPRECATED("SetDeviationAngle() should be used instead") void SetHLRAngle (const Standard_Real theAngle) { SetDeviationAngle (theAngle); } Standard_DEPRECATED("DeviationAngle() should be used instead") Standard_Real HLRAngle() const { return DeviationAngle(); } Standard_DEPRECATED("SetDeviationAngle() should be used instead") void SetHLRAngle() { SetDeviationAngle(); } Standard_DEPRECATED("HasOwnDeviationAngle() should be used instead") Standard_Boolean HasOwnHLRDeviationAngle() const { return HasOwnDeviationAngle(); } Standard_DEPRECATED("PreviousDeviationAngle() should be used instead") Standard_Real PreviousHLRDeviationAngle() const { return PreviousDeviationAngle(); } protected: Handle(Prs3d_Drawer) myLink; Standard_Integer myNbPoints; Standard_Real myMaximalParameterValue; Standard_Real myChordialDeviation; Aspect_TypeOfDeflection myTypeOfDeflection; Standard_Boolean myHasOwnTypeOfDeflection; Prs3d_TypeOfHLR myTypeOfHLR; Standard_Real myDeviationCoefficient; Standard_Real myPreviousDeviationCoefficient; Standard_Real myDeviationAngle; Standard_Real myPreviousDeviationAngle; Standard_Boolean myIsoOnPlane; Standard_Boolean myHasOwnIsoOnPlane; Standard_Boolean myIsoOnTriangulation; Standard_Boolean myHasOwnIsoOnTriangulation; Standard_Boolean myIsAutoTriangulated; Standard_Boolean myHasOwnIsAutoTriangulated; Handle(Prs3d_IsoAspect) myUIsoAspect; Handle(Prs3d_IsoAspect) myVIsoAspect; Handle(Prs3d_LineAspect) myWireAspect; Standard_Boolean myWireDraw; Standard_Boolean myHasOwnWireDraw; Handle(Prs3d_PointAspect) myPointAspect; Handle(Prs3d_LineAspect) myLineAspect; Handle(Prs3d_TextAspect) myTextAspect; Handle(Prs3d_ShadingAspect) myShadingAspect; Handle(Prs3d_PlaneAspect) myPlaneAspect; Handle(Prs3d_LineAspect) mySeenLineAspect; Handle(Prs3d_ArrowAspect) myArrowAspect; Standard_Boolean myLineArrowDraw; Standard_Boolean myHasOwnLineArrowDraw; Handle(Prs3d_LineAspect) myHiddenLineAspect; Standard_Boolean myDrawHiddenLine; Standard_Boolean myHasOwnDrawHiddenLine; Handle(Prs3d_LineAspect) myVectorAspect; Prs3d_VertexDrawMode myVertexDrawMode; Handle(Prs3d_DatumAspect) myDatumAspect; Handle(Prs3d_LineAspect) mySectionAspect; Handle(Prs3d_LineAspect) myFreeBoundaryAspect; Standard_Boolean myFreeBoundaryDraw; Standard_Boolean myHasOwnFreeBoundaryDraw; Handle(Prs3d_LineAspect) myUnFreeBoundaryAspect; Standard_Boolean myUnFreeBoundaryDraw; Standard_Boolean myHasOwnUnFreeBoundaryDraw; Handle(Prs3d_LineAspect) myFaceBoundaryAspect; Standard_Integer myFaceBoundaryUpperContinuity; //!< the most edge continuity class (GeomAbs_Shape) to be included to face boundaries presentation, or -1 if undefined Standard_Boolean myFaceBoundaryDraw; Standard_Boolean myHasOwnFaceBoundaryDraw; Handle(Prs3d_DimensionAspect) myDimensionAspect; Prs3d_DimensionUnits myDimensionModelUnits; Standard_Boolean myHasOwnDimLengthModelUnits; Standard_Boolean myHasOwnDimAngleModelUnits; Prs3d_DimensionUnits myDimensionDisplayUnits; Standard_Boolean myHasOwnDimLengthDisplayUnits; Standard_Boolean myHasOwnDimAngleDisplayUnits; }; #endif // _Prs3d_Drawer_HeaderFile
#include <string> #include <cmath> #include <fstream> #include <iostream> #include <sstream> #include <list> #include <algorithm> #include <set> #include <map> #include <stack> #include <queue> #include <numeric> #include <bitset> #include <deque> //#include <random> #include <string.h> #include <stdlib.h> #include <vector> #include <unordered_map> #include <thread> const long long LINF = (5e18); const int INF = (1<<28); const int sINF = (1<<23); const int MOD = 1000000009; const double EPS = 1e-6; using namespace std; class CatchTheBeatEasy { public: typedef pair<int, int> P; string ableToCatchAll(vector <int> x, vector <int> y) { vector<P> p; for (int i=0; i<x.size(); ++i) p.push_back(P(y[i], x[i])); sort(p.begin(), p.end()); int prvx = 0, prvy = 0; for (int i=0; i<x.size(); ++i) { int dx = abs(prvx - p[i].second); int dy = abs(p[i].first - prvy); if (dx > dy) return "Not able to catch"; prvx = p[i].second; prvy = p[i].first; } return "Able to catch"; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {-1, 1, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1, 3, 4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Able to catch"; verify_case(0, Arg2, ableToCatchAll(Arg0, Arg1)); } void test_case_1() { int Arr0[] = {-3}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Not able to catch"; verify_case(1, Arg2, ableToCatchAll(Arg0, Arg1)); } void test_case_2() { int Arr0[] = {-1, 1, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1, 2, 4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Not able to catch"; verify_case(2, Arg2, ableToCatchAll(Arg0, Arg1)); } void test_case_3() { int Arr0[] = {0, -1, 1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {9, 1, 3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Able to catch"; verify_case(3, Arg2, ableToCatchAll(Arg0, Arg1)); } void test_case_4() { int Arr0[] = {70,-108,52,-70,84,-29,66,-33}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {141,299,402,280,28,363,427,232}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Not able to catch"; verify_case(4, Arg2, ableToCatchAll(Arg0, Arg1)); } void test_case_5() { int Arr0[] = {-175,-28,-207,-29,-43,-183,-175,-112,-183,-31,-25,-66,-114,-116,-66}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {320,107,379,72,126,445,318,255,445,62,52,184,247,245,185}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Able to catch"; verify_case(5, Arg2, ableToCatchAll(Arg0, Arg1)); } void test_case_6() { int Arr0[] = {0,0,0,0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0,0,0,0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Able to catch"; verify_case(6, Arg2, ableToCatchAll(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { CatchTheBeatEasy ___test; ___test.run_test(-1); } // END CUT HERE
#ifndef NAVIGATIONWIDGET_H #define NAVIGATIONWIDGET_H #include <QtCore> #include <QtGui> #include <QtWidgets> namespace Ui { class navigationWidget; } class navigationWidget : public QWidget { Q_OBJECT public: explicit navigationWidget(QWidget *parent = 0); ~navigationWidget(); void searchNull(); void setNavWidget(QJsonObject dataObj); void setShowSize(int value); void setButtonFixedSize(int size); void setNavWidget2(QJsonObject dataObj); int pageNum(); public Q_SLOTS: int pageSize(); signals: void searchChanged(QString str); void pageChanged(int value); private Q_SLOTS: void onValueChanged(int value); void timerUpdate(); private: Ui::navigationWidget *ui; void initWidget(); QTimer *mTimer; }; #endif // NAVIGATIONWIDGET_H
#include<bits/stdc++.h> #define inf 100000000 using namespace std; struct node{ int to,cap,rev; }; vector<node> e[1000]; bool used[1000]; int s=0,t=999,m,n,tot=0,ans; inline void ins(int u,int v,int c){ e[u].push_back((node){v,c,e[v].size()}); e[v].push_back((node){u,0,e[u].size()-1}); } void readit(){ scanf("%d%d",&m,&n); for (int i=0;i<m;i++) for (int j=0;j<n;j++){ int u=i*n+j+1,x; scanf("%d",&x); tot+=x; if ((i+j)%2){ if (i>0) ins(u,u-n,inf); if (j>0) ins(u,u-1,inf); if (i<m-1) ins(u,u+n,inf); if (j<n-1) ins(u,u+1,inf); ins(s,u,x); } else ins(u,t,x); } } void writeit(){ printf("%d\n",ans); } int dfs(int v,int t,int f){ if (v==t) return f; used[v]=1; for (int i=0;i<e[v].size();i++){ node &evi=e[v][i]; if (!used[evi.to]&&evi.cap>0){ int c=dfs(evi.to,t,min(f,evi.cap)); if (c>0){ evi.cap-=c; e[evi.to][evi.rev].cap+=c; return c; } } } return 0; } int max_flow(int s,int t){ int flow=0; for (;;){ memset(used,0,sizeof(used)); int f=dfs(s,t,inf); if (f==0) return flow; flow+=f; } } void work(){ ans=tot-max_flow(s,t); } int main(){ readit(); work(); writeit(); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ /** @file romtablemanager.h * * This module provides access to a file that contains a set of named * binary tables, which are stored in the program binary. This is * normally used for devices where Opera is stored in ROM, since using * files there can be cumbersome. * * The module only provides the ability to get a particular table, the * actual administration of the tables is hidden under the covers. */ #ifndef ROMTABLEMANAGER_H #define ROMTABLEMANAGER_H #if (defined ENCODINGS_HAVE_TABLE_DRIVEN && defined ENCODINGS_HAVE_ROM_TABLES) || defined DOXYGEN_DOCUMENTATION # include "modules/encodings/tablemanager/tablemanager.h" /** * ROM based interface for access to named binary data tables. */ class RomTableManager : public TableCacheManager { public: RomTableManager(); virtual ~RomTableManager() {} // Inherited interfaces --- virtual void ConstructL() {} virtual OP_STATUS Load(); virtual OP_STATUS LoadRawTable(int index); virtual BOOL TablesAvailable() { return TRUE; } #ifdef OUT_OF_MEMORY_POLLING virtual void Flush() {} #endif }; /** * Return pointer to the binary image of an encoding.bin file. Must be defined * by platform code. See the documentation in the i18ndata module for * ways to produce one. */ const unsigned int *g_encodingtables(); #endif // ENCODINGS_HAVE_TABLE_DRIVEN && ENCODINGS_HAVE_ROM_TABLES #endif // ROMTABLEMANAGER_H
#include "SieveParRangeFinal.h" std::string SieveParRangeFinal::name() { return "Sieve Algorith, parallel finding of primes in given range final"; } int* SieveParRangeFinal::find(int min, int max, int* size) { int dividersSize = sqrt(max) + 1; int arraySize = max - min; // Initialize array bool* array = new bool[arraySize]; bool* dividers = new bool[dividersSize]; for (int i = 0; i < dividersSize; i++) { dividers[i] = true; } // Filter non-prime dividers for (int i = 2; i < sqrt(dividersSize); i++) { int j = i; while (j + i < dividersSize) { j += i; dividers[j] = false; } } int dividersNumSize = 0; for (int i = 2; i < dividersSize; i++) { if (dividers[i]) { dividersNumSize++; } } int* dividersNum = new int[dividersNumSize]; int k = 0; for (int i = 2; i < dividersSize; i++) { if (dividers[i]) { dividersNum[k++] = i; } } *size = 0; // Filter non-prime numbers #pragma omp parallel { #pragma omp for for (int i = 0; i < arraySize; i++) { array[i] = true; } #pragma omp for schedule(dynamic) for (int i = 0; i < dividersNumSize; i++) { int num = dividersNum[i]; int j = num * ((min - 1) / num); if (j < num) { j += num; } while (j + num < max) { j += num; int index = j - min; if (array[index]) { array[index] = false; } } } int localSize = 0; #pragma omp for for (int i = 0; i < arraySize; i++) { if (array[i]) { localSize++; } } #pragma omp atomic (*size) += localSize; } // Insert all prime numbers into an array int* result = new int[*size]; int j = 0; for (int i = 0; i < arraySize; i++) { if (array[i]) { result[j++] = min + i; } } // Clean up delete[] array; delete[] dividers; return result; }
// // Created by Данил Козловский on 2019-03-28. // #ifndef INC_2_VEC2I_H #define INC_2_VEC2I_H class Vec2I { public: int x, y; Vec2I(); Vec2I(int x, int y); int getX(); int getY(); void setX(int xG); void setY(int yG); void setTo(Vec2I vec); void setTo(int xG, int yG); void add(Vec2I vec); void add(int n); void add(int xG, int yG); void offset(Vec2I vec); void offset(int n); void offset(int x, int y); void sub(Vec2I vec); void sub(int n); void sub(int xG, int yG); void mul(Vec2I vec); void mul(int n); void mul(int xG, int yG); void div(Vec2I vec); void div(int n); void div(int xG, int yG); Vec2I* copy(); }; #endif //INC_2_VEC2I_H
#include<cstdio> #include<cstring> #define maxn 510 #define inf 1000000000 using namespace std; int lk[maxn]; int lx[maxn],ly[maxn]; bool sx[maxn],sy[maxn]; int w[maxn][maxn]; bool link[maxn][maxn]; int slack[maxn]; int n,m,nx,ny,e; int cs; void input() { int s,r,v; memset(w,0,sizeof(w)); memset(link,0,sizeof(link)); //link 表示是否连通 for(int i=0;i<e;i++) { scanf("%d%d%d",&s,&r,&v); if(v<0) continue; s++; r++; w[s][r]=v; link[s][r]=true; } nx=n; ny=m; } bool dfs(int cur) { int t; sx[cur]=true; for(int i=1;i<=ny;++i) if(!sy[i] && link[cur][i]){ if((t=lx[cur]+ly[i]-w[cur][i])==0){//i在相等子图中 sy[i]=true; if(!lk[i] || dfs(lk[i])){ lk[i]=cur; return true; } }else if(t<slack[i]) slack[i]=t; } return false; } //n<=m 左右分别有nx,ny个 void KM() { memset(lk,0,sizeof(lk)); memset(ly,0,sizeof(ly)); for(int i=1;i<=nx;++i) { lx[i]=-inf; for(int j=1;j<=ny;++j) if(w[i][j]>lx[i]) lx[i]=w[i][j]; } for(int i=1;i<=nx;++i) { for(int j=1;j<=ny;j++) slack[j]=inf; for(int l=1;l<=nx;l++) //最多增加nx条边 { memset(sx,0,sizeof(sx)); memset(sy,0,sizeof(sy)); if(dfs(i)) break; int d=inf; for(int j=1;j<=ny;++j) if(!sy[j] && slack[j]<d) d=slack[j]; for(int j=1;j<=nx;++j) if(sx[j]) lx[j]-=d; for(int j=1;j<=ny;++j){ if(sy[j]) ly[j]+=d; else slack[j]-=d; } } } } void output() { int ans=0,cnt=0; for(int i=1;i<=ny;++i){ if(lk[i]) ans+=w[lk[i]][i],cnt++; } if(cnt!=n) ans=-1; printf("%d\n",ans); } int main() { freopen("hdu2426.in","r",stdin); int cs=0; while(scanf("%d%d%d",&n,&m,&e)!=EOF) { printf("Case %d: ",++cs); input(); if(n<=m && e>0) { KM(); output(); }else printf("-1\n"); } return 0; }
//O(n^2). class Solution { public: int maxSubArray(vector<int>& nums) { int n = nums.size(); int maxsum = 0; for(int i=0;i<n;i++){ int sum = 0; for(int j=i;j<n;j++){ sum = sum + nums[j]; if(sum > maxsum){ maxsum = sum; } } } return maxsum; } }; //O(n). class Solution { public: int maxSubArray(vector<int>& nums) { int n = nums.size(); int maxsum = nums[0]; int sum = 0; for(int i=0;i<n;i++){ sum = sum + nums[i]; if(sum > maxsum){ maxsum = sum; } if(sum < 0){ sum = 0; } } return maxsum; } };
/* * **************************************************************************** * * * * * Copyright 2008, xWorkshop Inc. * * * All rights reserved. * * * Redistribution and use in source and binary forms, with or without * * * modification, are permitted provided that the following conditions are * * * met: * * * * Redistributions of source code must retain the above copyright * * * notice, this list of conditions and the following disclaimer. * * * * Redistributions in binary form must reproduce the above * * * copyright notice, this list of conditions and the following disclaimer * * * in the documentation and/or other materials provided with the * * * distribution. * * * * Neither the name of xWorkshop Inc. nor the names of its * * * contributors may be used to endorse or promote products derived from * * * this software without specific prior written permission. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * * * Author: stoneyrh@163.com * * * * * **************************************************************************** */ #include <gtest/gtest.h> #include "xbyte_array.hxx" using namespace xws; TEST(xbyte_array_tests, test_initialization_without_data) { xbyte_array byte_array; EXPECT_TRUE(byte_array.is_empty()); EXPECT_EQ(byte_array.size(), 0); } TEST(xbyte_array_tests, test_initialization_with_raw_data) { xbyte bytes[] = "1234567890"; std::size_t size = strlen((char*)bytes) * sizeof(xbyte); xbyte_array byte_array(bytes, size); EXPECT_FALSE(byte_array.is_empty()); EXPECT_EQ(byte_array.size(), size); EXPECT_TRUE(memcmp(bytes, byte_array.data(), size) == 0); } TEST(xbyte_array_tests, test_copy_initialization) { xbyte bytes[] = "1234567890"; std::size_t size = strlen((char*)bytes) * sizeof(xbyte); xbyte_array byte_array(bytes, size); xbyte_array cloned(byte_array); EXPECT_EQ(byte_array, cloned); } TEST(xbyte_array_tests, test_function_left) { xbyte bytes[] = "1234567890"; std::size_t size = strlen((char*)bytes) * sizeof(xbyte); xbyte_array byte_array(bytes, size); xbyte_array left_3_bytes = byte_array.left(3); EXPECT_EQ(left_3_bytes.size(), 3); EXPECT_TRUE(memcmp(left_3_bytes.data(), "123", 3) == 0); xbyte_array equal_to_origin = byte_array.left(size); EXPECT_EQ(byte_array, equal_to_origin); xbyte_array a_new_copy = byte_array.left(size * 2); EXPECT_EQ(a_new_copy, byte_array); } TEST(xbyte_array_tests, test_function_right) { xbyte bytes[] = "1234567890"; std::size_t size = strlen((char*)bytes) * sizeof(xbyte); xbyte_array byte_array(bytes, size); xbyte_array right_3_bytes = byte_array.right(3); EXPECT_EQ(right_3_bytes.size(), 3); EXPECT_TRUE(memcmp(right_3_bytes.data(), "890", 3) == 0) << (char*)right_3_bytes.data(); xbyte_array equal_to_origin = byte_array.right(size); EXPECT_EQ(equal_to_origin, byte_array); xbyte_array a_new_copy = byte_array.right(size * 2); EXPECT_EQ(a_new_copy, byte_array); } TEST(xbyte_array_tests, test_conjunction) { xbyte bytes[] = "1234567890"; std::size_t size = strlen((char*)bytes) * sizeof(xbyte); xbyte_array byte_array(bytes, size); xbyte_array left_5 = byte_array.left(5); xbyte_array rest = byte_array.right(size - 5); xbyte_array merged = left_5 + rest; EXPECT_EQ(merged, byte_array); left_5 += rest; EXPECT_EQ(left_5, merged); } TEST(xbyte_array_tests, test_assignment) { xbyte bytes[] = "1234567890"; std::size_t size = strlen((char*)bytes) * sizeof(xbyte); xbyte_array byte_array(bytes, size); xbyte_array array; array = byte_array; EXPECT_EQ(array, byte_array); } TEST(xbyte_array_tests, test_function_append) { xbyte_array byte_array; xint8_t xi8 = -8; xint16_t xi16 = -16; xint32_t xi32 = -32; xint64_t xi64 = -64; xuint8_t xui8 = 8; xuint16_t xui16 = 16; xuint32_t xui32 = 32; xuint64_t xui64 = 64; byte_array.append(xi8); byte_array.append(xi16); byte_array.append(xi32); byte_array.append(xi64); byte_array.append(xui8); byte_array.append(xui16); byte_array.append(xui32); byte_array.append(xui64); // xsize_t offset = 0; ASSERT_EQ(byte_array.value_at<xint8_t>(offset), xi8); offset += sizeof(xint8_t); ASSERT_EQ(byte_array.value_at<xint16_t>(offset), xi16); offset += sizeof(xint16_t); ASSERT_EQ(byte_array.value_at<xint32_t>(offset), xi32); offset += sizeof(xint32_t); ASSERT_EQ(byte_array.value_at<xint64_t>(offset), xi64); offset += sizeof(xint64_t); ASSERT_EQ(byte_array.value_at<xuint8_t>(offset), xui8); offset += sizeof(xuint8_t); ASSERT_EQ(byte_array.value_at<xuint16_t>(offset), xui16); offset += sizeof(xuint16_t); ASSERT_EQ(byte_array.value_at<xuint32_t>(offset), xui32); offset += sizeof(xuint32_t); ASSERT_EQ(byte_array.value_at<xuint64_t>(offset), xui64); offset += sizeof(xuint64_t); std::string ns("123"); std::wstring ws(L"45678"); byte_array.append(ns); byte_array.append(ws); ASSERT_EQ(byte_array.str_at(offset, ns.length()), ns); // Plus 1 to skip the _X('\0') char offset += (ns.length() + 1) * sizeof(char); ASSERT_EQ(byte_array.wstr_at(offset, ws.length()), ws); offset += (ws.length() + 1) * sizeof(wchar_t); xstring xs(_X("abcdefghijklmn")); byte_array.append(xs); ASSERT_EQ(byte_array.xstr_at(offset, xs.length()), xs); offset += (xs.length() + 1) * sizeof(xchar); xbyte_ptr raw = (xbyte_ptr)"khkl;,nko3jfkdsl"; xsize_t size = strlen((char*)raw) * sizeof(xbyte); byte_array.append(raw, size); EXPECT_STREQ((char*)raw, byte_array.str_at(offset, size).c_str()); } TEST(xbyte_array_tests, test_append_empty_string) { xbyte_array byte_array; xstring empty; byte_array.append(empty); ASSERT_EQ(byte_array.size(), sizeof(xchar)); } TEST(xbyte_array_tests, test_invalid_append) { xbyte_array byte_array; xbyte_ptr p = 0; byte_array.append(p, 0); byte_array.append(p, 10); } TEST(xbyte_array_tests, test_function_replace) { xbyte_array byte_array; xint16_t xi16 = -16; byte_array.append(xi16); ASSERT_FALSE(byte_array.replace(2 * sizeof(xi16), &xi16, sizeof(xi16))); ASSERT_FALSE(byte_array.replace(sizeof(xi16), &xi16, sizeof(xi16))); ASSERT_FALSE(byte_array.replace(sizeof(xi16) / 2, &xi16, sizeof(xi16))); ASSERT_FALSE(byte_array.replace(0, 0, 10)); ASSERT_EQ(byte_array.value_at<xint16_t>(0), xi16); xint16_t _xi16 = 16; ASSERT_TRUE(byte_array.replace(0, &_xi16, sizeof(_xi16))); ASSERT_EQ(byte_array.value_at<xint16_t>(0), _xi16); } TEST(xbyte_array_tests, test_function_clear) { xbyte_array byte_array; ASSERT_TRUE(byte_array.is_empty()); xint16_t xi16 = -16; byte_array.append(xi16); ASSERT_FALSE(byte_array.is_empty()); byte_array.clear(); ASSERT_TRUE(byte_array.is_empty()); }
// // GnITabCtrl.h // Core // // Created by Max Yoon on 11. 7. 22.. // Copyright 2011년 __MyCompanyName__. All rights reserved. // #ifndef __Core__GnITabCtrl__ #define __Core__GnITabCtrl__ #include "GnITabPage.h" class GnIButton; class GnITabCtrl : public GnInterfaceGroup { protected: GnInterfaceGroup* mpTabButtons; GnTPrimitiveSet<GnITabPage*> mTabPages; GnSignal2<gtuint, GnITabPage*> mSignal; GnMemberSlot2<GnITabCtrl, GnInterface*, GnIInputEvent*> mTabButtonPushEvent; gtint mNumActiveTab; GnVector2 mDefaultButtonSize; GnTPrimitiveSet< GnBaseSlot2< GnInterface*, GnIInputEvent*>* > mSignalSet; public: static GnITabCtrl* CreateTabCtrl(const gchar* pcBackgroundImage, float fSizeX, float fSizeY); static GnITabCtrl* CreateTabCtrl(float fTabBackgroundSizeX, float fTabBackgroundSizeY , float fTabButtonSizeX, float fTabButtonSizeY); public: void AddTabCreateButtonImage(GnITabPage* pTabPage, const gchar* pcDefaultButtonImage , const gchar* pcClickButtonImage); void SetActiveTab(gtint iNumActive); public: void SetPosition(GnVector2& cPos); void SetRect(float fLeft, float fTop, float fRight, float fBottom); void SubscribeClickedEvent(GnBaseSlot2<GnInterface*, GnIInputEvent*>* pSlot); public: inline gint GetNumActiveTab() { return mNumActiveTab; } inline GnITabPage* GetActiveTabPage() { if( mNumActiveTab != -1 ) return mTabPages.GetAt( (gtuint)mNumActiveTab ); return NULL; } inline GnITabPage* GetTabPage(gtuint uiIndex) { if( mTabPages.GetSize() < uiIndex ) return NULL; return mTabPages.GetAt( uiIndex ); } protected: GnVector2 GetStartTabButtonPosition(); void SetTabButtonPosition(GnVector2 cStartPos); void PushTabButton(GnInterface* pInterface, GnIInputEvent* pEvent); protected: GnITabCtrl(Gn2DMeshObject* pcBackgroundMesh); }; #endif
// Copyright (c) 2020 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _OpenGl_TextureSetPairIterator_Header #define _OpenGl_TextureSetPairIterator_Header #include <OpenGl_TextureSet.hxx> //! Class for iterating pair of texture sets through each defined texture slot. //! Note that iterator considers texture slots being in ascending order within OpenGl_TextureSet. class OpenGl_TextureSetPairIterator { public: //! Constructor. OpenGl_TextureSetPairIterator (const Handle(OpenGl_TextureSet)& theSet1, const Handle(OpenGl_TextureSet)& theSet2) : myIter1 (theSet1), myIter2 (theSet2), myTexture1 (NULL), myTexture2 (NULL), myUnitLower (IntegerLast()), myUnitUpper (IntegerFirst()), myUnitCurrent (0) { if (!theSet1.IsNull() && !theSet1->IsEmpty()) { myUnitLower = Min (myUnitLower, theSet1->FirstUnit()); myUnitUpper = Max (myUnitUpper, theSet1->LastUnit()); } if (!theSet2.IsNull() && !theSet2->IsEmpty()) { myUnitLower = Min (myUnitLower, theSet2->FirstUnit()); myUnitUpper = Max (myUnitUpper, theSet2->LastUnit()); } myUnitCurrent = myUnitLower; myTexture1 = (myIter1.More() && myIter1.Unit() == myUnitCurrent) ? myIter1.ChangeValue().get() : NULL; myTexture2 = (myIter2.More() && myIter2.Unit() == myUnitCurrent) ? myIter2.ChangeValue().get() : NULL; } //! Return TRUE if there are more texture units to pass through. bool More() const { return myUnitCurrent <= myUnitUpper; } //! Return current texture unit. Graphic3d_TextureUnit Unit() const { return (Graphic3d_TextureUnit )myUnitCurrent; } //! Access texture from first texture set. const OpenGl_Texture* Texture1() const { return myTexture1; } //! Access texture from second texture set. const OpenGl_Texture* Texture2() const { return myTexture2; } //! Move iterator position to the next pair. void Next() { ++myUnitCurrent; myTexture1 = myTexture2 = NULL; for (; myIter1.More(); myIter1.Next()) { if (myIter1.Unit() >= myUnitCurrent) { myTexture1 = myIter1.Unit() == myUnitCurrent ? myIter1.ChangeValue().get() : NULL; break; } } for (; myIter2.More(); myIter2.Next()) { if (myIter2.Unit() >= myUnitCurrent) { myTexture2 = myIter2.Unit() == myUnitCurrent ? myIter2.ChangeValue().get() : NULL; break; } } } private: OpenGl_TextureSet::Iterator myIter1; OpenGl_TextureSet::Iterator myIter2; OpenGl_Texture* myTexture1; OpenGl_Texture* myTexture2; Standard_Integer myUnitLower; Standard_Integer myUnitUpper; Standard_Integer myUnitCurrent; }; #endif //_OpenGl_TextureSetPairIterator_Header
/* //TODO: Comment */ #include "SetupGUI.h" #include <CommCtrl.h> #include <Strsafe.h> #include <string> #define MONITOR_BORDER_WIDTH 4 #define FILENAME_ARROW L"\\Arrow.bmp" #define FILENAME_LED L"\\LED.bmp" #define BMP_LED_DISPLAY_WIDTH 20 #define BMP_LED_DISPLAY_HEIGHT 20 #define BMP_ARROW_DISPLAY_HEIGHT 20 #define BMP_ARROW_DISPLAY_WIDTH 20 #define ARROW_MARGIN 20 /* Overloaded constructor. @param selectedMonitors: A reference to a vector containing all currently selected monitors. */ SetupGUI::SetupGUI(CONST std::vector<Monitor>& selectedMonitors) : m_selectedMonitors(selectedMonitors) { } /* Draws the gui. @param hWndParent: A handle to the parent window. @param x: The horizontal position of the GUI. @param y: The vertical position of the GUI. @param width: The width of the GUI. @parwam height: The height of the GUI. */ VOID SetupGUI::Draw(CONST HWND hWndParent, CONST UINT x, CONST UINT y, CONST UINT width, CONST UINT height) { HDC hdc = GetDC(hWndParent); RECT clientRect; GetClientRect(hWndParent, &clientRect); HDC hdcMem = CreateCompatibleDC(hdc); HBITMAP hBmp = CreateCompatibleBitmap(hdc, width, height); SelectObject(hdcMem, hBmp); //Fill the DC with white colour HBRUSH hBrush = CreateSolidBrush(RGB(255, 255, 255)); RECT memRect = { 0, 0, width, height }; FillRect(hdcMem, &memRect, hBrush); DeleteObject(hBrush); //Find out the maximal x and y position of the monitors UINT xMax = 0, yMax = 0; for (UINT i = 0; i < m_selectedMonitors.size(); i++) { xMax = (m_selectedMonitors.at(i).GetPosX() > xMax) ? m_selectedMonitors.at(i).GetPosX() : xMax; yMax = (m_selectedMonitors.at(i).GetPosY() > yMax) ? m_selectedMonitors.at(i).GetPosY() : yMax; } //Add one for easier calculations xMax++; yMax++; UINT monitorWidth = width / xMax; UINT monitorHeight = height / yMax; for (UINT i = 0; i < m_selectedMonitors.size(); i++) { DrawMonitor(hdcMem, m_selectedMonitors.at(i), monitorWidth * m_selectedMonitors.at(i).GetPosX(), monitorHeight * m_selectedMonitors.at(i).GetPosY(), monitorWidth, monitorHeight); } BitBlt(hdc, x, y, width, height, hdcMem, 0, 0, SRCCOPY); DeleteDC(hdcMem); DeleteObject(hBmp); ReleaseDC(hWndParent, hdc); } /* Draws a monitor in the GUI. @param hdc: The hdc object of the GUI. @param monitor: A reference to the monitor to be drawn. @param x: The horizontal position to draw the monitor at. @param y: The vertical position to draw the monitor at. @param width: The drawing width of the monitor. @param height: The drawing height of the monitor. */ VOID SetupGUI::DrawMonitor(CONST HDC hdc, CONST Monitor& monitor, CONST UINT x, CONST UINT y, CONST UINT width, CONST UINT height) { HBRUSH hBrush = CreateSolidBrush(RGB(0, 0, 0)); SelectObject(hdc, hBrush); //Draw the monitor edges Rectangle(hdc, x, y, x + MONITOR_BORDER_WIDTH, y + height); //Left edge Rectangle(hdc, x, y, x + width, y + MONITOR_BORDER_WIDTH); //Top edge Rectangle(hdc, x, y + height - MONITOR_BORDER_WIDTH, x + width, y + height); //Bottom edge Rectangle(hdc, x + width - MONITOR_BORDER_WIDTH, y, x + width, y + height); //Right edge HBITMAP hBmpArrow = LoadBMPFromCD(FILENAME_ARROW); if (hBmpArrow == NULL) { //TODO: Throw exception } HDC hdcBmpArrow = CreateCompatibleDC(hdc); SelectObject(hdcBmpArrow, hBmpArrow); BITMAP bmpArrow; GetObject(hBmpArrow, sizeof(BITMAP), &bmpArrow); HBITMAP hBmpLED = LoadBMPFromCD(FILENAME_LED); if (hBmpLED == NULL) { //TODO: Throw exception } HDC hdcBmpLED = CreateCompatibleDC(hdc); SelectObject(hdcBmpLED, hBmpLED); BITMAP bmpLED; GetObject(hBmpLED, sizeof(BITMAP), &bmpLED); POINT rotPt[3]; //LEFT side for (UINT i = 0; i < monitor.GetLeftLeds(); i++) { StretchBlt(hdc, x, y + (monitor.GetLeftLeds() == 1 ? height / 2 : i * height / (monitor.GetLeftLeds() - 1) - BMP_LED_DISPLAY_HEIGHT / 2), BMP_LED_DISPLAY_WIDTH, BMP_LED_DISPLAY_HEIGHT, hdcBmpLED, 0, 0, bmpLED.bmWidth, bmpLED.bmHeight, SRCCOPY); } if (monitor.GetLeftLeds()) { //Print the left monitor side position std::wstring strLeftPos = std::to_wstring(monitor.GetPosLeft()); TextOut(hdc, x, y + height / 2, strLeftPos.c_str(), strLeftPos.length()); if (monitor.GetClockwiseLeft()) { rotPt[0] = { LONG(x + ARROW_MARGIN), LONG(y + height / 2 + BMP_ARROW_DISPLAY_HEIGHT / 2) }; rotPt[1] = { LONG(x + ARROW_MARGIN), LONG(y + height / 2 - BMP_ARROW_DISPLAY_HEIGHT / 2) }; rotPt[2] = { LONG(x + ARROW_MARGIN + BMP_ARROW_DISPLAY_HEIGHT), LONG(y + height / 2 + BMP_ARROW_DISPLAY_HEIGHT / 2) }; } else { rotPt[0] = { LONG(x + ARROW_MARGIN + BMP_ARROW_DISPLAY_HEIGHT), LONG(y + height / 2 - BMP_ARROW_DISPLAY_HEIGHT / 2) }; rotPt[1] = { LONG(x + ARROW_MARGIN + BMP_ARROW_DISPLAY_HEIGHT), LONG(y + height / 2 + BMP_ARROW_DISPLAY_HEIGHT / 2) }; rotPt[2] = { LONG(x + ARROW_MARGIN), LONG(y + height / 2 - BMP_ARROW_DISPLAY_HEIGHT / 2) }; } PlgBlt(hdc, rotPt, hdcBmpArrow, 0, 0, bmpArrow.bmWidth, bmpArrow.bmHeight, NULL, NULL, NULL); } //RIGHT side for (UINT i = 0; i < monitor.GetRightLeds(); i++) { StretchBlt(hdc, x + width - BMP_LED_DISPLAY_WIDTH, y + (monitor.GetRightLeds() == 1 ? height / 2 : i * height / (monitor.GetRightLeds() - 1) - BMP_LED_DISPLAY_HEIGHT / 2), BMP_LED_DISPLAY_WIDTH, BMP_LED_DISPLAY_HEIGHT, hdcBmpLED, 0, 0, bmpLED.bmWidth, bmpLED.bmHeight, SRCCOPY); } if (monitor.GetRightLeds()) { //Print the right monitor side position std::wstring strRightPos = std::to_wstring(monitor.GetPosRight()); TextOut(hdc, x + width, y + height / 2, strRightPos.c_str(), strRightPos.length()); if (monitor.GetClockwiseRight()) { rotPt[0] = { LONG(x + width - ARROW_MARGIN), LONG(y + height / 2 - BMP_ARROW_DISPLAY_HEIGHT / 2) }; rotPt[1] = { LONG(x + width - ARROW_MARGIN), LONG(y + height / 2 + BMP_ARROW_DISPLAY_HEIGHT / 2) }; rotPt[2] = { LONG(x + width - ARROW_MARGIN - BMP_ARROW_DISPLAY_WIDTH), LONG(y + height / 2 - BMP_ARROW_DISPLAY_HEIGHT / 2) }; } else { rotPt[0] = { LONG(x + width - BMP_ARROW_DISPLAY_HEIGHT - ARROW_MARGIN), LONG(y + height / 2 + BMP_ARROW_DISPLAY_HEIGHT / 2) }; rotPt[1] = { LONG(x + width - BMP_ARROW_DISPLAY_HEIGHT - ARROW_MARGIN), LONG(y + height / 2 - BMP_ARROW_DISPLAY_HEIGHT / 2) }; rotPt[2] = { LONG(x + width - ARROW_MARGIN), LONG(y + height / 2 + BMP_ARROW_DISPLAY_HEIGHT / 2) }; } PlgBlt(hdc, rotPt, hdcBmpArrow, 0, 0, bmpArrow.bmWidth, bmpArrow.bmHeight, NULL, NULL, NULL); } //TOP side for (UINT i = 0; i < monitor.GetTopLeds(); i++) { StretchBlt(hdc, x + (monitor.GetTopLeds() == 1 ? width / 2 : i * width / (monitor.GetTopLeds() - 1)) - BMP_LED_DISPLAY_WIDTH / 2, y, BMP_LED_DISPLAY_WIDTH, BMP_LED_DISPLAY_HEIGHT, hdcBmpLED, 0, 0, bmpLED.bmWidth, bmpLED.bmHeight, SRCCOPY); } if (monitor.GetTopLeds()) { //Print the top monitor side position std::wstring strTopPos = std::to_wstring(monitor.GetPosTop()); TextOut(hdc, x + width / 2, y, strTopPos.c_str(), strTopPos.length()); if (monitor.GetClockwiseTop()) { rotPt[0] = { LONG(x + width / 2 - BMP_ARROW_DISPLAY_WIDTH / 2), LONG(y + ARROW_MARGIN)}; rotPt[1] = { LONG(x + width / 2 + BMP_ARROW_DISPLAY_WIDTH / 2), LONG(y + ARROW_MARGIN)}; rotPt[2] = { LONG(x + width / 2 - BMP_ARROW_DISPLAY_WIDTH / 2), LONG(y + ARROW_MARGIN + BMP_ARROW_DISPLAY_HEIGHT) }; } else { rotPt[0] = { LONG(x + width / 2 + BMP_ARROW_DISPLAY_WIDTH / 2), LONG(y + ARROW_MARGIN + BMP_LED_DISPLAY_HEIGHT) }; rotPt[1] = { LONG(x + width / 2 - BMP_ARROW_DISPLAY_WIDTH / 2), LONG(y + ARROW_MARGIN + BMP_LED_DISPLAY_HEIGHT) }; rotPt[2] = { LONG(x + width / 2 + BMP_ARROW_DISPLAY_WIDTH / 2), LONG(y + ARROW_MARGIN) }; } PlgBlt(hdc, rotPt, hdcBmpArrow, 0, 0, bmpArrow.bmWidth, bmpArrow.bmHeight, NULL, NULL, NULL); } //BOTTOM side for (UINT i = 0; i < monitor.GetBottomLeds(); i++) { StretchBlt(hdc, x + (monitor.GetBottomLeds() == 1 ? width / 2 : i * width / (monitor.GetBottomLeds() - 1)) - BMP_LED_DISPLAY_WIDTH / 2, y + height - BMP_LED_DISPLAY_HEIGHT, BMP_LED_DISPLAY_WIDTH, BMP_LED_DISPLAY_HEIGHT, hdcBmpLED, 0, 0, bmpLED.bmWidth, bmpLED.bmHeight, SRCCOPY); } if (monitor.GetBottomLeds()) { //Print the bottom monitor side position std::wstring strBotPos = std::to_wstring(monitor.GetPosBottom()); TEXTMETRIC txtMetric; GetTextMetrics(hdc, &txtMetric); TextOut(hdc, x + width / 2, y + height - txtMetric.tmHeight, strBotPos.c_str(), strBotPos.length()); if (monitor.GetClockwiseBottom()) { rotPt[0] = { LONG(x + width / 2 + BMP_ARROW_DISPLAY_WIDTH / 2), LONG(y + height - ARROW_MARGIN) }; rotPt[1] = { LONG(x + width / 2 - BMP_ARROW_DISPLAY_WIDTH / 2), LONG(y + height - ARROW_MARGIN) }; rotPt[2] = { LONG(x + width / 2 + BMP_ARROW_DISPLAY_WIDTH / 2), LONG(y + height - ARROW_MARGIN - BMP_ARROW_DISPLAY_HEIGHT) }; } else { rotPt[0] = { LONG(x + width / 2 - BMP_ARROW_DISPLAY_WIDTH / 2), LONG(y + height - ARROW_MARGIN - BMP_ARROW_DISPLAY_HEIGHT) }; rotPt[1] = { LONG(x + width / 2 + BMP_ARROW_DISPLAY_WIDTH / 2), LONG(y + height - ARROW_MARGIN - BMP_ARROW_DISPLAY_HEIGHT) }; rotPt[2] = { LONG(x + width / 2 - BMP_ARROW_DISPLAY_WIDTH / 2), LONG(y + height - ARROW_MARGIN) }; } PlgBlt(hdc, rotPt, hdcBmpArrow, 0, 0, bmpArrow.bmWidth, bmpArrow.bmHeight, NULL, NULL, NULL); } DeleteDC(hdcBmpArrow); DeleteObject(hBmpArrow); DeleteDC(hdcBmpLED); DeleteObject(hBmpLED); DeleteObject(hBrush); CONST auto MONITORNAME_MARGIN_X = 30, MONITORNAME_MARGIN_Y = 20; RECT monitorRect; monitorRect.left = x + MONITORNAME_MARGIN_X; monitorRect.right = x + width - MONITORNAME_MARGIN_X; monitorRect.top = y + MONITORNAME_MARGIN_Y; monitorRect.bottom = y + height - MONITORNAME_MARGIN_Y; DrawText(hdc, monitor.GetMonitorName().c_str(), lstrlen(monitor.GetMonitorName().c_str()), &monitorRect, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_WORD_ELLIPSIS); } /* Loads a bitmap from the current directory. @param fileName: The filename of the bitmap file. */ CONST HBITMAP SetupGUI::LoadBMPFromCD(CONST LPCWSTR fileName) { WCHAR buffer[MAX_PATH]; GetCurrentDirectory(MAX_PATH, buffer); if (StringCchCat(buffer, MAX_PATH, fileName) != S_OK) { throw L"Exception in function LoadBMPFromCD. Error: Failed to concatenate file path strings."; } return (HBITMAP)LoadImage(NULL, buffer, IMAGE_BITMAP, NULL, NULL, LR_LOADFROMFILE); }
#pragma once #include "IEngineTrace.h" class IMaterial; class KeyValues; struct vcollide_t; struct model_t; struct cplane_t; struct studiohdr_t; struct virtualmodel_t; typedef unsigned char byte; struct virtualterrainparams_t; class CPhysCollide; typedef unsigned short MDLHandle_t; class CUtlBuffer; class IModelLoadCallback { public: virtual void OnModelLoadComplete(const model_t *pModel) = 0; }; class IVModelInfo { public: virtual ~IVModelInfo(void) = 0; virtual const model_t *GetModel(int modelindex) = 0; virtual int GetModelIndex(const char *name) const = 0; virtual const char *GetModelName(const model_t *model) const = 0; virtual vcollide_t *GetVCollide(const model_t *model) = 0; virtual vcollide_t *GetVCollide(int modelindex) = 0; virtual void GetModelBounds(const model_t *model, Vector &mins, Vector &maxs) const = 0; virtual void GetModelRenderBounds(const model_t *model, Vector &mins, Vector &maxs) const = 0; virtual int GetModelFrameCount(const model_t *model) const = 0; virtual int GetModelType(const model_t *model) const = 0; virtual void *GetModelExtraData(const model_t *model) = 0; virtual bool ModelHasMaterialProxy(const model_t *model) const = 0; virtual bool IsTranslucent(model_t const *model) const = 0; virtual bool IsTranslucentTwoPass(const model_t *model) const = 0; virtual void RecomputeTranslucency(const model_t *model, int nSkin, int nBody, void *pClientRenderable, float fInstanceAlphaModulate = 1.0f) = 0; virtual int GetModelMaterialCount(const model_t *model) const = 0; virtual void GetModelMaterials(const model_t *model, int count, IMaterial **ppMaterial) = 0; virtual bool IsModelVertexLit(const model_t *model) const = 0; virtual const char *GetModelKeyValueText(const model_t *model) = 0; virtual bool GetModelKeyValue(const model_t *model, CUtlBuffer &buf) = 0; virtual float GetModelRadius(const model_t *model) = 0; virtual const studiohdr_t *FindModel(const studiohdr_t *pStudioHdr, void **cache, const char *modelname) const = 0; virtual const studiohdr_t *FindModel(void *cache) const = 0; virtual virtualmodel_t *GetVirtualModel(const studiohdr_t *pStudioHdr) const = 0; virtual byte *GetAnimBlock(const studiohdr_t *pStudioHdr, int iBlock) const = 0; virtual void GetModelMaterialColorAndLighting(const model_t *model, Vector const &origin, QAngle const &angles, trace_t *pTrace, Vector &lighting, Vector &matColor) = 0; virtual void GetIlluminationPoint(const model_t *model, IClientRenderable *pRenderable, Vector const &origin, QAngle const &angles, Vector *pLightingCenter) = 0; virtual int GetModelContents(int modelIndex) = 0; virtual studiohdr_t *GetStudiomodel(const model_t *mod) = 0; virtual int GetModelSpriteWidth(const model_t *model) const = 0; virtual int GetModelSpriteHeight(const model_t *model) const = 0; virtual void SetLevelScreenFadeRange(float flMinSize, float flMaxSize) = 0; virtual void GetLevelScreenFadeRange(float *pMinArea, float *pMaxArea) const = 0; virtual void SetViewScreenFadeRange(float flMinSize, float flMaxSize) = 0; virtual unsigned char ComputeLevelScreenFade(const Vector &vecAbsOrigin, float flRadius, float flFadeScale) const = 0; virtual unsigned char ComputeViewScreenFade(const Vector &vecAbsOrigin, float flRadius, float flFadeScale) const = 0; virtual int GetAutoplayList(const studiohdr_t *pStudioHdr, unsigned short **pAutoplayList) const = 0; virtual CPhysCollide *GetCollideForVirtualTerrain(int index) = 0; virtual bool IsUsingFBTexture(const model_t *model, int nSkin, int nBody, void *pClientRenderable) const = 0; virtual const model_t *FindOrLoadModel(const char *name) = 0; virtual void InitDynamicModels() = 0; virtual void ShutdownDynamicModels() = 0; virtual void AddDynamicModel(const char *name, int nModelIndex = -1) = 0; virtual void ReferenceModel(int modelindex) = 0; virtual void UnreferenceModel(int modelindex) = 0; virtual void CleanupDynamicModels(bool bForce = false) = 0; virtual MDLHandle_t GetCacheHandle(const model_t *model) const = 0; virtual int GetBrushModelPlaneCount(const model_t *model) const = 0; virtual void GetBrushModelPlane(const model_t *model, int nIndex, cplane_t &plane, Vector *pOrigin) const = 0; virtual int GetSurfacepropsForVirtualTerrain(int index) = 0; virtual void OnLevelChange() = 0; virtual int GetModelClientSideIndex(const char *name) const = 0; virtual int RegisterDynamicModel(const char *name, bool bClientSide) = 0; virtual bool IsDynamicModelLoading(int modelIndex) = 0; virtual void AddRefDynamicModel(int modelIndex) = 0; virtual void ReleaseDynamicModel(int modelIndex) = 0; virtual bool RegisterModelLoadCallback(int modelindex, IModelLoadCallback *pCallback, bool bCallImmediatelyIfLoaded = true) = 0; virtual void UnregisterModelLoadCallback(int modelindex, IModelLoadCallback *pCallback) = 0; }; namespace I { inline IVModelInfo *ModelInfo; }
#ifndef rqt_system_control_h #define rqt_system_control_h #include <rqt_gui_cpp/plugin.h> #include <ui_rqt_system_control.h> #include <QWidget> namespace rqt_system_control { class SystemControlPlugin : public rqt_gui_cpp::Plugin { Q_OBJECT public: SystemControlPlugin(); virtual void initPlugin(qt_gui_cpp::PluginContext& context); virtual void shutdownPlugin(); virtual void saveSettings(qt_gui_cpp::Settings& plugin_settings, qt_gui_cpp::Settings& instance_settings) const; virtual void restoreSettings(const qt_gui_cpp::Settings& plugin_settings, const qt_gui_cpp::Settings& instance_settings); // Comment in to signal that the plugin has a way to configure it //bool hasConfiguration() const; //void triggerConfiguration(); private: Ui::SystemControlPluginWidget ui_; QWidget* widget_; }; } // namespace #endif // rqt_system_control
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> using namespace std; int main(void) { int Temp1, Temp2; int Result[4] = { 0 }; int TempRes = 0; for (int i = 0; i < 4; i++) { scanf("%d%d",&Temp1, &Temp2); TempRes += (Temp2 - Temp1); Result[i] = TempRes; } sort(Result, Result+4); printf("%d\n", Result[3]); return 0; }
// addrspace.cc // Routines to manage address spaces (executing user programs). // // In order to run a user program, you must: // // 1. link with the -N -T 0 option // 2. run coff2noff to convert the object file to Nachos format // (Nachos object code format is essentially just a simpler // version of the UNIX executable object code format) // 3. load the NOFF file into the Nachos file system // (if you haven't implemented the file system yet, you // don't need to do this last step) // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "addrspace.h" #include "copyright.h" #include "system.h" #ifdef HOST_SPARC #include <strings.h> #endif //---------------------------------------------------------------------- // SwapHeader // Do little endian to big endian conversion on the bytes in the // object file header, in case the file was generated on a little // endian machine, and we're now running on a big endian machine. //---------------------------------------------------------------------- //extern MemoryManager *memoryManager; static void SwapHeader (NoffHeader *noffH) { noffH->noffMagic = WordToHost(noffH->noffMagic); noffH->code.size = WordToHost(noffH->code.size); noffH->code.virtualAddr = WordToHost(noffH->code.virtualAddr); noffH->code.inFileAddr = WordToHost(noffH->code.inFileAddr); noffH->initData.size = WordToHost(noffH->initData.size); noffH->initData.virtualAddr = WordToHost(noffH->initData.virtualAddr); noffH->initData.inFileAddr = WordToHost(noffH->initData.inFileAddr); noffH->uninitData.size = WordToHost(noffH->uninitData.size); noffH->uninitData.virtualAddr = WordToHost(noffH->uninitData.virtualAddr); noffH->uninitData.inFileAddr = WordToHost(noffH->uninitData.inFileAddr); } //---------------------------------------------------------------------- // AddrSpace::AddrSpace // Create an address space to run a user program. // Load the program from a file "executable", and set everything // up so that we can start executing user instructions. // // Assumes that the object code file is in NOFF format. // // First, set up the translation from program memory to physical // memory. For now, this is really simple (1:1), since we are // only uniprogramming, and we have a single unsegmented page table // // "executable" is the file containing the object code to load into memory //---------------------------------------------------------------------- AddrSpace::AddrSpace() { //dummy constructor, its job is replace by Initialize } int AddrSpace::Initialize(OpenFile *executable){ backingStore = new BackingStore(this); RandomInit(888); // NoffHeader noffH; unsigned int i, size; this->executableFile = executable; executableFile->ReadAt((char *)&noffH, sizeof(noffH), 0); if ((noffH.noffMagic != NOFFMAGIC) && (WordToHost(noffH.noffMagic) == NOFFMAGIC)) SwapHeader(&noffH); ASSERT(noffH.noffMagic == NOFFMAGIC); // how big is address space? size = noffH.code.size + noffH.initData.size + noffH.uninitData.size + UserStackSize; // we need to increase the size // to leave room for the stack numPages = divRoundUp(size, PageSize); size = numPages * PageSize; // if (numPages > NumPhysPages) { // printf("File is too big to be loaded.\n"); // //return -1; // } // create a pageTable (amount of page entires) for the current process DEBUG('4',"Initializing address space, Program size %d, Virtual pages %d, Physical pages %d\n", size, numPages, NumPhysPages); //ASSERT(numPages <= NumPhysPages) // check we're not trying // to run anything too big -- // at least until we have // virtual memory // first, set up the translation pageTable = new TranslationEntry[numPages]; for (i = 0; i < numPages; i++) { pageTable[i].virtualPage = i; //pageTable[i].physicalPage = 0;// assign a free physical page // zero out the entire address space, to zero the unitialized data segment // and the stack segment // zero the allocted page // ASSERT(pageTable[i].physicalPage >= 0); // bzero(&machine->mainMemory[pageTable[i].physicalPage * PageSize], PageSize); pageTable[i].valid = FALSE; pageTable[i].use = FALSE; pageTable[i].dirty = FALSE; pageTable[i].readOnly = FALSE; // if the code segment was entirely on // a separate page, we could set its // pages to be read-only pageTable[i].isStore = FALSE; } return 1; } bool AddrSpace::HandlePageFault(OpenFile *executable, int badvpn) { int codePageNum, codeVirtAddr, codeFileOffset, codeSize; int dataPageNum, dataVirtAddr, dataFileOffset, dataSize; int n = memoryManager->AllocPage(); if(n == -1) { printf("Couldn't find free physical page. Going to evict.\n"); return false; } else { //allocate physical address pageTable[badvpn].physicalPage = n; printf("Faulted virtual page %d now points to physical page %d\n",badvpn,n); } if(!pageTable[badvpn].isStore){ codePageNum = (noffH.code.virtualAddr + noffH.code.size)/PageSize; dataPageNum = (noffH.initData.virtualAddr + noffH.initData.size)/PageSize; // load code if(codePageNum >= badvpn && noffH.code.size > 0){ if (noffH.code.virtualAddr/PageSize == badvpn){ codeVirtAddr = noffH.code.virtualAddr; codeSize = PageSize - noffH.code.virtualAddr % PageSize; codeFileOffset = noffH.code.inFileAddr; executable->ReadAt(&(machine->mainMemory[Translate(codeVirtAddr)]), codeSize, codeFileOffset); } else if (codePageNum > badvpn){ codeFileOffset = noffH.code.inFileAddr + PageSize * badvpn - noffH.code.virtualAddr; codeVirtAddr = PageSize * badvpn ; codeSize = PageSize; executable->ReadAt(&(machine->mainMemory[Translate(codeVirtAddr)]), codeSize, codeFileOffset); } else if (codePageNum == badvpn){ codeFileOffset = noffH.code.inFileAddr + PageSize * badvpn - noffH.code.virtualAddr; codeVirtAddr = PageSize * badvpn ; codeSize = (noffH.code.virtualAddr + noffH.code.size) % PageSize; executable->ReadAt(&(machine->mainMemory[Translate(codeVirtAddr)]), codeSize, codeFileOffset); bzero(&(machine->mainMemory[pageTable[badvpn].physicalPage*PageSize + codeSize]), sizeof(PageSize-codeSize)); } } // load data if((dataPageNum >= badvpn) && (badvpn >= codePageNum) && (noffH.initData.size > 0) ){ if (noffH.initData.virtualAddr/PageSize == badvpn){ dataVirtAddr = noffH.initData.virtualAddr; dataSize = PageSize - noffH.initData.virtualAddr % PageSize; dataFileOffset = noffH.initData.inFileAddr; executable->ReadAt(&(machine->mainMemory[Translate(dataVirtAddr)]), dataSize, dataFileOffset); } else if (dataPageNum > badvpn){ dataFileOffset = noffH.initData.inFileAddr + PageSize * badvpn - noffH.initData.virtualAddr; dataVirtAddr = PageSize * badvpn ; dataSize = PageSize; executable->ReadAt(&(machine->mainMemory[Translate(dataVirtAddr)]), dataSize, dataFileOffset); } else if (dataPageNum == badvpn){ dataFileOffset = noffH.initData.inFileAddr + PageSize * badvpn - noffH.initData.virtualAddr; dataVirtAddr = PageSize * badvpn ; dataSize = (noffH.initData.virtualAddr + noffH.initData.size) % PageSize; executable->ReadAt(&(machine->mainMemory[Translate(dataVirtAddr)]), dataSize, dataFileOffset); bzero(&(machine->mainMemory[pageTable[badvpn].physicalPage*PageSize + dataSize]), sizeof(PageSize-dataSize)); } } if (dataPageNum < badvpn) bzero(&(machine->mainMemory[pageTable[badvpn].physicalPage*PageSize]), sizeof(PageSize)); } else { backingStore->PageIn(&pageTable[badvpn]); } return true; } ///////////////////////////////////////////////////////////////////////////////// void AddrSpace::setBit(int vpn){ pageTable[vpn].valid = TRUE; } void AddrSpace::Evict(){ //printf("Evict has been called\n"); int i=0; while(!pageTable[i].valid) { //evictPhysPage = Rand(); i++; } //printf("%d",pageTable.size()); pageTable[i].valid = FALSE; TranslationEntry *pte = &pageTable[i]; if(pageTable[i].dirty) { // printf("PTE to Evict is : %d\n", pte); backingStore->PageOut(pte); pageTable[i].dirty = FALSE; pageTable[i].isStore = TRUE; } memoryManager->FreePage(pageTable[i].physicalPage); } //////////////////////////////////////////////////////////////////////////// int AddrSpace::Translate(int addr){ int phypage = addr / PageSize; int offset = addr % PageSize; int phyaddr = pageTable[phypage].physicalPage * PageSize + offset; return phyaddr; } int AddrSpace::getPteIndex(TranslationEntry *pte) { // printf("numPages is : %d\n", numPages); for (unsigned int i = 0;i < numPages; i++) { if(pte == &pageTable[i]) return i; } return -1; } //////////////////////////////////////////////////////////////////////////// // void AddrSpace::ReadIntoMem(OpenFile *exec, int addr, int size, int infile){ // unsigned int phyaddr; // while (size>PageSize) { // Translate(addr); // // DEBUG('c',"Physical addr = 0x%x\n",phyaddr); // exec->ReadAt(&(machine->mainMemory[phyaddr]),PageSize, infile); // size-=PageSize; // addr+=PageSize; // infile+=PageSize; // } // if(size) { // Translate(addr); // // DEBUG('c',"Physical addr = 0x%x\n",phyaddr); // exec->ReadAt(&(machine->mainMemory[phyaddr]), size, infile); // } // } //---------------------------------------------------------------------- // AddrSpace::~AddrSpace // Dealloate an address space. Nothing for now! //---------------------------------------------------------------------- AddrSpace::~AddrSpace() { // fileSystem->Remove(swap_name); for (unsigned int i = 0; i < numPages; i ++) memoryManager->FreePage(pageTable[i].physicalPage); if(pageTable != NULL) delete [] pageTable; delete executableFile; delete backingStore; } //---------------------------------------------------------------------- // AddrSpace::InitRegisters // Set the initial values for the user-level register set. // // We write these directly into the "machine" registers, so // that we can immediately jump to user code. Note that these // will be saved/restored into the currentThread->userRegisters // when this thread is context switched out. //---------------------------------------------------------------------- void AddrSpace::InitRegisters() { int i; for (i = 0; i < NumTotalRegs; i++) machine->WriteRegister(i, 0); // Initial program counter -- must be location of "Start" machine->WriteRegister(PCReg, 0); // Need to also tell MIPS where next instruction is, because // of branch delay possibility machine->WriteRegister(NextPCReg, 4); // Set the stack register to the end of the address space, where we // allocated the stack; but subtract off a bit, to make sure we don't // accidentally reference off the end! machine->WriteRegister(StackReg, numPages * PageSize - 16); DEBUG('a', "Initializing stack register to %d\n", numPages * PageSize - 16); } //---------------------------------------------------------------------- // AddrSpace::SaveState // On a context switch, save any machine state, specific // to this address space, that needs saving. // // For now, nothing! //---------------------------------------------------------------------- void AddrSpace::SaveState() {} //---------------------------------------------------------------------- // AddrSpace::RestoreState // On a context switch, restore the machine state so that // this address space can run. // // For now, tell the machine where to find the page table. //---------------------------------------------------------------------- void AddrSpace::RestoreState() { machine->pageTable = pageTable; machine->pageTableSize = numPages; } // BackingStore class implementation // BackingStore::BackingStore(AddrSpace *as) { int pn; this->space = as; int pid = currentThread->spaceID; BSFile = new FileSystem(true); pn = space->getNumPages(); sprintf (fileName, "%d", pid); BSFile->Create(fileName,pn*PageSize); swap = BSFile->Open(fileName); } void BackingStore::PageOut(TranslationEntry *pte){ printf("PageOut has been called\n"); stats->incrNumPageOuts(); int pageNum; int physAddr; pageNum = space->getPteIndex(pte); //printf("pageout has been called %d\n", stats->numPageOuts); physAddr = space->Translate(pageNum*PageSize); swap->WriteAt(&machine->mainMemory[physAddr], PageSize, pageNum*PageSize); } void BackingStore::PageIn(TranslationEntry *pte){ printf("PageIn has been called\n"); stats->incrNumPageIns(); int pageNum; int physAddr; pageNum = space->getPteIndex(pte); physAddr = space->Translate(pageNum*PageSize); swap->ReadAt(&machine->mainMemory[physAddr], PageSize, pageNum*PageSize); }
// Created on: 2003-06-04 // Created by: Galina KULIKOVA // Copyright (c) 2003-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepDimTol_CommonDatum_HeaderFile #define _StepDimTol_CommonDatum_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepRepr_CompositeShapeAspect.hxx> #include <StepData_Logical.hxx> class StepDimTol_Datum; class TCollection_HAsciiString; class StepRepr_ProductDefinitionShape; class StepDimTol_CommonDatum; DEFINE_STANDARD_HANDLE(StepDimTol_CommonDatum, StepRepr_CompositeShapeAspect) //! Representation of STEP entity CommonDatum class StepDimTol_CommonDatum : public StepRepr_CompositeShapeAspect { public: //! Empty constructor Standard_EXPORT StepDimTol_CommonDatum(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init(const Handle(TCollection_HAsciiString)& theShapeAspect_Name, const Handle(TCollection_HAsciiString)& theShapeAspect_Description, const Handle(StepRepr_ProductDefinitionShape)& theShapeAspect_OfShape, const StepData_Logical theShapeAspect_ProductDefinitional, const Handle(TCollection_HAsciiString)& theDatum_Name, const Handle(TCollection_HAsciiString)& theDatum_Description, const Handle(StepRepr_ProductDefinitionShape)& theDatum_OfShape, const StepData_Logical theDatum_ProductDefinitional, const Handle(TCollection_HAsciiString)& theDatum_Identification); //! Returns data for supertype Datum Standard_EXPORT Handle(StepDimTol_Datum) Datum() const; //! Set data for supertype Datum Standard_EXPORT void SetDatum (const Handle(StepDimTol_Datum)& theDatum); DEFINE_STANDARD_RTTIEXT(StepDimTol_CommonDatum,StepRepr_CompositeShapeAspect) protected: private: Handle(StepDimTol_Datum) myDatum; }; #endif // _StepDimTol_CommonDatum_HeaderFile
#include "Explosion.h" int Explosion::animation = -1; std::vector < std::shared_ptr <Explosion> > Explosion::explosion; sf::SoundBuffer Explosion::soundBuffer; Explosion::Explosion(float x, float y, float scale, float timeScale, int timeDelay) { texture.loadFromFile("Images/explosion/explosion1.png"); sprite.setTexture(texture); sf::Vector2u size = texture.getSize(); sprite.setOrigin(size.x / 2, size.y / 2); sprite.setPosition(x, y); sprite.setScale(scale, scale); animationObject = Animation::addObject(animation, 15 * timeScale); destroyed = false; sound.setBuffer(soundBuffer); sound.setVolume(25); sound.play(); deltaTime = 0; this->timeDelay = timeDelay; } void Explosion::loadAnimation() { soundBuffer.loadFromFile("Sounds/explosion.ogg"); animation = Animation::addAnimation(); Animation::addImage(animation, "Images/explosion/explosion1.png"); Animation::addImage(animation, "Images/explosion/explosion2.png"); Animation::addImage(animation, "Images/explosion/explosion3.png"); Animation::addImage(animation, "Images/explosion/explosion4.png"); Animation::addImage(animation, "Images/explosion/explosion5.png"); Animation::addImage(animation, "Images/explosion/explosion6.png"); Animation::addImage(animation, "Images/explosion/explosion7.png"); Animation::addImage(animation, "Images/explosion/explosion8.png"); Animation::addImage(animation, "Images/explosion/explosion9.png"); Animation::addImage(animation, "Images/explosion/explosion10.png"); Animation::addImage(animation, "Images/explosion/explosion11.png"); Animation::addImage(animation, "Images/explosion/explosion12.png"); Animation::addImage(animation, "Images/explosion/explosion13.png"); Animation::addImage(animation, "Images/explosion/explosion14.png"); Animation::addImage(animation, "Images/explosion/explosion13.png"); Animation::addImage(animation, "Images/explosion/explosion12.png"); Animation::addImage(animation, "Images/explosion/explosion11.png"); Animation::addImage(animation, "Images/explosion/explosion10.png"); Animation::addImage(animation, "Images/explosion/explosion9.png"); Animation::addImage(animation, "Images/explosion/explosion8.png"); Animation::addImage(animation, "Images/explosion/explosion7.png"); Animation::addImage(animation, "Images/explosion/explosion6.png"); Animation::addImage(animation, "Images/explosion/explosion5.png"); Animation::addImage(animation, "Images/explosion/explosion4.png"); Animation::addImage(animation, "Images/explosion/explosion3.png"); Animation::addImage(animation, "Images/explosion/explosion2.png"); Animation::addImage(animation, "Images/explosion/explosion1.png"); } void Explosion::create(sf::Vector2f position, float scale, float timeScale, int timeDelay) { Explosion::explosion.push_back(std::make_shared <Explosion>(position.x, position.y, scale, timeScale, timeDelay)); } void Explosion::create(float x, float y, float scale, float timeScale, int timeDelay) { Explosion::explosion.push_back(std::make_shared <Explosion>(x, y, scale, timeScale, timeDelay)); } void Explosion::renderAll() { for (int i = Explosion::explosion.size() - 1; i >= 0; i--) { Explosion::explosion[i]->render(i); } } void Explosion::render(int explosionNumber) { timeDelay -= GameInfo::getDeltaTime(); if(timeDelay <= 0) { if (destroyed) { deltaTime += GameInfo::getDeltaTime(); if (deltaTime > 5000) Explosion::explosion.erase(Explosion::explosion.begin() + explosionNumber); } else { Animation::animation[animationObject]->render(&sprite); if (Animation::animation[animationObject]->licznik2 == 26) { Animation::animation[animationObject]->licznik2 = 0; destroyed = true; } } } }
#include <iostream> #include <vector> #include <string> #include <map> using namespace std; class ValueHistogram { public: int getMax(map<int, int> list) { int max = 0; for (int i=0; i<10; ++i) { if(max < list[i]){ max = list[i]; } } return max; } vector <string> build(vector <int> values) { map<int,int> list; for (int i=0; i<10; ++i) { list[i] = 0; } for (vector<int>::iterator it = values.begin(); it != values.end(); ++it) { list[*it]++; } int max = getMax(list); vector<string> ret(max+1); string tmp =".........."; for (vector<string>::iterator it = ret.begin(); it != ret.end(); ++it) { *it = tmp; } int size = (int)ret.size() - 1; for (int i=0; i<10; ++i) { for (int j=0; j<list[i]; ++j) { ret[size-j][i] = 'X'; } } return ret; } };
/** * @copyright 2013 Christoph Woester * @author Christoph Woester * * 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. */ #ifndef EFFICIENTPORTFOLIOCORETEST_H_ #define EFFICIENTPORTFOLIOCORETEST_H_ #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestFixture.h> #include <cppunit/TestSuite.h> #include "../../optimizer/EfficientRiskyAssetPortfolio.h" #include "../runner/fpo_tests.h" #include <Eigen/Dense> namespace fpo { class EfficientRiskyAssetPortfolio; } namespace fpo { class EfficientRiskyAssetPortfolioTest : public CPPUNIT_NS::TestFixture { private: CPPUNIT_TEST_SUITE(EfficientRiskyAssetPortfolioTest); CPPUNIT_TEST(testMinimumVariancePortfolio); CPPUNIT_TEST(testPerformanceIncreasingPortfolio); CPPUNIT_TEST(testEfficientPortfolio); CPPUNIT_TEST_SUITE_END(); Eigen::VectorXd* _mean; Eigen::MatrixXd* _variance; public: EfficientRiskyAssetPortfolioTest(); virtual ~EfficientRiskyAssetPortfolioTest(); void testMinimumVariancePortfolio(); void testPerformanceIncreasingPortfolio(); void testEfficientPortfolio(); private: void _createReturnStatistics(); void _destroyReturnStatistics(); }; } /* namespace fpo */ #endif /* EFFICIENTPORTFOLIOCORETEST_H_ */
#ifndef SRC_SIZE_H #define SRC_SIZE_H /** * Return the number of children/first-level descendants for this TrieNode. */ template<class T> int TrieNode<T>::getNumChildren() { return children.size(); } /** * Return true if this TrieNode has children and false otherwise. */ template<class T> bool TrieNode<T>::hasChildren() { return !children.empty(); } /** * Return true if this TrieNode has a parent and false otherwise. */ template<class T> bool TrieNode<T>::hasParent() { return parent != NULL; } /** * Return true if this TrieNode does not have a parent or any children, * and if size = 1. Otherwise, return false. */ template<class T> bool TrieNode<T>::isSingleton() { return !hasChildren() && !hasParent() && size() == 1; } /** * Return the total number of TrieNodes below this TrieNode (all descendants), including * this TrieNode. */ template<class T> int TrieNode<T>::size() { // Return 1 if this TrieNode has no children/descendants. int size = 1; if (children.empty()) { return size; } // Otherwise, add up the number of descendants for each TrieNode. // size starts at 1 to account for this TrieNode. for (int i = 0; i < children.size(); i++) { size += children[i]->size(); } return size; } #endif // SRC_SIZE_H
#pragma once #include "merger_base.hpp" #include "proto/data_tower.pb.h" #include "utils/service_thread.hpp" #include <memory> using namespace std; namespace pd = proto::data; namespace nora { class tower_merger : public merger_base { public: static tower_merger& instance() { static tower_merger inst; return inst; } void start(); private: void load_next_level(); void merge(); int cur_level_ = 1; bool from_tower_end_ = false; bool to_tower_end_ = false; unique_ptr<pd::tower_record_array> from_tower_; unique_ptr<pd::tower_record_array> to_tower_; }; }
/** * Copyright (c) 2007-2012, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "base/auto_fd.hh" #include "config.h" #include "line_buffer.hh" using namespace std; static const char* TEST_DATA = "Hello, World!\n" "Goodbye, World!\n"; static void single_line(const char* data) { line_buffer lb; auto_fd pi[2]; off_t off = 0; assert(auto_fd::pipe(pi) == 0); log_perror(write(pi[1], data, strlen(data))); pi[1].reset(); lb.set_fd(pi[0]); auto load_result = lb.load_next_line({off}); auto li = load_result.unwrap(); assert(data[strlen(data) - 1] == '\n' || li.li_partial); assert(li.li_file_range.next_offset() == (off_t) strlen(data)); assert(li.li_file_range.fr_size == strlen(data)); auto next_load_result = lb.load_next_line(li.li_file_range); assert(next_load_result.isOk()); assert(next_load_result.unwrap().li_file_range.empty()); assert(lb.get_file_size() != -1); } int main(int argc, char* argv[]) { int retval = EXIT_SUCCESS; single_line("Dexter Morgan"); single_line("Rudy Morgan\n"); { char fn_template[] = "test_line_buffer.XXXXXX"; auto fd = auto_fd(mkstemp(fn_template)); remove(fn_template); line_buffer lb; write(fd, TEST_DATA, strlen(TEST_DATA)); lseek(fd, SEEK_SET, 0); lb.set_fd(fd); shared_buffer_ref sbr; auto result = lb.read_range({0, 1024}); assert(result.isErr()); } { static string first = "Hello"; static string second = ", World!"; static string third = "Goodbye, World!"; static string last = "\n"; line_buffer lb; auto_fd pi[2]; off_t off = 0; assert(auto_fd::pipe(pi) == 0); log_perror(write(pi[1], first.c_str(), first.size())); fcntl(pi[0], F_SETFL, O_NONBLOCK); lb.set_fd(pi[0]); auto load_result = lb.load_next_line({off}); auto li = load_result.unwrap(); assert(li.li_partial); assert(li.li_file_range.fr_size == 5); log_perror(write(pi[1], second.c_str(), second.size())); auto load_result2 = lb.load_next_line({off}); li = load_result2.unwrap(); assert(li.li_partial); assert(li.li_file_range.fr_size == 13); log_perror(write(pi[1], last.c_str(), last.size())); auto load_result3 = lb.load_next_line({off}); li = load_result3.unwrap(); assert(!li.li_partial); assert(li.li_file_range.fr_size == 14); auto load_result4 = lb.load_next_line(li.li_file_range); li = load_result4.unwrap(); auto last_range = li.li_file_range; assert(li.li_partial); assert(li.li_file_range.empty()); log_perror(write(pi[1], third.c_str(), third.size())); auto load_result5 = lb.load_next_line(last_range); li = load_result5.unwrap(); assert(li.li_partial); assert(li.li_file_range.fr_size == 15); log_perror(write(pi[1], last.c_str(), last.size())); auto load_result6 = lb.load_next_line(last_range); li = load_result6.unwrap(); assert(!li.li_partial); assert(li.li_file_range.fr_size == 16); auto load_result7 = lb.load_next_line(li.li_file_range); li = load_result7.unwrap(); assert(li.li_partial); assert(li.li_file_range.empty()); assert(!lb.is_pipe_closed()); pi[1].reset(); auto load_result8 = lb.load_next_line(li.li_file_range); li = load_result8.unwrap(); assert(!li.li_partial); assert(li.li_file_range.empty()); assert(lb.is_pipe_closed()); } return retval; }
#pragma once #include <stdio.h> #ifdef __linux__ // OpenGL includes for Raspberry Pi #include <GL/glu.h> #include "GLES2/gl2.h" #include "EGL/egl.h" #include "EGL/eglext.h" #else // OpenGL includes for Windows #include <gl\glew.h> #include <SDL_opengl.h> #endif #include "globals.h" #include "stb_image.h" /** * Cube class * Cube rotates and has same texture on all 6 sides. */ class Cube { public: Cube(); ~Cube(); /** * Init vertex data and texture if any. */ bool init(); /** * Renders the cube. */ void render(); /** * Update cube state. Rotation in this case. */ void update(); private: bool m_render; // will render cube only when true float m_angle; // rotation angle // GL GLuint m_textures[1]; // One texture, but can be extended to multiple GLuint m_gVBO; // Vertex buffer object };
class Solution { public: int longestPalindrome(string s) { unordered_map<char, int> check; for(char c : s) ++check[c]; int res = 0; for(auto it : check) { if(!(it.second % 2)) res += it.second; else if(it.second >= 2) //odd case res += it.second - 1; } return res < s.size() ? res + 1 : res; //if there is at least an odd case, leave 1 for it } };
#pragma once #include "Curve.h" namespace ae { /// \ingroup math /// <summary>Linear 3D parametric curve.</summary> class AERO_CORE_EXPORT CurveLinear : public Curve { public: /// <summary> /// Build a curve with the given control points.<para/> /// The tangents are automaticaly computed from the points. /// </summary> /// <param name="_ControlPoints">The curve control points.</param> CurveLinear( const std::vector<Vector3>& _ControlPoints ); /// <summary>Get a curve point at the given parameter.</summary> /// <param name="_Param">The parameter on the curve.</param> /// <returns>Position on the curve at the given parameter.</returns> Vector3 GetPointAtParam( float _Param ) const override; /// <summary>Get the interpolation type of the curve.</summary> /// <returns>The interpolation type of the curve.</returns> Type GetType() const override; private: /// <summary>Linear interpolate the two control data around the parameter index.</summary> /// <param name="_Param">The parameter on the curve.</param> /// <param name="_ToInterpolate">The data to interpolate.</param> /// <returns>The interpolated data.</returns> Vector3 LinearInterpolation( float _Param, const std::vector<Vector3>& _ToInterpolate ) const; }; } // ae
// Created on: 1992-08-06 // Created by: Laurent BUCHARD // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IntAna_IntConicQuad_HeaderFile #define _IntAna_IntConicQuad_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Integer.hxx> #include <gp_Pnt.hxx> class gp_Lin; class IntAna_Quadric; class gp_Circ; class gp_Elips; class gp_Parab; class gp_Hypr; class gp_Pln; //! This class provides the analytic intersection between //! a conic defined as an element of gp (Lin,Circ,Elips, //! Parab,Hypr) and a quadric as defined in the class //! Quadric from IntAna. //! The intersection between a conic and a plane is treated //! as a special case. //! //! The result of the intersection are points (Pnt from //! gp), associated with the parameter on the conic. //! //! A call to an Intersection L:Lin from gp and //! SPH: Sphere from gp can be written either : //! IntAna_IntConicQuad Inter(L,IntAna_Quadric(SPH)) //! or : //! IntAna_IntConicQuad Inter(L,SPH) (it is necessary //! to include IntAna_Quadric.hxx in this case) class IntAna_IntConicQuad { public: DEFINE_STANDARD_ALLOC //! Empty constructor. Standard_EXPORT IntAna_IntConicQuad(); //! Creates the intersection between a line and a quadric. Standard_EXPORT IntAna_IntConicQuad(const gp_Lin& L, const IntAna_Quadric& Q); //! Intersects a line and a quadric. Standard_EXPORT void Perform (const gp_Lin& L, const IntAna_Quadric& Q); //! Creates the intersection between a circle and a quadric. Standard_EXPORT IntAna_IntConicQuad(const gp_Circ& C, const IntAna_Quadric& Q); //! Intersects a circle and a quadric. Standard_EXPORT void Perform (const gp_Circ& C, const IntAna_Quadric& Q); //! Creates the intersection between an ellipse and a quadric. Standard_EXPORT IntAna_IntConicQuad(const gp_Elips& E, const IntAna_Quadric& Q); //! Intersects an ellipse and a quadric. Standard_EXPORT void Perform (const gp_Elips& E, const IntAna_Quadric& Q); //! Creates the intersection between a parabola and a quadric. Standard_EXPORT IntAna_IntConicQuad(const gp_Parab& P, const IntAna_Quadric& Q); //! Intersects a parabola and a quadric. Standard_EXPORT void Perform (const gp_Parab& P, const IntAna_Quadric& Q); //! Creates the intersection between an hyperbola and //! a quadric. Standard_EXPORT IntAna_IntConicQuad(const gp_Hypr& H, const IntAna_Quadric& Q); //! Intersects an hyperbola and a quadric. Standard_EXPORT void Perform (const gp_Hypr& H, const IntAna_Quadric& Q); //! Intersection between a line and a plane. //! Tolang is used to determine if the angle between two //! vectors is null. //! Tol is used to check the distance between line and plane //! on the distance <Len> from the origin of the line. Standard_EXPORT IntAna_IntConicQuad(const gp_Lin& L, const gp_Pln& P, const Standard_Real Tolang, const Standard_Real Tol = 0, const Standard_Real Len = 0); //! Intersects a line and a plane. //! Tolang is used to determine if the angle between two //! vectors is null. //! Tol is used to check the distance between line and plane //! on the distance <Len> from the origin of the line. Standard_EXPORT void Perform (const gp_Lin& L, const gp_Pln& P, const Standard_Real Tolang, const Standard_Real Tol = 0, const Standard_Real Len = 0); //! Intersection between a circle and a plane. //! Tolang is used to determine if the angle between two //! vectors is null. //! Tol is used to determine if a distance is null. Standard_EXPORT IntAna_IntConicQuad(const gp_Circ& C, const gp_Pln& P, const Standard_Real Tolang, const Standard_Real Tol); //! Intersects a circle and a plane. //! Tolang is used to determine if the angle between two //! vectors is null. //! Tol is used to determine if a distance is null. Standard_EXPORT void Perform (const gp_Circ& C, const gp_Pln& P, const Standard_Real Tolang, const Standard_Real Tol); //! Intersection between an ellipse and a plane. //! Tolang is used to determine if the angle between two //! vectors is null. //! Tol is used to determine if a distance is null. Standard_EXPORT IntAna_IntConicQuad(const gp_Elips& E, const gp_Pln& P, const Standard_Real Tolang, const Standard_Real Tol); //! Intersects an ellipse and a plane. //! Tolang is used to determine if the angle between two //! vectors is null. //! Tol is used to determine if a distance is null. Standard_EXPORT void Perform (const gp_Elips& E, const gp_Pln& P, const Standard_Real Tolang, const Standard_Real Tol); //! Intersection between a parabola and a plane. //! Tolang is used to determine if the angle between two //! vectors is null. Standard_EXPORT IntAna_IntConicQuad(const gp_Parab& Pb, const gp_Pln& P, const Standard_Real Tolang); //! Intersects a parabola and a plane. //! Tolang is used to determine if the angle between two //! vectors is null. Standard_EXPORT void Perform (const gp_Parab& Pb, const gp_Pln& P, const Standard_Real Tolang); //! Intersection between an hyperbola and a plane. //! Tolang is used to determine if the angle between two //! vectors is null. Standard_EXPORT IntAna_IntConicQuad(const gp_Hypr& H, const gp_Pln& P, const Standard_Real Tolang); //! Intersects an hyperbola and a plane. //! Tolang is used to determine if the angle between two //! vectors is null. Standard_EXPORT void Perform (const gp_Hypr& H, const gp_Pln& P, const Standard_Real Tolang); //! Returns TRUE if the creation completed. Standard_Boolean IsDone() const; //! Returns TRUE if the conic is in the quadric. Standard_Boolean IsInQuadric() const; //! Returns TRUE if the line is in a quadric which //! is parallel to the quadric. Standard_Boolean IsParallel() const; //! Returns the number of intersection point. Standard_Integer NbPoints() const; //! Returns the point of range N. const gp_Pnt& Point (const Standard_Integer N) const; //! Returns the parameter on the line of the intersection //! point of range N. Standard_Real ParamOnConic (const Standard_Integer N) const; protected: private: Standard_Boolean done; Standard_Boolean parallel; Standard_Boolean inquadric; Standard_Integer nbpts; gp_Pnt pnts[4]; Standard_Real paramonc[4]; }; #include <IntAna_IntConicQuad.lxx> #endif // _IntAna_IntConicQuad_HeaderFile
#ifndef __SERIALRDM_H__ #define __SERIALRDM_H__ #include <ros/ros.h> #include <geometry_msgs/PoseStamped.h> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <netinet/in.h> #include <signal.h> #include <string.h> #include <pthread.h> #include <termios.h> #include <ctype.h> #include <math.h> #include <time.h> #include <fstream> #include <stdarg.h> #include <sys/time.h> #include <sys/stat.h> #include <fcntl.h> #pragma warning( disable : 4996 ) #define MAX_NAMELENGTH 256 #define MULTICAST_ADDRESS "239.255.42.99" // IANA, local network #define PORT_DATA 1511 // Default multicast group #define EXTERNALGPS_IPADDRESS "192.168.1.74" //#define ONBOARD_IPADDRESS "192.168.1.50" #define ONBOARD_IPADDRESS "192.168.1.63" // Socket compatible #ifndef INVALID_SOCKET #define INVALID_SOCKET -1 #endif #ifndef SOCKET_ERROR #define SOCKET_ERROR -1 #endif class ExternalGPS { public: // Constructor / Destructor ExternalGPS(void); virtual ~ExternalGPS(); int quadID; void set_values(int id, char myip[100], char serverip[100]); float g_x,g_y,g_z,g_qx,g_qy,g_qz,g_qw; int init(void); void loop(void); private: char szMyIPAddress[128]; char szServerIPAddress[128]; int DataSocket; char szData[20000]; int addr_len; struct sockaddr_in TheirAddress; // Analyse the data void Unpack(char*,int); }; #endif
// Created on: 2013-01-17 // Created by: Kirill GAVRILOV // Copyright (c) 2013-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef Standard_CLocaleSentry_HeaderFile #define Standard_CLocaleSentry_HeaderFile #include <Standard_Macro.hxx> #include <locale.h> #if defined(__APPLE__) #include <xlocale.h> #endif #ifndef OCCT_CLOCALE_POSIX2008 //! @def OCCT_CLOCALE_POSIX2008 //! //! POSIX.1-2008 extends C locale API by providing methods like newlocale/freelocale/uselocale. //! Presence of this extension cannot be checked in straightforward way (like (_POSIX_C_SOURCE >= 200809L)) //! due to missing such declarations in standard. //! On macOS new functions are declared within "xlocale.h" header (the same is for glibc, but this header has been removed since glibc 2.26). #if defined(__APPLE__) #define OCCT_CLOCALE_POSIX2008 #endif //! We check _GNU_SOURCE for glibc extensions here and it is always defined by g++ compiler. #if defined(_GNU_SOURCE) && !defined(__ANDROID__) #define OCCT_CLOCALE_POSIX2008 #endif #endif #if !defined(__ANDROID__) //! This class intended to temporary switch C locale and logically equivalent to setlocale(LC_ALL, "C"). //! It is intended to format text regardless of user locale settings (for import/export functionality). //! Thus following calls to sprintf, atoi and other functions will use "C" locale. //! Destructor of this class will return original locale. //! //! Notice that this functionality is platform dependent and intended only to workaround alien code //! that doesn't setup locale correctly. //! //! Internally you should prefer more portable C++ locale interfaces //! or OCCT wrappers to some C functions like Sprintf, Atof, Strtod. class Standard_CLocaleSentry { public: //! Setup current C locale to "C". Standard_EXPORT Standard_CLocaleSentry(); //! Restore previous locale. Standard_EXPORT ~Standard_CLocaleSentry(); public: #ifdef OCCT_CLOCALE_POSIX2008 typedef locale_t clocale_t; #elif defined(_MSC_VER) typedef _locale_t clocale_t; #else typedef void* clocale_t; #endif //! @return locale "C" instance (locale_t within xlocale or _locale_t within Windows) //! to be used for _l functions with locale argument. static Standard_EXPORT clocale_t GetCLocale(); private: void* myPrevLocale; //!< previous locale, platform-dependent pointer! #ifdef _MSC_VER int myPrevTLocaleState; //!< previous thread-locale state, MSVCRT-specific #endif private: //! Copying disallowed Standard_CLocaleSentry (const Standard_CLocaleSentry& ); Standard_CLocaleSentry& operator= (const Standard_CLocaleSentry& ); }; #else //! C/C++ runtime on Android currently supports only C-locale, no need to call anything. class Standard_CLocaleSentry { public: Standard_CLocaleSentry() {} typedef void* clocale_t; static clocale_t GetCLocale() { return 0; } }; #endif // __ANDROID__ #endif // _Standard_CLocaleSentry_H__
#include "CentralWindow.h" #include <QMessageBox> #include <QMouseEvent> CentralWindow::CentralWindow(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); connect(&timer, SIGNAL(timeout()), this, SLOT(draw())); timer.start(timerInterval); bubbleManager = new BubbleManager(ui.centralWidget); calculationThread = new CalculationThread(bubbleManager); calculationThread->start(); } CentralWindow::~CentralWindow() { timer.stop(); calculationThread->stop(); calculationThread->wait(); delete calculationThread; delete bubbleManager; } void CentralWindow::mousePressEvent(QMouseEvent * event) { if (event->button() == Qt::MouseButton::LeftButton) { bubbleManager->lock(); timer.stop(); Bubble* bl = bubbleManager->addBubble(); connect(bl, SIGNAL(finishedAnimation()), this, SLOT(bubleAnimationFinished())); connect(bl, SIGNAL(startMove()), this, SLOT(bubleStartMove())); connect(bl, SIGNAL(finishedMove()), this, SLOT(bubleFinishedMove())); connect(bl, SIGNAL(mousePress(Bubble&)), bubbleManager, SLOT(removeBubble(Bubble&))); bl->show(); bubbleManager->unlock(); timer.start(timerInterval); } else draw(); } void CentralWindow::bubleAnimationFinished() { QMutexLocker ml(&mutex); animationCount--; timerStart(); } void CentralWindow::bubleStartMove() { isBubleMove = true; timer.stop(); } void CentralWindow::bubleFinishedMove() { isBubleMove = false; timer.start(); } void CentralWindow::draw() { QMutexLocker ml(&mutex); timer.stop(); bubbleManager->lock(); animationCount = 0; foreach(Bubble* key, bubbleManager->bubbles.keys()) { animationCount++; key->animationMove(bubbleManager->bubbles.value(key)); bubbleManager->bubbles.insert(key, QPoint(0, 0)); } bubbleManager->unlock(); timerStart(); } void CentralWindow::timerStart() { if (animationCount == 0 && !isBubleMove) { timer.start(timerInterval); } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" #if defined(_NATIVE_SSL_SUPPORT_) #ifdef SSL_DH_SUPPORT #include "modules/libssl/sslbase.h" #include "modules/libssl/handshake/dhparam.h" SSL_ServerDHParams::SSL_ServerDHParams() { AddItem(dh_p); AddItem(dh_g); AddItem(dh_Ys); } BOOL SSL_ServerDHParams::Valid(SSL_Alert *msg) const { if(!LoadAndWritableList::Valid(msg)) return FALSE; if(dh_p.GetLength() <1 || dh_g.GetLength() <1 || dh_Ys.GetLength() <1) { if(msg != NULL) msg->Set(SSL_Fatal, SSL_Illegal_Parameter); return FALSE; } return TRUE; } #endif // SSL_DH_SUPPORT #endif
#pragma once #include <vector> #include<string> #include "TrackPoint.h" #include "SqlTool.h" using std::vector; using std::string; class Track { private: int TRACKID; int POINTAMOUNT; string TARGETID; /*char* TARGETMODELNUMBER; char* TARGETNAME; char* TARGETTYPE;*/ int STARTTIME; int ENDTIME; double CONFIDENCELEVEL; char* SOURCE; char* TASKINFO; char* OPERATOR; char* RESERVE1; char* RESERVE2; double length; public: vector<TrackPoint> historyPoint; vector<int> featurePointIndex; vector<int> mdlPointIndex; Track(); Track(int trackID, char* TARGETID, char* SOURCE, char* TASKINFO, char* OPERATOR, int STARTTIME); Track(int trackID, char* TARGETID, char* SOURCE, char* TASKINFO, char* OPERATOR, char* STARTTIME); Track(char* trackID, char* POINTAMOUNT, char* TARGETID, char* STARTTIME, char* ENDTIME, char* LENGTH, char* SOURCE, char* TASKINFO, char* CONFIDENCELEVEL, char* OPERATOR, char* RESERVE1, char* RESERVE2); ~Track(); const static char* getTargetsQuery; static char* getTargetRecords(char* targetID); //static Track frequentTrackGenerate(vector<Segment>clusterSegs, vector<Point> freqPoints); //static int getMinTrackID(); int getTrackID(); int getEndTime(); int getStartTime(); int getPointAmount(); void setPointAmount(int pointAmount); void setStartTime(int startTime); void setEndTime(int endTime); void setTrackID(int trackID); void setLength(double length); void setTargetID(char* id); void setTrackIDofPoint(int trackID); string getTargetID(); string insertHisSQL(); char* insertFreqSQL(); void trackEndProcession(int endTime, int pointAmount, vector<TrackPoint>details, double totalLength); };
#define WIN32_LEAN_AND_MEAN #include <windows.h> #pragma warning (disable: 4104) #define DLL_EXP extern "C" HRESULT __declspec(dllexport) __stdcall // define them first with the correct linkage since they are defined incorrectly in the following includes DLL_EXP DllCanUnloadNow(); DLL_EXP DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppReturn); DLL_EXP DllRegisterServer(); DLL_EXP DllUnregisterServer(); #include <shlobj.h> #include <olectl.h> #define GUID_STR L"{1F151065-B5A0-4A89-95B8-6DCCD0918D54}" GUID CLSID_HelloExtNoAtl = { 0x1f151065, 0xb5a0, 0x4a89, 0x95, 0xb8, 0x6d, 0xcc, 0xd0, 0x91, 0x8d, 0x54 }; #define EXT_NAME L"MyHelloExt" // data HINSTANCE g_hInst; UINT g_DllRefCount; DWORD WINAPI threadMain(LPVOID lpParameter); BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: g_hInst = (HINSTANCE)hModule; CreateThread(NULL, 0, threadMain, 0, 0, NULL); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } class CShellExt : public IShellExtInit //, IContextMenu { protected: DWORD m_ObjRefCount; public: CShellExt::CShellExt() { } virtual CShellExt::~CShellExt() { } // IUnknown methods STDMETHODIMP_(DWORD) Release(void) { if (--m_ObjRefCount == 0) { delete this; return 0; } return m_ObjRefCount; } STDMETHODIMP_(DWORD) AddRef(void) { return ++m_ObjRefCount; } STDMETHODIMP QueryInterface(REFIID riid, LPVOID *ppReturn) { *ppReturn = NULL; if (IsEqualIID(riid, IID_IUnknown)) *ppReturn = this; else if (IsEqualIID(riid, IID_IClassFactory)) *ppReturn = (IClassFactory*)this; else if (IsEqualIID(riid, IID_IShellExtInit)) *ppReturn = (IShellExtInit*)this; else return E_NOINTERFACE; LPUNKNOWN pUnk = (LPUNKNOWN)(*ppReturn); pUnk->AddRef(); return S_OK; } // IShellExtInit STDMETHODIMP Initialize(LPCITEMIDLIST pidlFolder, LPDATAOBJECT pDataObj, HKEY hProgID) { return S_OK; } }; class CClassFactory : public IClassFactory { protected: DWORD m_ObjRefCount; public: CClassFactory() { m_ObjRefCount = 1; g_DllRefCount++; } virtual ~CClassFactory() { g_DllRefCount--; } //IUnknown methods STDMETHODIMP QueryInterface(REFIID riid, LPVOID *ppReturn) { *ppReturn = NULL; if (IsEqualIID(riid, IID_IUnknown)) *ppReturn = this; else if (IsEqualIID(riid, IID_IClassFactory)) *ppReturn = (IClassFactory*)this; else return E_NOINTERFACE; LPUNKNOWN pUnk = (LPUNKNOWN)(*ppReturn); pUnk->AddRef(); return S_OK; } STDMETHODIMP_(DWORD) AddRef() { return ++m_ObjRefCount; } STDMETHODIMP_(DWORD) Release() { if (--m_ObjRefCount == 0) { delete this; return 0; } return m_ObjRefCount; } //IClassFactory methods STDMETHODIMP CreateInstance(LPUNKNOWN pUnknown, REFIID riid, LPVOID *ppObject) { *ppObject = NULL; if (pUnknown != NULL) return CLASS_E_NOAGGREGATION; // creates the namespace's main class CShellExt *pShellExt = new CShellExt(); if (NULL == pShellExt) return E_OUTOFMEMORY; // query interface for the return value HRESULT hResult = pShellExt->QueryInterface(riid, ppObject); pShellExt->Release(); return hResult; } STDMETHODIMP LockServer(BOOL) { return E_NOTIMPL; }; }; DLL_EXP DllCanUnloadNow() { return (g_DllRefCount ? S_FALSE : S_OK); } DLL_EXP DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppReturn) { *ppReturn = NULL; // do we support the CLSID? if( !IsEqualCLSID(rclsid, CLSID_HelloExtNoAtl) ) return CLASS_E_CLASSNOTAVAILABLE; // call the factory CClassFactory *pClassFactory = new CClassFactory(); if (pClassFactory == NULL) return E_OUTOFMEMORY; // query interface for the a pointer HRESULT hResult = pClassFactory->QueryInterface(riid, ppReturn); pClassFactory->Release(); return hResult; } struct REGSTRUCT{ HKEY hRootKey; LPWSTR lpszSubKey; LPWSTR lpszValueName; LPWSTR lpszData; }; REGSTRUCT ClsidEntries[] = { HKEY_CLASSES_ROOT, L"CLSID\\" GUID_STR, NULL, EXT_NAME, // HKEY_CLASSES_ROOT, L"CLSID\\" GUID_STR, L"InfoTip", EXT_NAME L".", HKEY_CLASSES_ROOT, L"CLSID\\" GUID_STR L"\\InprocServer32", NULL, L"%s", HKEY_CLASSES_ROOT, L"CLSID\\" GUID_STR L"\\InprocServer32", L"ThreadingModel", L"Apartment", // HKEY_CLASSES_ROOT, L"CLSID\\" GUID_STR L"\\DefaultIcon", NULL, L"%s,0", HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ShellIconOverlayIdentifiers\\" EXT_NAME, NULL, GUID_STR, HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved", GUID_STR, EXT_NAME }; //"txtfile\\ShellEx\\ContextMenuHandlers\\" EXT_NAME DLL_EXP DllRegisterServer() { WCHAR szModule[MAX_PATH]; GetModuleFileNameW(g_hInst, szModule, ARRAYSIZE(szModule) ); for(int i = 0; i < _countof(ClsidEntries); ++i) { HKEY hKey; DWORD dwDisp; LRESULT lResult = RegCreateKeyExW(ClsidEntries[i].hRootKey, ClsidEntries[i].lpszSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, &dwDisp); if (lResult == 0) { WCHAR szData[MAX_PATH]; wsprintfW(szData, ClsidEntries[i].lpszData, szModule); lResult = RegSetValueExW(hKey, ClsidEntries[i].lpszValueName, 0, REG_SZ, (LPBYTE)szData, (lstrlenW(szData) + 1) * sizeof(WCHAR)); RegCloseKey(hKey); } else return SELFREG_E_CLASS; } return S_OK; } DLL_EXP DllUnregisterServer() { WCHAR szModule[MAX_PATH]; GetModuleFileNameW(g_hInst, szModule, ARRAYSIZE(szModule) ); LRESULT lResult; for(int i = 0; i < _countof(ClsidEntries) - 1; ++i) { lResult = RegDeleteKeyW(ClsidEntries[i].hRootKey, ClsidEntries[i].lpszSubKey); } // only remove value, not key int entryIndex = _countof(ClsidEntries) - 1; HKEY hKey; lResult = RegOpenKeyExW(ClsidEntries[entryIndex].hRootKey, ClsidEntries[entryIndex].lpszSubKey, 0, KEY_WRITE, &hKey); if (lResult == 0) { lResult = RegDeleteValueW(hKey, ClsidEntries[entryIndex].lpszValueName); RegCloseKey(hKey); } return S_OK; }
#include <iostream> #include <time.h> #include <algorithm> #include <random> #include <vector> using namespace std; using ll = long long; template <typename T> T gcd(T a, T b) { if (a < b) return gcd(b, a); return b == 0 ? a : gcd(b, a % b); } mt19937 mert(ll(time(0))); int q = 0; int query(int t, int x) { cout << "?>"[t] << " " << x << endl; ++q; int res; cin >> res; return res; } int findmax() { // ok >= max int ok = 1e9 + 1, ng = -1; while (ok - ng > 1) { int mid = (ok + ng) / 2; int res = query(1, mid); if (res) { ng = mid; } else { ok = mid; } } return ok; } void answer(int x1, int d) { cout << "! " << x1 << " " << d << endl; } int main() { int N; cin >> N; int M = findmax(); vector<int> a; bool asked[N]; fill(asked, asked + N, false); while (q < 60 && !all_of(asked, asked + N, [](bool b) { return b; })) { while (true) { int i = mert() % N; if (asked[i]) continue; a.push_back(query(0, i + 1)); asked[i] = true; break; } } sort(a.begin(), a.end()); int g = M - a.front(); for (int i = 0; i < a.size() - 1; ++i) { g = gcd(g, a[i + 1] - a[i]); } answer(M - (N - 1) * g, g); return 0; }
#pragma once #include"Saving.h" class Term:public Saving { private: int Kyhan; public: friend istream& operator>>(istream&, Term&); friend ostream& operator<<(ostream&, Term); double TinhTienLai(); Term(); ~Term(); };
// Copyright 2018 Benjamin Bader // // 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. #include <metrics/Meter.h> #include <metrics/Clock.h> #include <metrics/EWMA.h> namespace cppmetrics { namespace { using namespace std::chrono; using namespace std::chrono_literals; const long long kTickInterval = duration_cast<nanoseconds>(5s).count(); } Meter::Meter(Clock* clock) : m_clock(clock != nullptr ? clock : GetDefaultClock()) , m_count(0) , m_start_time(m_clock->tick()) , m_last_tick(m_start_time.count()) , m_m1( EWMA::one_minute() ) , m_m5( EWMA::five_minutes() ) , m_m15( EWMA::fifteen_minutes() ) {} void Meter::mark(long n) { tick_if_necessary(); m_count += n; m_m1->update(n); m_m5->update(n); m_m15->update(n); } void Meter::tick_if_necessary() { auto old_tick = m_last_tick.load(); auto new_tick = m_clock->tick().count(); auto age = new_tick - old_tick; if (age > kTickInterval) { auto new_interval_start_tick = new_tick - age % kTickInterval; if (std::atomic_compare_exchange_strong(&m_last_tick, &old_tick, new_interval_start_tick)) { auto required_ticks = age / kTickInterval; for (int i = 0; i < required_ticks; ++i) { m_m1->tick(); m_m5->tick(); m_m15->tick(); } } } } long Meter::get_count() const noexcept { return m_count.load(); } double Meter::get_m1_rate() { tick_if_necessary(); return m_m1->get_rate(std::chrono::seconds(1)); } double Meter::get_m5_rate() { tick_if_necessary(); return m_m5->get_rate(std::chrono::seconds(1)); } double Meter::get_m15_rate() { tick_if_necessary(); return m_m15->get_rate(std::chrono::seconds(1)); } double Meter::get_mean_rate() { auto count = get_count(); if (count == 0) { return 0.0; } constexpr auto kNanosPerSecond = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::seconds(1)).count(); auto elapsed = m_clock->tick() - m_start_time; return static_cast<double>(count) / elapsed.count() * kNanosPerSecond; } }
// // This file contains the C++ code from Program 9.10 of // "Data Structures and Algorithms // with Object-Oriented Design Patterns in C++" // by Bruno R. Preiss. // // Copyright (c) 1998 by Bruno R. Preiss, P.Eng. All rights reserved. // // http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus4/programs/pgm09_10.cpp // #include <GeneralTree.h> #include <LinkedList.h> #include <stdexcept> using std::out_of_range; using std::logic_error; GeneralTree::GeneralTree (Object& _key) : key (&_key), degree (0), list () { count = 1; } void GeneralTree::Purge () { ListElement<GeneralTree*> const* ptr; if (IsOwner ()) delete key; for (ptr = list.Head (); ptr != 0; ptr = ptr->Next ()) delete ptr->Datum (); key = 0; list.Purge (); } int GeneralTree::Height() const { int height = 0; if(!degree){ return -1; } ListElement<GeneralTree*> const* ptr; for (ptr = list.Head (); ptr != 0; ptr = ptr->Next ()) { if (ptr->Datum ()->Height() > height){ height = ptr->Datum ()->Height(); } } return ++height; } GeneralTree::~GeneralTree () { Purge (); } Object& GeneralTree::Key () const { return *key; } GeneralTree& GeneralTree::Subtree (unsigned int i) const { if (i >= degree) throw out_of_range ("invalid subtree index"); unsigned int j = 0; ListElement<GeneralTree*> const* ptr = list.Head (); while (j < i && ptr != 0) { ++j; ptr = ptr->Next (); } if (ptr == 0) throw logic_error ("should never happen"); return *ptr->Datum (); } void GeneralTree::AttachSubtree (GeneralTree& t) { list.Append (&t); ++degree; } GeneralTree& GeneralTree::DetachSubtree (GeneralTree& t) { list.Extract (&t); --degree; return t; } void GeneralTree::Put (std::ostream& s) const { #ifdef DPRINT using namespace std; static int i = 0; ++i; cout<<"put :"<<i<<endl; #endif s<<*key; }
// Created on: 1992-05-06 // Created by: Jacques GOUSSARD // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IntPatch_TheSurfFunction_HeaderFile #define _IntPatch_TheSurfFunction_HeaderFile #include <Adaptor3d_Surface.hxx> #include <gp_Pnt.hxx> #include <gp_Vec.hxx> #include <gp_Dir2d.hxx> #include <math_FunctionSetWithDerivatives.hxx> #include <math_Vector.hxx> class Adaptor3d_HSurfaceTool; class IntSurf_Quadric; class IntSurf_QuadricTool; class math_Matrix; class IntPatch_TheSurfFunction : public math_FunctionSetWithDerivatives { public: DEFINE_STANDARD_ALLOC Standard_EXPORT IntPatch_TheSurfFunction(); Standard_EXPORT IntPatch_TheSurfFunction(const Handle(Adaptor3d_Surface)& PS, const IntSurf_Quadric& IS); Standard_EXPORT IntPatch_TheSurfFunction(const IntSurf_Quadric& IS); void Set (const Handle(Adaptor3d_Surface)& PS); void SetImplicitSurface (const IntSurf_Quadric& IS); void Set (const Standard_Real Tolerance); Standard_EXPORT Standard_Integer NbVariables() const; Standard_EXPORT Standard_Integer NbEquations() const; Standard_EXPORT Standard_Boolean Value (const math_Vector& X, math_Vector& F); Standard_EXPORT Standard_Boolean Derivatives (const math_Vector& X, math_Matrix& D); Standard_EXPORT Standard_Boolean Values (const math_Vector& X, math_Vector& F, math_Matrix& D); Standard_Real Root() const; //! Returns the value Tol so that if Abs(Func.Root())<Tol //! the function is considered null. Standard_Real Tolerance() const; const gp_Pnt& Point() const; Standard_EXPORT Standard_Boolean IsTangent(); const gp_Vec& Direction3d(); const gp_Dir2d& Direction2d(); const Handle(Adaptor3d_Surface)& PSurface() const; const IntSurf_Quadric& ISurface() const; protected: private: Standard_Address surf; Standard_Address func; Standard_Real u; Standard_Real v; Standard_Real tol; gp_Pnt pntsol; Standard_Real valf; Standard_Boolean computed; Standard_Boolean tangent; Standard_Real tgdu; Standard_Real tgdv; gp_Vec gradient; Standard_Boolean derived; gp_Vec d1u; gp_Vec d1v; gp_Vec d3d; gp_Dir2d d2d; }; #define ThePSurface Handle(Adaptor3d_Surface) #define ThePSurface_hxx <Adaptor3d_Surface.hxx> #define ThePSurfaceTool Adaptor3d_HSurfaceTool #define ThePSurfaceTool_hxx <Adaptor3d_HSurfaceTool.hxx> #define TheISurface IntSurf_Quadric #define TheISurface_hxx <IntSurf_Quadric.hxx> #define TheISurfaceTool IntSurf_QuadricTool #define TheISurfaceTool_hxx <IntSurf_QuadricTool.hxx> #define IntImp_ZerImpFunc IntPatch_TheSurfFunction #define IntImp_ZerImpFunc_hxx <IntPatch_TheSurfFunction.hxx> #include <IntImp_ZerImpFunc.lxx> #undef ThePSurface #undef ThePSurface_hxx #undef ThePSurfaceTool #undef ThePSurfaceTool_hxx #undef TheISurface #undef TheISurface_hxx #undef TheISurfaceTool #undef TheISurfaceTool_hxx #undef IntImp_ZerImpFunc #undef IntImp_ZerImpFunc_hxx #endif // _IntPatch_TheSurfFunction_HeaderFile
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #ifdef SQLITE_SUPPORT #include "modules/sqlite/sqlite_module.h" #include "modules/sqlite/sqlite3.h" /*virtual*/ void SqliteModule::Destroy() { sqlite3_shutdown(); } #endif // SQLITE_SUPPORT
//: C05:Stash.h // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt // Zmieniony w celu wykorzystania kontroli dostepu #ifndef STASH_H #define STASH_H class Stash { int size; // Wielkosc kazdego elementu int quantity; // Liczba elementow pamieci int next; // Nastepny pusty element // Dynamicznie przydzielana tablica bajtow: unsigned char* storage; void inflate(int increase); public: void initialize(int size); void cleanup(); int add(void* element); void* fetch(int index); int count(); }; #endif // STASH_H ///:~
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2012 Bryce Adelstein-Lelbach // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //////////////////////////////////////////////////////////////////////////////// #pragma once #include <pika/config.hpp> #include <pika/preprocessor/stringize.hpp> #include <string> namespace pika::util { // return the full path of the current executable PIKA_EXPORT std::string get_executable_filename(char const* argv0 = nullptr); PIKA_EXPORT std::string get_executable_prefix(char const* argv0 = nullptr); } // namespace pika::util
/* * Copyright 2016 Freeman Zhang <zhanggyb@gmail.com> * * 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. */ #ifndef SKLAND_WAYLAND_SEAT_HPP_ #define SKLAND_WAYLAND_SEAT_HPP_ #include "registry.hpp" namespace skland { namespace wayland { class Pointer; class Keyboard; class Touch; class XdgToplevel; class DataDevice; class Seat { friend class Pointer; friend class Keyboard; friend class Touch; friend class XdgToplevel; friend class DataDevice; Seat(const Seat &) = delete; Seat &operator=(const Seat &) = delete; public: Seat() : wl_seat_(nullptr) {} ~Seat() { if (wl_seat_) wl_seat_destroy(wl_seat_); } void Setup(const Registry &registry, uint32_t id, uint32_t version) { Destroy(); wl_seat_ = static_cast<struct wl_seat *>(registry.Bind(id, &wl_seat_interface, version)); wl_seat_add_listener(wl_seat_, &kListener, this); } void Destroy() { if (wl_seat_) { wl_seat_destroy(wl_seat_); wl_seat_ = nullptr; } } void SetUserData(void *user_data) { wl_seat_set_user_data(wl_seat_, user_data); } void *GetUserData() const { return wl_seat_get_user_data(wl_seat_); } uint32_t GetVersion() const { return wl_seat_get_version(wl_seat_); } bool IsValid() const { return nullptr != wl_seat_; } bool Equal(const void *object) const { return wl_seat_ == object; } DelegateRef<void(uint32_t)> capabilities() { return capabilities_; } DelegateRef<void(const char *)> name() { return name_; } private: static void OnCapabilities(void *data, struct wl_seat *wl_seat, uint32_t capabilities); static void OnName(void *data, struct wl_seat *wl_seat, const char *name); static const struct wl_seat_listener kListener; struct wl_seat *wl_seat_; Delegate<void(uint32_t)> capabilities_; Delegate<void(const char *)> name_; }; } } #endif // SKLAND_WAYLAND_SEAT_HPP_
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2010 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Luca Venturi ** ** This file contains several macros and some classes that did not find a better place. */ #ifndef CACHE_UTILS_H #define CACHE_UTILS_H // Class that define a segment of file stored on disk; usually storages will just host all the file or nothing, // but Multimedia Storages can host more than one, without covering all the file struct StorageSegment { // Content start of the segment. The position on the disk can be different OpFileLength content_start; // Bytes available on this segment. OpFileLength content_length; }; /// Generic class implementing an iterator. /// When the iterator is created, it can be iterated only once /// Example of use: /// while(ptr=iterator.Next(ops)) { /** Manage ptr */ } template <class T> class ListIterator { public: /// Return the next element, NULL if the last one is reached /// Call to Next() after the list is finished are legal, and they will return NULL virtual T* Next()=0; }; /// Iterator that is able to delete the last element returned. This has two main advantages: /// - The user does not have to know what operations are required to perform the delete correctly /// - It is possible to keep a different internal representation of what has been returned. /// Both these points are important to simplify the containers management template <class T> class ListIteratorDelete: public ListIterator<T> { public: /// Delete the last element returned by Next() virtual OP_STATUS DeleteLast()=0; }; // Class that delete a pointer when the destructor is called template <class T> class SafePointer { private: // Pointer T *ptr; // TRUE if it is an array BOOL is_array; public: /** Constructor. The pointer WILL be deleted on destruction. @param pointer Pointer to the resource @param vector TRUE if the pointer is a vector (meaningfull only for owned pointers); */ SafePointer(T *pointer, BOOL vector) { ptr=pointer; is_array=vector; } /// Return the pointer T *GetPointer() { return ptr; } // Destructor ~SafePointer() { if(is_array) OP_DELETEA(ptr); else OP_DELETE(ptr); } }; // Utility macro to reduce the complexity: traverse all the contexts // No references count performed #define CACHE_CTX_WHILE_BEGIN_NOREF { \ Context_Manager *manager=ctx_main; \ Context_Manager *next_manager=NULL; \ OP_ASSERT(manager); \ while(manager) { \ if(manager==ctx_main) \ next_manager = (Context_Manager *) context_list.First(); \ else \ next_manager = (Context_Manager *) (manager->Suc()); \ // Utility macro to reduce the complexity // No references count performed #define CACHE_CTX_WHILE_END_NOREF \ manager=next_manager; \ } \ } // Utility macro to reduce the complexity // No references count performed #define CACHE_CTX_WHILE_END_NOREF_FROZEN \ manager=next_manager; \ if(!manager) \ { \ manager=frozen_manager; \ frozen_manager=NULL; \ } \ } \ } // Utility macro to reduce the complexity: traverse all the contexts // References count performed #define CACHE_CTX_WHILE_BEGIN_REF { \ Context_Manager *manager=ctx_main; \ Context_Manager *next_manager=NULL; \ OP_ASSERT(manager); \ while(manager) { \ manager->IncReferencesCount(); \ if(manager==ctx_main) \ next_manager = (Context_Manager *) context_list.First(); \ else \ next_manager = (Context_Manager *) (manager->Suc()); \ // Utility macro to reduce the complexity // References count performed #define CACHE_CTX_WHILE_END_REF \ manager->DecReferencesCount(); \ manager=next_manager; \ } \ } // Utility macro to reduce the complexity: traverse all the contexts // References count performed // This version also check frozen contexts #define CACHE_CTX_WHILE_BEGIN_REF_FROZEN { \ Context_Manager *manager=ctx_main; \ Context_Manager *next_manager=NULL; \ Context_Manager *frozen_manager=(Context_Manager *)frozen_contexts.First(); \ OP_ASSERT(manager); \ while(manager) { \ manager->IncReferencesCount(); \ if(manager==ctx_main) \ next_manager = (Context_Manager *) context_list.First(); \ else \ next_manager = (Context_Manager *) (manager->Suc()); \ // Utility macro to reduce the complexity // References count performed #define CACHE_CTX_WHILE_END_REF_FROZEN \ manager->DecReferencesCount(); \ manager=next_manager; \ if(!manager) \ { \ manager=frozen_manager; \ frozen_manager=NULL; \ } \ } \ } // Call the method in every context, then continue #define CACHE_CTX_CALL_ALL(METHOD_CALL) \ CACHE_CTX_WHILE_BEGIN_REF \ manager->METHOD_CALL; \ CACHE_CTX_WHILE_END_REF // Call the method in every context and get the first error, then continue #define CACHE_CTX_CALL_ALL_OPS(OPS, METHOD_CALL) \ CACHE_CTX_WHILE_BEGIN_REF \ OP_STATUS temp=manager->METHOD_CALL; \ if(!OpStatus::IsSuccess(temp) && OpStatus::IsSuccess(OPS)) \ OPS=temp; \ CACHE_CTX_WHILE_END_REF // Call the method in the context with the right contextid; return void // Reference count protection applies #define CACHE_CTX_FIND_ID_VOID_REF(CTX_ID, METHOD_CALL) { \ Context_Manager *manager = FindContextManager(CTX_ID); \ if (manager) { \ manager->IncReferencesCount(); \ manager->METHOD_CALL; \ manager->DecReferencesCount(); \ return; \ } \ OP_ASSERT(FALSE); /*Cache context not found"*/ \ } // Call only the method in the context with the right contextid. #define CACHE_CTX_FIND_ID_VOID(CTX_ID, METHOD_CALL) { \ Context_Manager *manager = FindContextManager(CTX_ID); \ if (manager) { \ manager->METHOD_CALL; \ return; \ } \ OP_ASSERT(FALSE); /*Cache context not found"*/ \ } // Call only the method in the context with the right contextid (with return); // ERR is what to return when the context id is not found #define CACHE_CTX_FIND_ID_RETURN(CTX_ID, METHOD_CALL, ERR) { \ Context_Manager *manager = FindContextManager(CTX_ID); \ if (manager) { \ return manager->METHOD_CALL; \ } \ OP_ASSERT(FALSE); /*Cache context not found*/ \ return ERR; \ } // Parameter used only for selftests #ifdef SELFTEST #define SELFTEST_PARAM_COMMA_BEFORE(DEF) , DEF #else #define SELFTEST_PARAM_COMMA_BEFORE(DEF) #endif // Operator and OEM cache macros #if defined __OEM_EXTENDED_CACHE_MANAGEMENT && defined __OEM_OPERATOR_CACHE_MANAGEMENT #define OEM_EXT_OPER_CACHE_MNG(DEF) DEF #define OEM_EXT_OPER_CACHE_MNG_BEFORE(DEF) ,DEF #else #define OEM_EXT_OPER_CACHE_MNG(DEF) #define OEM_EXT_OPER_CACHE_MNG_BEFORE(DEF) #endif #if defined __OEM_EXTENDED_CACHE_MANAGEMENT && defined __OEM_CACHE_OPERATION #define OEM_CACHE_OPER(DEF) DEF #define OEM_CACHE_OPER_AFTER(DEF) DEF, #else #define OEM_CACHE_OPER(DEF) #define OEM_CACHE_OPER_AFTER(DEF) #endif #if defined __OEM_EXTENDED_CACHE_MANAGEMENT && defined __OEM_CACHE_OPERATION && defined __OEM_OPERATOR_CACHE_MANAGEMENT #define OPER_CACHE_COMMA() , #else #define OPER_CACHE_COMMA() #endif #endif
#pragma once #include <map> #include <string> #include <vector> using namespace std; class CAMB_CALLER { public: CAMB_CALLER(); ~CAMB_CALLER(); void call(map<string, double> params); void call_full(map<string, double> params); vector<vector<double>> get_Pz_values(); vector<double> get_k_values(); double get_sigma8(); private: vector<string> file_content; vector<double> k_values; vector<vector<double>> Pz_values; string parameter_names [13]; string NP_parameter_names [13]; vector<bool> parameters_found; void update_params_ini(map<string, double> params); void update_params_ini_full(map<string, double> params); void create_output_file(); void read_matterpower_files(int nfiles); void read_sigma8_file(); bool run_first_time, use_non_physical; int num_params; double sig8; };
//算法:堆 /* 维护一个最多能存下m个数的大根堆。 每读入一个数xi, 就将xi放入堆中。 如果堆中数的数量大于m, 就删掉大根堆的根。 就能维护当前最小的m个数了。 最后,将堆里的所有数排序,依次输出即可。 */ #include<cstdio> #include<queue> #include<functional> using namespace std; int n,m; priority_queue <int> s; priority_queue <int,vector<int>,greater<int> > s1; int main() { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) { int x; scanf("%d",&x); if(i<=m) s.push(x); else if(x<s.top()) s.pop(),s.push(x); } for(int i=1;i<=m;i++) { s1.push(s.top()); s.pop(); } while(!s1.empty()) { printf("%d\n",s1.top()); s1.pop(); } }
/*#include <iostream> #include "cards.h" using namespace std; int main() { // Create and print a demo card with arbitrery values. Card demoCard(500, 4); demoCard.printCard(); // Create and print a demo deck. Deck demoDeck; demoDeck.printDeck(); // Draw a card from the deck and print it. Card demoCard2 = demoDeck.draw(); demoCard2.printCard(); // Check the current deck after we draw a card from it. demoDeck.printDeck(); // Create and print a demo Hand from the already instantiated deck. Hand demoHand(demoDeck); demoHand.printHand(); // Check the current deck after we instantiated the Hand (we use draw 6 cards from the deck for the hand). demoDeck.printDeck(); // Create and print a single handSlot object using a single card drawed from the deck. HandSlot newHandSlot(0, demoDeck.draw()); newHandSlot.printHandSlot(); system("PAUSE"); return 0; }*/
/******************************************************************************** ** Form generated from reading UI file 'window.ui' ** ** Created by: Qt User Interface Compiler version 5.8.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_WINDOW_H #define UI_WINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QGridLayout> #include <QtWidgets/QGroupBox> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QListWidget> #include <QtWidgets/QPushButton> #include <QtWidgets/QSlider> #include <QtWidgets/QWidget> #include "myglwidget.h" QT_BEGIN_NAMESPACE class Ui_Window { public: QGridLayout *gridLayout; QHBoxLayout *horizontalLayout; MyGLWidget *myGLWidget; QLabel *lblZ; QSlider *horizontalSlider; QPushButton *btnRot; QPushButton *extrudeButton; QLabel *lblX; QLabel *lblY; QListWidget *listWidget; QGroupBox *groupBox; QLineEdit *lineEdit; QLabel *label; QLabel *label_2; QLabel *label_3; QLineEdit *lineEdit_2; QLineEdit *lineEdit_3; QPushButton *Create; QLineEdit *lineEdit_4; QLabel *label_4; QPushButton *pushButton; QPushButton *pushButton_2; QPushButton *pushButton_3; QPushButton *pushButton_4; QPushButton *pushButton_5; QPushButton *pushButton_6; QLineEdit *lineEdit_5; QLineEdit *lineEdit_6; QLineEdit *lineEdit_7; QLabel *label_5; QLineEdit *lineEdit_9; QLabel *label_6; QPushButton *pushButton_7; QPushButton *pushButton_8; QLineEdit *lineEdit_8; QLineEdit *lineEdit_10; QPushButton *pushButton_9; void setupUi(QWidget *Window) { if (Window->objectName().isEmpty()) Window->setObjectName(QStringLiteral("Window")); Window->resize(897, 596); gridLayout = new QGridLayout(Window); gridLayout->setSpacing(6); gridLayout->setContentsMargins(11, 11, 11, 11); gridLayout->setObjectName(QStringLiteral("gridLayout")); horizontalLayout = new QHBoxLayout(); horizontalLayout->setSpacing(6); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); myGLWidget = new MyGLWidget(Window); myGLWidget->setObjectName(QStringLiteral("myGLWidget")); myGLWidget->setMinimumSize(QSize(480, 480)); horizontalLayout->addWidget(myGLWidget); gridLayout->addLayout(horizontalLayout, 0, 4, 1, 1); lblZ = new QLabel(Window); lblZ->setObjectName(QStringLiteral("lblZ")); gridLayout->addWidget(lblZ, 4, 3, 1, 1); horizontalSlider = new QSlider(Window); horizontalSlider->setObjectName(QStringLiteral("horizontalSlider")); horizontalSlider->setOrientation(Qt::Horizontal); gridLayout->addWidget(horizontalSlider, 1, 3, 1, 1); btnRot = new QPushButton(Window); btnRot->setObjectName(QStringLiteral("btnRot")); gridLayout->addWidget(btnRot, 1, 4, 1, 1); extrudeButton = new QPushButton(Window); extrudeButton->setObjectName(QStringLiteral("extrudeButton")); extrudeButton->setContextMenuPolicy(Qt::NoContextMenu); gridLayout->addWidget(extrudeButton, 2, 4, 1, 1); lblX = new QLabel(Window); lblX->setObjectName(QStringLiteral("lblX")); gridLayout->addWidget(lblX, 2, 3, 1, 1); lblY = new QLabel(Window); lblY->setObjectName(QStringLiteral("lblY")); gridLayout->addWidget(lblY, 3, 3, 1, 1); listWidget = new QListWidget(Window); listWidget->setObjectName(QStringLiteral("listWidget")); gridLayout->addWidget(listWidget, 0, 3, 1, 1); groupBox = new QGroupBox(Window); groupBox->setObjectName(QStringLiteral("groupBox")); lineEdit = new QLineEdit(groupBox); lineEdit->setObjectName(QStringLiteral("lineEdit")); lineEdit->setGeometry(QRect(0, 30, 81, 20)); label = new QLabel(groupBox); label->setObjectName(QStringLiteral("label")); label->setGeometry(QRect(0, 10, 61, 20)); label_2 = new QLabel(groupBox); label_2->setObjectName(QStringLiteral("label_2")); label_2->setGeometry(QRect(0, 50, 47, 13)); label_3 = new QLabel(groupBox); label_3->setObjectName(QStringLiteral("label_3")); label_3->setGeometry(QRect(0, 83, 47, 20)); lineEdit_2 = new QLineEdit(groupBox); lineEdit_2->setObjectName(QStringLiteral("lineEdit_2")); lineEdit_2->setGeometry(QRect(0, 70, 81, 20)); lineEdit_3 = new QLineEdit(groupBox); lineEdit_3->setObjectName(QStringLiteral("lineEdit_3")); lineEdit_3->setGeometry(QRect(0, 100, 81, 20)); Create = new QPushButton(groupBox); Create->setObjectName(QStringLiteral("Create")); Create->setGeometry(QRect(0, 160, 81, 23)); lineEdit_4 = new QLineEdit(groupBox); lineEdit_4->setObjectName(QStringLiteral("lineEdit_4")); lineEdit_4->setGeometry(QRect(0, 140, 81, 20)); label_4 = new QLabel(groupBox); label_4->setObjectName(QStringLiteral("label_4")); label_4->setGeometry(QRect(0, 120, 47, 13)); pushButton = new QPushButton(groupBox); pushButton->setObjectName(QStringLiteral("pushButton")); pushButton->setGeometry(QRect(0, 190, 81, 23)); pushButton_2 = new QPushButton(groupBox); pushButton_2->setObjectName(QStringLiteral("pushButton_2")); pushButton_2->setGeometry(QRect(0, 210, 81, 23)); pushButton_3 = new QPushButton(groupBox); pushButton_3->setObjectName(QStringLiteral("pushButton_3")); pushButton_3->setGeometry(QRect(0, 250, 81, 23)); pushButton_4 = new QPushButton(groupBox); pushButton_4->setObjectName(QStringLiteral("pushButton_4")); pushButton_4->setGeometry(QRect(0, 270, 81, 23)); pushButton_5 = new QPushButton(groupBox); pushButton_5->setObjectName(QStringLiteral("pushButton_5")); pushButton_5->setGeometry(QRect(0, 380, 81, 23)); pushButton_6 = new QPushButton(groupBox); pushButton_6->setObjectName(QStringLiteral("pushButton_6")); pushButton_6->setGeometry(QRect(0, 450, 81, 23)); lineEdit_5 = new QLineEdit(groupBox); lineEdit_5->setObjectName(QStringLiteral("lineEdit_5")); lineEdit_5->setGeometry(QRect(0, 320, 81, 20)); lineEdit_6 = new QLineEdit(groupBox); lineEdit_6->setObjectName(QStringLiteral("lineEdit_6")); lineEdit_6->setGeometry(QRect(0, 340, 81, 20)); lineEdit_7 = new QLineEdit(groupBox); lineEdit_7->setObjectName(QStringLiteral("lineEdit_7")); lineEdit_7->setGeometry(QRect(0, 360, 81, 20)); label_5 = new QLabel(groupBox); label_5->setObjectName(QStringLiteral("label_5")); label_5->setGeometry(QRect(10, 300, 71, 20)); lineEdit_9 = new QLineEdit(groupBox); lineEdit_9->setObjectName(QStringLiteral("lineEdit_9")); lineEdit_9->setGeometry(QRect(0, 430, 81, 20)); label_6 = new QLabel(groupBox); label_6->setObjectName(QStringLiteral("label_6")); label_6->setGeometry(QRect(10, 410, 61, 16)); pushButton_7 = new QPushButton(groupBox); pushButton_7->setObjectName(QStringLiteral("pushButton_7")); pushButton_7->setGeometry(QRect(0, 510, 81, 23)); pushButton_8 = new QPushButton(groupBox); pushButton_8->setObjectName(QStringLiteral("pushButton_8")); pushButton_8->setGeometry(QRect(0, 550, 81, 23)); lineEdit_8 = new QLineEdit(groupBox); lineEdit_8->setObjectName(QStringLiteral("lineEdit_8")); lineEdit_8->setGeometry(QRect(0, 530, 81, 20)); lineEdit_10 = new QLineEdit(groupBox); lineEdit_10->setObjectName(QStringLiteral("lineEdit_10")); lineEdit_10->setGeometry(QRect(0, 470, 81, 20)); pushButton_9 = new QPushButton(groupBox); pushButton_9->setObjectName(QStringLiteral("pushButton_9")); pushButton_9->setGeometry(QRect(0, 490, 81, 23)); gridLayout->addWidget(groupBox, 0, 0, 5, 1); retranslateUi(Window); QMetaObject::connectSlotsByName(Window); } // setupUi void retranslateUi(QWidget *Window) { Window->setWindowTitle(QApplication::translate("Window", "Window", Q_NULLPTR)); lblZ->setText(QApplication::translate("Window", "TextLabel", Q_NULLPTR)); btnRot->setText(QApplication::translate("Window", "Auto Rotate", Q_NULLPTR)); extrudeButton->setText(QApplication::translate("Window", "Extrude", Q_NULLPTR)); lblX->setText(QApplication::translate("Window", "TextLabel", Q_NULLPTR)); lblY->setText(QApplication::translate("Window", "TextLabel", Q_NULLPTR)); groupBox->setTitle(QApplication::translate("Window", "INPUT BOXES", Q_NULLPTR)); label->setText(QApplication::translate("Window", "#of Rows", Q_NULLPTR)); label_2->setText(QApplication::translate("Window", "#of Col", Q_NULLPTR)); label_3->setText(QApplication::translate("Window", "depth", Q_NULLPTR)); Create->setText(QApplication::translate("Window", "Create", Q_NULLPTR)); label_4->setText(QApplication::translate("Window", "width", Q_NULLPTR)); pushButton->setText(QApplication::translate("Window", "Wired", Q_NULLPTR)); pushButton_2->setText(QApplication::translate("Window", "Solid", Q_NULLPTR)); pushButton_3->setText(QApplication::translate("Window", "Top View", Q_NULLPTR)); pushButton_4->setText(QApplication::translate("Window", "Z Side View", Q_NULLPTR)); pushButton_5->setText(QApplication::translate("Window", "new color", Q_NULLPTR)); pushButton_6->setText(QApplication::translate("Window", "change height", Q_NULLPTR)); label_5->setText(QApplication::translate("Window", "color x,y,z", Q_NULLPTR)); label_6->setText(QApplication::translate("Window", "input Height", Q_NULLPTR)); pushButton_7->setText(QApplication::translate("Window", "Fractalize", Q_NULLPTR)); pushButton_8->setText(QApplication::translate("Window", "Sub Divide", Q_NULLPTR)); pushButton_9->setText(QApplication::translate("Window", "cap height", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class Window: public Ui_Window {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_WINDOW_H
// // Created by bodand on 2019-12-22. // #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wused-but-marked-unused" #pragma once #pragma clang diagnostic push #pragma ide diagnostic ignored "MemberFunctionCanBeStaticInspection" #pragma ide diagnostic ignored "cert-err58-cpp" #include <boost/test/included/unit_test.hpp> BOOST_AUTO_TEST_SUITE(Trivial) BOOST_AUTO_TEST_CASE(FrameworkTest) { BOOST_CHECK_MESSAGE(true, "Your Boost is properly installed"); } BOOST_AUTO_TEST_SUITE_END() #pragma clang diagnostic pop #pragma clang diagnostic pop
// // PlistHandler.cpp // Aircraft // // Created by lc on 11/27/14. // // #include "PlistHandler.h" PlistHandler* PlistHandler::m_instance = NULL; PlistHandler::Delete PlistHandler::m_delete; PlistHandler::PlistHandler() { init(); } PlistHandler::~PlistHandler() { } PlistHandler* PlistHandler::getInstance() { if (m_instance == NULL) { m_instance = new PlistHandler(); } return m_instance; } void PlistHandler::init() { //png加入全局cache中 frameCache = SpriteFrameCache::getInstance(); frameCache->addSpriteFramesWithFile("shoot_background.plist"); frameCache->addSpriteFramesWithFile("shoot.plist"); animationCache = AnimationCache::getInstance(); //game loading Animation* animationLoading = Animation::create(); animationLoading->setDelayPerUnit(0.2f); animationLoading->addSpriteFrame(frameCache->getSpriteFrameByName("game_loading1.png")); animationLoading->addSpriteFrame(frameCache->getSpriteFrameByName("game_loading2.png")); animationLoading->addSpriteFrame(frameCache->getSpriteFrameByName("game_loading3.png")); animationLoading->addSpriteFrame(frameCache->getSpriteFrameByName("game_loading4.png")); animationCache->addAnimation(animationLoading, "loading"); // plane fly Animation* animationPlane = Animation::create(); animationPlane->setDelayPerUnit(0.1f); animationPlane->addSpriteFrame(frameCache->getSpriteFrameByName("hero1.png")); animationPlane->addSpriteFrame(frameCache->getSpriteFrameByName("hero2.png")); animationCache->addAnimation(animationPlane, "plane"); // plane blowup Animation* animationPlaneBlowup = Animation::create(); animationPlaneBlowup->setDelayPerUnit(0.1f); animationPlaneBlowup->addSpriteFrame(frameCache->getSpriteFrameByName("hero_blowup_n1.png")); animationPlaneBlowup->addSpriteFrame(frameCache->getSpriteFrameByName("hero_blowup_n2.png")); animationPlaneBlowup->addSpriteFrame(frameCache->getSpriteFrameByName("hero_blowup_n3.png")); animationPlaneBlowup->addSpriteFrame(frameCache->getSpriteFrameByName("hero_blowup_n4.png")); animationCache->addAnimation(animationPlaneBlowup, "planeBlowup"); // enemy3 fly Animation* animationEnemy3 = Animation::create(); animationEnemy3->setDelayPerUnit(0.2f); animationEnemy3->addSpriteFrame(frameCache->getSpriteFrameByName("enemy3_n1.png")); animationEnemy3->addSpriteFrame(frameCache->getSpriteFrameByName("enemy3_n2.png")); animationCache->addAnimation(animationEnemy3, "enemy3"); // enemy1 down Animation* animationEnemy1Blowup = Animation::create(); animationEnemy1Blowup->setDelayPerUnit(0.1f); animationEnemy1Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy1_down1.png")); animationEnemy1Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy1_down2.png")); animationEnemy1Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy1_down3.png")); animationEnemy1Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy1_down4.png")); animationCache->addAnimation(animationEnemy1Blowup, "enemy1Blowup"); Animation* animationEnemy2Blowup = Animation::create(); animationEnemy2Blowup->setDelayPerUnit(0.1f); animationEnemy2Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy2_down1.png")); animationEnemy2Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy2_down2.png")); animationEnemy2Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy2_down3.png")); animationEnemy2Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy2_down4.png")); animationCache->addAnimation(animationEnemy2Blowup, "enemy2Blowup"); Animation* animationEnemy3Blowup = Animation::create(); animationEnemy3Blowup->setDelayPerUnit(0.1f); animationEnemy3Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy3_down1.png")); animationEnemy3Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy3_down2.png")); animationEnemy3Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy3_down3.png")); animationEnemy3Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy3_down4.png")); animationEnemy3Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy3_down5.png")); animationEnemy3Blowup->addSpriteFrame(frameCache->getSpriteFrameByName("enemy3_down6.png")); animationCache->addAnimation(animationEnemy3Blowup, "enemy3Blowup"); } SpriteFrame* PlistHandler::getFrameByName(const string& name) { return frameCache->getSpriteFrameByName(name); } Animation* PlistHandler::getAnimationByName(const string& name) { return animationCache->getAnimation(name); }
#ifndef PIONEERCONNECTION_H #define PIONEERCONNECTION_H #include "data_types/pioneer.h" #include "data_types/computer.h" #include <QCoreApplication> #include <QtSql> #include <QDebug> #include <QFileInfo> #include <string> #include <sstream> #include <fstream> #include <iostream> #include <vector> class PioneerConnection { public: PioneerConnection(); // Default constructor, creates connection with SQLite database vector<Pioneer> getPioneerList(); // Returns pioneers vector vector<Pioneer> getPioneerTrash(); // Returns pioneer vector from trash Pioneer getPioValuesFromDB(QSqlQuery query); //gets the pioneer values and returns them void addToPioTable(Pioneer pioneer); // Adds list vector to Pioneers table in SQL database vector<Pioneer> getPioneerListAsc(); // Returns pioneers vector but with the name in ascending order vector<Pioneer> getPioneerListDesc(); // Returns pioneers vector but with the name in descending order string convertToString(int year); // Converts integers to strings void removePioneer(); // Deletes a single pioneer from table void deleteAllPioneers(); // Deletes the entire table void editPioneer(Pioneer pio); // Edits information already in table int getHighestId(); // Returns highest id in Pioneers table (most recently added entry) vector<Pioneer> printQueryPioneers(string sex, string dYear, string orderCol, string order); // Gets input from Print menu in interface and returns what the user wants to see printed vector<Pioneer> searchPio(string searchWord, string searchBy, string sex, string vitalStatus, string orderBy, string direction); // Searches through database for a name of pioneer that matches a search word void pioneerToTrash(Pioneer pio); // Sets delete flag to "true" void removeSinglePioneer(Pioneer pio); // Removes pio from SQL database private: vector<Pioneer> pioneers; // Vector that holds onto all information on runtime Pioneer temp; QSqlQuery query; // Object used to send query to SQLite database }; #endif // PIONEERCONNECTION_H
#include "Globals.h" #include "Application.h" #include "ModuleTextures.h" #include "ModuleFadeToBlack.h" #include "ModuleSceneIntro.h" #include "ModuleRender.h" #include "ModulePlayer.h" #include "ModuleInput.h" #include "ModuleAudio.h" #include "SDL\include\SDL_render.h" #include "SDL/include/SDL_timer.h" #include "ModuleWelcomeScreen.h" #include "WinScreen.h" #include "ModuleSceneLoose.h" #include"ModulePowerUPS.h" #include "CharSelec.h" ModuleSceneIntro::ModuleSceneIntro() { // Psikyo s1 = {1730,0,323,227 }; s2 = {462,0,323,227 }; s3 = {827,0,323,227 }; s4 = {1183,0,323,227 }; s5 = {0,326,323,224 }; s6 = {450,347,323,227 }; s7 = {806,347,323,227 }; s8 = {1162,347,323,227 }; s9 = {57,665,323,227 }; s10 = {451,665,323,227 }; s11 = {807,665,323,227 }; s12 = {1163,665,323,227 }; s13= { 47,963,323,227 }; s14= { 441,963,323,227 }; s15 = { 797,963 ,323,227 }; s16= {1153,963,323,227 }; s17 = {47,1247,323,227 }; s18 = {441,1247,323,227 }; s19 = {797,1247,323,227 }; s20 = {1165,1247,323,227 }; } ModuleSceneIntro::~ModuleSceneIntro() {} bool ModuleSceneIntro::Init() { App->scene_start->Disable(); App->scene_win->Disable(); App->scene_loose->Disable(); App->powerup->Disable(); App->charmenu->Disable(); return true; } // Load assets bool ModuleSceneIntro::Start() { LOG("Loading Intro"); graphics = App->textures->Load("assets/sprites/Scenes/Scene_Intro/Psikyo.png"); //Mix_PlayMusic(mus, -1); time_on_entry = SDL_GetTicks(); return true; } // UnLoad assets bool ModuleSceneIntro::CleanUp() { LOG("Unloading Intro"); App->textures->Unload(graphics); graphics = nullptr; return true; } // Update: draw background update_status ModuleSceneIntro::Update() { //Timer current_time = SDL_GetTicks() - time_on_entry; // Draw everything -------------------------------------- App->render->Blit(graphics, 0, 0, &Psikyo, 0.00f); if (current_time <= 100) App->render->Blit(graphics, 0, 0, &s1); else if (current_time > 100 &&current_time <= 200) App->render->Blit(graphics, 0, 0, &s2); else if (current_time > 200 && current_time <= 300) App->render->Blit(graphics, 0, 0, &s3); else if (current_time > 300 && current_time <= 400) App->render->Blit(graphics, 0, 0, &s4); else if (current_time > 400 && current_time <= 500) App->render->Blit(graphics, 0, 0, &s5); else if (current_time > 500 && current_time <= 600) App->render->Blit(graphics, 0, 0, &s6); else if (current_time > 600 && current_time <= 700) App->render->Blit(graphics, 0, 0, &s7); else if (current_time > 700 && current_time <= 800) App->render->Blit(graphics, 0, 0, &s8); else if (current_time > 800 && current_time <= 900) App->render->Blit(graphics, 0, 0, &s9); else if (current_time > 900 && current_time <= 1000) App->render->Blit(graphics, 0, 0, &s10); else if (current_time > 1000 && current_time <= 1100) App->render->Blit(graphics, 0, 0, &s11); else if (current_time > 1100 && current_time <= 1200) App->render->Blit(graphics, 0, 0, &s12); else if (current_time > 1200 && current_time <= 1300) App->render->Blit(graphics, 0, 0, &s13); else if (current_time > 1300 && current_time <= 1400) App->render->Blit(graphics, 0, 0, &s14); else if (current_time > 1400 && current_time <= 1500) App->render->Blit(graphics, 0, 0, &s15); else if (current_time > 1500 && current_time <= 1600) App->render->Blit(graphics, 0, 0, &s16); else if (current_time > 1600 && current_time <= 1700) App->render->Blit(graphics, 0, 0, &s17); else if (current_time > 1700 && current_time <= 1800) App->render->Blit(graphics, 0, 0, &s18); else if (current_time > 1800 && current_time <= 1900) App->render->Blit(graphics, 0, 0, &s19); else if (current_time > 1900 && current_time <= 3500) App->render->Blit(graphics, 0, 0, &s20); // If pressed, change scene if (App->input->keyboard[SDL_SCANCODE_RETURN] == KEY_STATE::KEY_DOWN || current_time>3499 || App->input->controller_START_button == KEY_STATE::KEY_DOWN) { //Mix_PlayChannel(-1, start, 0); App->fade->FadeToBlack(App->scene_intro, App->scene_start, 0.50f); } return UPDATE_CONTINUE; }
#include <iostream> #include <string> using namespace std; void order_numbers(){ float numbers[10]; for (int i = 0; i < 10; i++){ cout<<"Ingresa un numero: "; cin>>numbers[i]; } float temporal; for (int i = 0;i < 10; i++){ for (int j = 0; j< 10-1; j++){ if (numbers[j] < numbers[j+1]){ temporal = numbers[j]; numbers[j] = numbers[j+1]; numbers[j+1] = temporal; } } } float max[3]; float min[3]; int j=9; for (int i = 0; i < 3; i++){ min[i] = numbers[j]; j--; } for (int i = 0; i < 3; i++){ cout<<min[i]<<endl; } j=0; for (int i = 0; i < 3; i++){ max[i] = numbers[j]; j++; } for (int i = 0; i < 3; i++){ cout<<max[i]<<endl; } } void operations(float number1, float number2){ float div = number1/number2; cout<<"Suma: "<<number1+number2<<endl; cout<<"Resta: "<<number1-number2<<endl; cout<<"Multiplicion: "<<number1*number2<<endl; cout<<"Division: "<<div<<endl; } string type_of_triangle(float side1, float side2, float side3){ if (side1 == side2 && side2 == side3){ return "equilatero"; } else if ((side1 == side2 && side2 != side3) || (side1 == side3 && side1 != side2) || (side2 == side3 && side2 != side1)){ return "isoceles"; } else if (side1 != side2 && side2 != side3){ return "escaleno"; } } int main(){ float s1, s2, s3; float n1, n2; cout<<"Ingrese el lado 1 del triangulo: "; cin>>s1; cout<<"Ingrese el lado 2 del triangulo: "; cin>>s2; cout<<"Ingrese el lado 3 del triangulo: "; cin>>s3; cout<<"Es un triangulo "<<type_of_triangle(s1, s2, s3)<<endl; order_numbers(); cout<<"Ingrese un numero: "; cin>>n1; cout<<"Ingrese otro numero: "; cin>>n2; operations(n1, n2); }
// // sudokuMain.cpp // // // Created by Juha Kreula on 23/01/2020. // #include <stdio.h> #include <iostream> #include <algorithm> #include <cctype> #include "sudokuGrid.hpp" #include "sudokuSolver.hpp" using std::cout, std::cin, std::endl; // Overloaded output operator for Grid std::ostream & operator<<(std::ostream & out, Grid & grid) { std::for_each (grid.array.begin(), grid.array.end(), [&out,&grid](std::vector<int> & row) { for (int col=0; col < grid.cols; ++col) { if (row[col] == 0) out << "- "; else out << row[col] << " "; } out << endl; }); return out; } int main(int argc, char* argv[]) { const int size = 9; Grid grid(size); char ans; cout << "Give non-empty Sudoku grid cells on command line? (y/n)" << endl; cin >> ans; while (std::tolower(ans) != 'y' && std::tolower(ans) != 'n') { cout << "Type 'y' for yes or 'n' for no." << endl; cin >> ans; } if( std::tolower(ans) == 'y' ) { grid.fillEmptyWithZeros(); cout << "Give info on non-empty grid cells.\n"; int row, col, value; while(true) { cout << "Row number (1,...,9, or type -1 if done):\n"; cin >> row; if (row == -1) break; cout << "Column number (1,..,9):\n"; cin >> col; cout << "Cell value (1,..,9):\n"; cin >> value; /* We are asking the user row and col numbers between 1 and 9 (easier to picture this way), but the actual indices are between 0 and 8, so we need to take 1 out of the row and col given by the user. */ grid[--row][--col] = value; } } else { // Alternatively give full grid here. 0 means empty cell. // This is an example grid. grid = {{0, 0, 3, 0, 1, 0, 0, 0, 6}, {9, 0, 0, 0, 0, 0, 0, 5, 0}, {1, 5, 0, 0, 0, 9, 0, 0, 8}, {0, 0, 0, 5, 0, 0, 8, 1, 0}, {0, 0, 0, 9, 0, 4, 0, 0, 0}, {0, 8, 6, 0, 0, 2, 0, 0, 0}, {5, 0, 0, 3, 0, 0, 0, 8, 2}, {0, 4, 0, 0, 0, 0, 0, 0, 7}, {6, 0, 0, 0, 7, 0, 1, 0, 0}}; } cout << "\nInput:" << endl; cout << grid << endl; // Solver object corresponding to given grid. Solver solver(grid); if (solver.solveBacktracking() == true) { cout << "\nSolution:" << endl; cout << solver.getGrid() << endl; } else { cout << "No solution found." << endl; } cout << "The solution required " << solver.getCycles() << " backtracking cycles." << endl; return 0; }
#ifndef RECGANDDRAW_H #define RECGANDDRAW_H #include "opencv2/imgcodecs/imgcodecs.hpp" #include "opencv2/opencv.hpp" #include "opencv2/core/core.hpp" extern float ex; extern float ey; extern float er; class recganddraw { public: recganddraw(); void showl(); protected: }; #endif // RECGANDDRAW_H
// GameLibrary.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "GameLib.h" int ola=0; void Teste() { if (ola == 0) { _tprintf(TEXT("TESTE -- 1")); ola++; } else if (ola == 1) { _tprintf(TEXT("TESTE -- 2")); ola++; } else { _tprintf(TEXT("TESTE -- 3")); } return; }
#include "player/Player.h" #include "FileRecordThread.h" CLASS_LOG_IMPLEMENT(CFileRecordThread, "CRecordThread[file]"); /////////////////////////////////////////////////////////////////// int CFileRecordThread::PrepareWrite() { m_Mp4file->Start(); return CMediaRecorder::PrepareWrite(); } int CFileRecordThread::Write(int index, AVPacket *pPacket) { if( m_ref < 0 ) m_ref = pPacket->pts; if( pPacket->pts > m_now ) m_now = pPacket->pts; m_Mp4file->Write(index==0? AVMEDIA_TYPE_VIDEO:AVMEDIA_TYPE_AUDIO, pPacket); m_nframes[index] ++; return 0; }
#include <iostream> #include "FactoryMachineState.h" #include "FactoryMachine.h" #include "Event.h" using namespace std; void FactoryMachineState::Enter() { } void FactoryMachineState::Execute(FactoryMachine* player) { if (isFactoryMachine_PowerOn) { cout << "장비를 동작 중..." << endl; } } void FactoryMachineState::Exit() { } bool FactoryMachineState::OnEvent(FactoryMachine* agent, const Event& event_src) { switch (event_src.etType) { case ET_Machine_Power_Up: isFactoryMachine_PowerOn = true; break; case ET_Machine_Power_Down: isFactoryMachine_PowerOn = false; break; default: break; } return false; }
#include <iostream> #include <vector> using namespace std; int a, b, c, d, e, f, g, h; int get_value(char x) { switch (x) { case 'A': return a; case 'B': return b; case 'C': return c; case 'D': return d; case 'E': return e; case 'F': return f; case 'G': return g; case 'H': return h; } return 0; }void dead(char x) { switch (x) { case 'A': a--; break; case 'B': b--; break; case 'C': c--; break; case 'D': d--; break; case 'E': e--; break; case 'F': f--; break; case 'G': g--; break; case 'H': h--; break; } } bool check(string str) { if ((get_value(str[0]) > 0) && (get_value(str[1]) > 0)) { dead(str[0]); dead(str[1]); return true;} return false; } int main() { cin >> a >> b >> c >> d >> e >> f >> g >> h; vector<string> path{ "DH", "DH-", "DA", "DA-", "DC", "DC-", "DF", "AB+\nDA-\nFB-", "HD", "HD-", "HE", "HE-", "HG", "HG-", "HB", "EF+\nHE-\nFB-", "EH", "EH-", "EA", "EA-", "EF", "EF-", "EC", "FB+\nEF-\nBC-", "AD", "AD-", "AE", "AE-", "AB", "AB-", "AG", "FB+\nAB-\nFG-", "FE", "FE-", "FB", "FB-", "FG", "FG-", "FD", "EA+\nFE-\nDA-", "BA", "BA-", "BF", "BF-", "BC", "BC-", "BH", "EA+\nBA-\nHE-", "GF", "GF-", "GC", "GC-", "GH", "GH-", "GA", "EF+\nGF-\nAE-", "CG", "CG-", "CB", "CB-", "CD", "CD-", "CE", "AB+\nCB-\nAE-"}; string ans; if ((e + b + d + g != a + f + c + h)) { cout << "IMPOSSIBLE"; return 0; } for (int i = 0; i < path.size(); i += 2) { while (check(path[i])) { ans += path[i + 1] + "\n"; } } cout << ans; return 0; }
int a=7,b=6,c=5,d=11,e=10,f=8,g=9,dp=4; int n[10][8]={{1,0,0,0,0,1,0,0},{1,0,0,1,1,1,1,1},{1,1,0,0,1,0,0,0},{1,0,0,0,1,0,1,0},{1,0,0,1,0,0,1,1},{1,0,1,0,0,0,1,0},{1,0,1,0,0,0,0,0},{1,0,0,0,1,1,1,1},{1,0,0,0,0,0,0,0},{1,0,0,0,0,0,1,0}}; int alg[10][8]={{0,0,0,0,0,1,0,0},{0,0,0,1,1,1,1,1},{0,1,0,0,1,0,0,0},{0,0,0,0,1,0,1,0},{0,0,0,1,0,0,1,1},{0,0,1,0,0,0,1,0},{0,0,1,0,0,0,0,0},{0,0,0,0,1,1,1,1},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,1,0}}; int diao[3][8]={{0,393,441,495,556,624,661,742},/*G中*/ {0,786,882,990,1049,1178,1322,1484},/*G高*/ {0,262,294,330,350,393,441,495}};/*C中*/ int qu1[15]={3,3,4,5,5,4,3,2,1,1,2,3,3,2,2}; int qu2[16]={1,2,3,5,1,3,3,0,2,1,2,5,5,5,5,0}; int duration2[16]; int qu_flag=2; int flag=1; int song_change=0; void setup() { for(int i=0;i<6;i++) duration2[i]=250; duration2[6]=500; duration2[14]=500; for(int i=8;i<14;i++) duration2[i]=250; duration2[7]=125;duration2[15]=125; pinMode(12,OUTPUT); pinMode(13,INPUT); for(int i=4;i<12;i++){ pinMode(i,OUTPUT); } pinMode(2,INPUT); pinMode(3,INPUT); //attachInterrupt(digitalPinToInterrupt(2),gdadiao,RISING); attachInterrupt(digitalPinToInterrupt(3),csong,RISING); } void gdadiao(){ if (flag%2==0){ for(int i=0;i<1000;i++){ delayMicroseconds(200); } while(!digitalRead(2)){ } qu_flag=0; } flag++; } void csong(){ song_change=1; } void loop() { if(digitalRead(2)==HIGH){ for(int i=0;i<15;i++){ if(song_change==0){ tone(12,diao[qu_flag][qu1[i]]); for(int j=4;j<12;j++){ digitalWrite(j,n[qu1[i]][j-4]); } delay(250); } else{break;} } song2(); } } void song2(){ for(int i=0;i<16;i++){ if(i==3){ tone(12,diao[0][qu2[3]]); delay(duration2[3]); for(int j=4;j<12;j++) digitalWrite(j,n[qu2[3]][j-4]); } else{ tone(12,diao[1][qu2[i]]); delay(duration2[i]); for(int j=4;j<12;j++){ digitalWrite(j,alg[qu2[i]][j-4]); } } } }
// // Created by payaln on 27.02.2019. // #include "DataSaver.h" std::ofstream DataSaver::out; std::string DataSaver::splitter = " "; void DataSaver::CreateFile(const std::string& filename) { out.open(filename); } void DataSaver::OpenFile(const std::string& filename) { out.open(filename, std::ios::app); } void DataSaver::CloseFile() { out << std::endl; out.close(); } void DataSaver::SetSplitter(const std::string& s) { splitter = s; } std::string DataSaver::GetSplitter() { return splitter; } void DataSaver::AddData(const std::vector<double>& data) { for (const auto& d : data) { out << d << splitter; } out << std::endl; } void DataSaver::SaveSpectre(const std::string &filename, const std::map<double, double> &data) { std::ofstream out_s(filename); // for (const auto& [ch, cnt] : data) { // out << ch << splitter << cnt << std::endl; // } for (const auto& d : data) { out_s << d.first << splitter << d.second << std::endl; } out_s.close(); }
#include<bits/stdc++.h> #define ll long long int #define v vector using namespace std; struct AVLNode { ll data; AVLNode* lc; AVLNode* rc; ll height,num; }; AVLNode* AVLCreate(ll k) { AVLNode* temp = new AVLNode; temp->lc = NULL; temp->rc = NULL; temp->height = 0; temp->num = 1; temp->data = k; return temp; } ll AVLNum(AVLNode* node) { if(node==NULL) return 0; else return node->num; } ll AVLHeight(AVLNode* node) { if(node==NULL) return -1; else return node->height; } ll AVLBalance(AVLNode* node) { if(node==NULL) return 0; else return AVLHeight(node->lc) - AVLHeight(node->rc); } AVLNode* AVLRRotate(AVLNode* node) { AVLNode* tnode = node->lc; AVLNode* rtnode = tnode->rc; tnode->rc = node; node-> lc = rtnode; node->height = 1 + max(AVLHeight(node->lc),AVLHeight(node->rc)); tnode->height = 1 + max(AVLHeight(tnode->lc),AVLHeight(tnode->rc)); node->num = 1 + AVLNum(node->lc)+AVLNum(node->rc); tnode->num = 1 + AVLNum(tnode->lc)+AVLNum(tnode->rc); return tnode; } AVLNode* AVLLRotate(AVLNode* node) { AVLNode* tnode = node->rc; AVLNode* ltnode = tnode->lc; tnode->lc = node; node-> rc = ltnode; node->height = 1 + max(AVLHeight(node->lc),AVLHeight(node->rc)); tnode->height = 1 + max(AVLHeight(tnode->lc),AVLHeight(tnode->rc)); node->num = 1 + AVLNum(node->lc)+AVLNum(node->rc); tnode->num = 1 + AVLNum(tnode->lc)+AVLNum(tnode->rc); return tnode; } AVLNode* AVLInsert(AVLNode* node,ll k) { if(node==NULL) return AVLCreate(k); if(k<=node->data) node->lc = AVLInsert(node->lc,k); else if (k>node->data) node->rc = AVLInsert(node->rc,k); else return node; node->height = 1 + max(AVLHeight(node->lc),AVLHeight(node->rc)); ll balance = AVLBalance(node); node->num = 1 + AVLNum(node->lc)+AVLNum(node->rc); if(balance > 1) { if(k <= (node->lc)->data) return AVLRRotate(node); if(k > (node->lc)->data) { node->lc = AVLLRotate(node->lc); return AVLRRotate(node); } } if(balance < -1) { if(k > (node->rc)->data) return AVLLRotate(node); if(k <= (node->rc)->data) { node->rc = AVLRRotate(node->rc); return AVLLRotate(node); } } return node; } AVLNode* AVLMinValueNode(AVLNode* node) { AVLNode* cur = node; while(cur->lc!=NULL) cur = cur->lc; return cur; } AVLNode* AVLDelete(AVLNode* root,ll k) { if(root == NULL) return root; if(k < root->data) root->lc = AVLDelete(root->lc,k); else if (k > root->data) root->rc = AVLDelete(root->rc,k); else { if(root->lc==NULL || root->rc==NULL) { if(root->lc==NULL && root->rc==NULL) { AVLNode* temp = root; root = NULL; free(temp); } else { AVLNode* temp = root->lc ? root->lc : root->rc; *root = *temp; free(temp); } } else { AVLNode* temp = AVLMinValueNode(root); root->data = temp->data; root->rc = AVLDelete(root->rc,temp->data); } } if(root==NULL) return root; root->num = 1 + AVLNum(root->lc)+AVLNum(root->rc); root->height = 1 + max(AVLHeight(root->lc),AVLHeight(root->rc)); ll balance = AVLBalance(root); if(balance > 1) { if(AVLBalance(root->lc)>=0) return AVLRRotate(root); if(AVLBalance(root->lc)<0) { root->lc = AVLLRotate(root->lc); return AVLRRotate(root); } } if(balance < -1) { if(AVLBalance(root->rc)<=0) return AVLLRotate(root); if(AVLBalance(root->rc)>0) { root->rc = AVLRRotate(root->rc); return AVLLRotate(root); } } return root; } void Preorder(AVLNode* root) { if(root!=NULL) { cout<<root->data<<" "<<root->num<<"\n"; Preorder(root->lc); Preorder(root->rc); } } int main() { AVLNode *root = NULL; root = AVLInsert(root, 9); root = AVLInsert(root, 5); root = AVLInsert(root, 10); root = AVLInsert(root, 0); root = AVLInsert(root, 6); root = AVLInsert(root, 11); root = AVLInsert(root, -1); root = AVLInsert(root, 1); root = AVLInsert(root, 2); cout << "Preorder traversal of the constructed AVL tree is \n"; Preorder(root); root = AVLDelete(root, 10); cout<<"\nPreorder traversal after deletion of 10 \n"; Preorder(root); return 0; }
#include <iostream> #include <string> #include <sstream> using namespace std; int main() { int N; stringstream ss; cin >> N; for(int i=N; i>0; i--) { ss << i << '\n'; } cout << ss.str(); return 0; }
#include <iostream> using namespace std; int getHalf(int num) { if(num == 1) { return 1; } if(num % 2) { return num / 2 + 1; } else { return num / 2; } } int main() { int day = 0; int num = 0; int overflow = 0; int sum = 0; int temp = 0; // input cin>>day>>num; // if one day if(day == 1) { cout<<num<<endl; return 0; } // else for(int i = 1; i <= num; i++) { sum += i; temp = i; for(int j = 1; j < day; j++) { sum += getHalf(temp); temp = getHalf(temp); } if(sum > num) { overflow = i - 1; break; } sum = 0; } cout<<overflow<<endl; return 0; }
#include <iostream> #include <vector> #include <string> #include <sstream> #include <map> #include <list> #include <tuple> #include <algorithm> using std::string; using std::vector; struct Query { string type, name; int number; }; std::ostream& operator << (std::ostream& out, Query q) { out << q.type << "," << q.number << "," << q.name; } template <int p, int a, int b> int hashf(int m, int x) { return ((a*x + b) % p) % m; } template <typename TKey, typename TValue> struct Hashmap { bool get(TKey key, TValue& out) const { // std::cout << "get" << std::endl; auto i = hash(key); auto& t = *table[i]; auto it = std::find_if(t.begin(), t.end(), [&](const std::tuple<TKey,TValue>& x){return std::get<0>(x) == key;}); if(it != t.end()) { out = std::get<1>(*it); return true; } else { return false; } } void set(TKey key, TValue value) { auto i = hash(key); auto& t = *table[i]; auto it = std::find_if(t.begin(), t.end(), [&](const std::tuple<TKey,TValue>& x){return std::get<0>(x) == key;}); if(it != t.end()) { t.erase(it); } t.emplace_back(key,value); } void remove(TKey key) { auto i = hash(key); auto& t = *table[i]; // std::cout << "remove" << std::endl; auto it = std::find_if(t.begin(), t.end(), [&](const std::tuple<TKey,TValue>& x){return std::get<0>(x) == key;}); if(it != t.end()) { t.erase (it); } } int hash(TKey key) const { return hashf<10000019, 34, 2>(m, key); } Hashmap() : m(1000) { table.reserve(m); for(int i = 0;i < 1000;++i) { table[i] = new std::list< std::tuple<TKey,TValue> >(); } } int m; std::vector< std::list< std::tuple<TKey,TValue> >* > table; }; vector<Query> read_queries(std::istream& in) { int n; in >> n; vector<Query> queries(n); for (int i = 0; i < n; ++i) { in >> queries[i].type; if (queries[i].type == "add") in >> queries[i].number >> queries[i].name; else in >> queries[i].number; } return queries; } void write_responses(std::ostream& out, const vector<string>& result) { for (size_t i = 0; i < result.size(); ++i) out << result[i] << "\n"; } vector<string> process_queries(const vector<Query>& queries) { Hashmap<int, std::string> table; vector<string> result; // Keep list of all existing (i.e. not deleted yet) contacts. vector<Query> contacts; for (size_t i = 0; i < queries.size(); ++i) { auto q = queries[i]; // std::cout << q << std::endl; if (q.type == "add") { table.set(q.number, q.name); // bool was_founded = false; // // if we already have contact with such number, // // we should rewrite contact's name // for (size_t j = 0; j < contacts.size(); ++j) // if (contacts[j].number == queries[i].number) { // contacts[j].name = queries[i].name; // was_founded = true; // break; // } // // otherwise, just add it // if (!was_founded) // contacts.push_back(queries[i]); } else if (q.type == "del") { table.remove(q.number); // for (size_t j = 0; j < contacts.size(); ++j) // if (contacts[j].number == queries[i].number) { // contacts.erase(contacts.begin() + j); // break; // } } else { string response = "not found"; table.get(q.number, response); result.push_back(response); // for (size_t j = 0; j < contacts.size(); ++j) // if (contacts[j].number == queries[i].number) { // response = contacts[j].name; // break; // } // result.push_back(response); } } return result; } void run(std::istream& in, std::ostream& out) { write_responses(out, process_queries(read_queries(in))); } #ifdef UNITTESTS #define CATCH_CONFIG_MAIN #include "../../catch.hpp" void test(const std::string strin, const std::string strExpectedOut) { auto instream = std::stringstream{strin}; auto expectedOutstream = std::stringstream{strExpectedOut}; auto outstream = std::stringstream{}; run(instream,outstream); std::cout << strExpectedOut << std::endl; std::cout << "-------------------" << std::endl; std::cout << outstream.str() << std::endl; std::cout << "-------------------" << std::endl; outstream.seekg(0); std::string expected, actual; while(!outstream.eof()) { std::getline(expectedOutstream, expected); std::getline(outstream, actual); REQUIRE(expected == actual); } } TEST_CASE("","") { test(R"(12 add 911 police add 76213 Mom add 17239 Bob find 76213 find 910 find 911 del 910 del 911 find 911 find 76213 add 76213 daddy find 76213)",R"(Mom not found police not found Mom daddy )"); test(R"(8 find 3839442 add 123456 me add 0 granny find 0 find 123456 del 0 del 0 find 0)", R"(not found granny me not found )"); } #else int main() { run(std::cin, std::cout); return 0; } #endif
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #include "GameFramework/GameMode.h" #include "CombatGrid.h" #include "ParentCombatCharacter.h" #include "Project_152GameMode.generated.h" // The GameMode defines the game being played. It governs the game rules, scoring, what actors // are allowed to exist in this game type, and who may enter the game. // // This game mode just sets the default pawn to be the MyCharacter asset, which is a subclass of Project_152Character UCLASS(minimalapi) class AProject_152GameMode : public AGameMode { GENERATED_BODY() public: AProject_152GameMode(); //This will start the combat. Pass through the characters involved and which grid its on // UFUNCTION(BlueprintCallable, Category = Combat) // void StartCombat(TArray<AParentCombatCharacter*> CharactersInCombat, ACombatGrid* GridRef); virtual void Tick(float DeltaSeconds) override; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat) bool bInCombat = false; //Set this when units are spawned. Keeps track of all the actors/characters in combat UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat) TArray<AParentCombatCharacter*> CharactersInCombat; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat) ACombatGrid* GridRef; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat) int32 TurnIncrement = 0; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat) bool bTakeTurn; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat) bool bNextTurn; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Stat) bool bDoneWithMove; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Stat) bool bDoneWithAttack; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Stat) int32 UniqueItemID = 0; UFUNCTION(BlueprintNativeEvent, Category = WinCondition) void WinExecution(); // Dummy event UFUNCTION(BlueprintNativeEvent, Category = WinCondition) void LossExecution(); // Dummy event UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Level) FString CurrentLevelName; UFUNCTION(BlueprintCallable, Category = WinCondition) void ProcessWin(int32 inputExperience, int32 currencytoadd); UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Stat) TArray<int32> ExperienceBrackets; UFUNCTION(BlueprintCallable, Category = WinCondition) void CheckForLevelUP(FInventoryItemStruct ItemIn, int32 arrayindex); };
/* ** EPITECH PROJECT, 2021 ** B-CPP-300-STG-3-1-CPPrush3-maxime.owaller ** File description: ** Shape */ #include "RectShape.hpp" #include "WindowManager.hpp" #include "Itop.hpp" #define TITLE_SECTION(n) {_rectangleShape.getPosition().x + 20, _rectangleShape.getPosition().y - n } RectShape::RectShape(sf::Vector2f position, sf::Vector2f size, sf::Color color, int thickness) noexcept { _rectangleShape.setSize(size); _rectangleShape.setFillColor(color); _rectangleShape.setOutlineColor(EDGE_COLOR); _rectangleShape.setOutlineThickness(thickness); _rectangleShape.setPosition(position); } // Getter sf::RectangleShape& RectShape::getRectShape() noexcept { return (_rectangleShape); } sf::Text RectShape::getData() const noexcept { return (_data->getText()); } sf::Text RectShape::getTitle() const noexcept { return (_title->getText()); } // Setter void RectShape::setStyle(sf::Color color, int thickness, sf::Color edgeColor, sf::Vector2f size, sf::Vector2f position) noexcept { _rectangleShape.setFillColor(color); _rectangleShape.setOutlineThickness(thickness); _rectangleShape.setOutlineColor(edgeColor); _rectangleShape.setSize(size); _rectangleShape.setPosition(position); } void RectShape::setTitleColumn(std::string const& title) noexcept { _title = new Text(title, RED_TXT, TITLE_SECTION(-10), 16); } void RectShape::setDataColumn(std::string const& data) noexcept { _data = new Text(data, BLUE_TXT, TITLE_SECTION(-30), 16, false); } void RectShape::FullRect(int nbr) { WindowManager manager; _rectRed = new RectShape({30, 500}, {315 + (float)nbr, 90}, RED_COLOR, 0); _rectGreen = new RectShape({30, 500}, {(float)percent(90), 90}, GREEN_COLOR, 0); } void RectShape::drawFullRect(sf::RenderWindow &window) { window.draw(_rectGreen->getRectShape()); window.draw(_rectRed->getRectShape()); }
#include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; using namespace testing; using std::tr1::make_tuple; using std::tr1::get; typedef std::tr1::tuple<Size, int, int> Size_Ksize_BorderType_t; typedef perf::TestBaseWithParam<Size_Ksize_BorderType_t> Size_Ksize_BorderType; PERF_TEST_P( Size_Ksize_BorderType, spatialGradient, Combine( SZ_ALL_HD, Values( 3 ), Values( BORDER_DEFAULT, BORDER_REPLICATE ) ) ) { Size size = std::tr1::get<0>(GetParam()); int ksize = std::tr1::get<1>(GetParam()); int borderType = std::tr1::get<2>(GetParam()); Mat src(size, CV_8UC1); Mat dx(size, CV_16SC1); Mat dy(size, CV_16SC1); declare.in(src, WARMUP_RNG).out(dx, dy); TEST_CYCLE() spatialGradient(src, dx, dy, ksize, borderType); SANITY_CHECK(dx); SANITY_CHECK(dy); }
#ifndef DEBUG_H_ #define DEBUG_H_ #include <fstream> #include <ctime> class Debug { private: std::ofstream* file; public: Debug(); ~Debug(); void write(std::string toWrite); }; #endif
/* * Copyright [2017] <Bonn-Rhein-Sieg University> * * Author: Torsten Jandt * */ #include <mir_planner_executor/actions/move/mockup_move_action.h> #include <mir_planner_executor/actions/mockup_helper.h> bool MockupMoveAction::run(std::string& robot, std::string& from, std::string& to) { return mockupAsk("move_base", {robot, from, to}); }
#pragma once #include "framework/system/core/types.h" #include "ElementDoubleLink.h" #include "IteratorDoubleLink.h" namespace framework { //-------------------------------------------------------------------------------- // ListDoubleLink Class // Manages the elements linked by double link method //-------------------------------------------------------------------------------- class ListDoubleLink_c { public: ListDoubleLink_c(); ~ListDoubleLink_c(); void PushBack( ElementDoubleLink_c* element ); // Adds an element at the end of the list ElementDoubleLink_c * PopBack(); // Removes an element in the bottom of the list and returns it void PushFront( ElementDoubleLink_c* element ); // Adds an element in the front of the list ElementDoubleLink_c * PopFront(); // Removes an element in the front of the list and returns it void Remove( ElementDoubleLink_c* element ); // Removes an specific element void Remove( int index ); // Removes an element by index void Insert( ElementDoubleLink_c* element, int index ); // Inserts an element by index void InsertAfter( ElementDoubleLink_c* element, ElementDoubleLink_c* previousElement ); // Inserts an element just after other void InsertBefore( ElementDoubleLink_c* element, ElementDoubleLink_c* nextElement ); // Inserts an element just before other void Replace( ElementDoubleLink_c* originalElement, ElementDoubleLink_c* newElemnt ); // Replaces an element removing the original one from the list int Size() const; // Returns the number of elements ElementDoubleLink_c * Get( int index ) const; // Returns an element by index int GetElementIndex( const ElementDoubleLink_c* element ) const; // Gets the index of an element, returns -1 if the element is not on the list bool IsOnTheArray( const ElementDoubleLink_c* element ) const; // Checks if an element is on the array IteratorDoubleLink_c GetIterator() const; // Get an iterator of the list void Clear(); // Restores initial status protected: ElementDoubleLink_c m_firstElement; ElementDoubleLink_c m_lastElement; ElementDoubleLink_c * m_first; ElementDoubleLink_c * m_last; int m_size; }; //--------------------------------------------------------------------- // Returns the number of elements //--------------------------------------------------------------------- inline int ListDoubleLink_c::Size() const { return m_size; } //--------------------------------------------------------------------- // Checks if an element is on the array //--------------------------------------------------------------------- inline bool ListDoubleLink_c::IsOnTheArray( const ElementDoubleLink_c* element ) const { return ( GetElementIndex( element ) != -1 ); } //--------------------------------------------------------------------- // Get an iterator of the list //--------------------------------------------------------------------- inline IteratorDoubleLink_c ListDoubleLink_c::GetIterator() const { return IteratorDoubleLink_c( m_first, m_last ); } //--------------------------------------------------------------------- // Removes an element by index //--------------------------------------------------------------------- inline void ListDoubleLink_c::Remove(int index) { Remove( Get( index ) ); } //--------------------------------------------------------------------- // Adds an element at the end of the list //--------------------------------------------------------------------- inline void ListDoubleLink_c::PushBack( ElementDoubleLink_c* element ) { InsertAfter( element, m_last->m_previous ); } //--------------------------------------------------------------------- // Adds an element in the front of the list //--------------------------------------------------------------------- inline void ListDoubleLink_c::PushFront( ElementDoubleLink_c* element ) { InsertAfter( element, m_first ); } }//namespace framework
#include <bits/stdc++.h> using namespace std; #define f first #define s second #define pb push_back #define rep(i, begin, end) \ for (__typeof(end) i = (begin) - ((begin) > (end)); \ i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define db(x) cout << '>' << #x << ':' << x << endl; #define sz(x) ((int)(x).size()) #define newl cout << "\n" #define ll long long int #define vi vector<int> #define vll vector<long long> #define vvll vector<vll> #define pll pair<long long, long long> #define fast_io() \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); ll tc, m, k; ll ans = 1e12+7; void dfs(ll n, ll c) { if(n == 1) { ans = min(ans, c); return; } vector<pair<int, int>> primes; for (int p = 2; p * p <= n; p++) { if (n % p == 0) { int cnt = 0; while (n % p == 0) cnt++, n /= p; primes.push_back({p, cnt}); } } if (n > 1) { primes.push_back({n, 1}); } if (primes.size() == 1) { if (primes[0].s == 1) { dfs(primes[0].f-1, c+1); } else { dfs(primes[0].f, c+1); } } else { for(auto x:primes) { dfs(x.f, c+1); } } return; } int main() { fast_io(); #ifndef ONLINE_JUDGE freopen("../input.txt", "r", stdin); freopen("../output.txt", "w", stdout); #endif cin >> tc; ll n; while (tc--) { cin >> n; ans = 1e12+7; dfs(n, 0); cout << ans; newl; } return 0; } /* 13 30 1 6 5 2 7 3 3 8 4 4 11 4 5 12 3 6 1 5 6 7 8 6 9 5 7 2 2 7 6 7 7 8 4 7 10 7 8 3 4 8 7 6 9 6 6 9 10 3 9 12 7 10 6 4 10 7 5 10 9 3 10 11 5 11 4 4 11 8 5 11 10 5 11 13 10 12 5 2 12 9 7 12 13 6 13 11 10 13 12 5 */
#include "Engines/AbcRejectionEngine.hpp" #include "Engines/AbcSmcEngineSynthetic.hpp" #include "Engines/AbcSmcEngineExperimental.hpp" #include "Engines/SimulationEngineForSyntheticData.hpp" #include "ParameterSets/SyntheticParameterSet.hpp" #include "Other/PeriodicBoundaryConditionsConfiguration.hpp" #include "Parallelization/Parallelization.hpp" int main(int argc, char **argv) { LaunchParallelSession(argc, argv); Thread thread(argc, argv); SyntheticParameterSet parameter_set; PeriodicBoundaryConditionsConfiguration pbc_config(parameter_set.Get_L(), parameter_set.Get_L()); SimulationEngineForSyntheticData simulation_engine(parameter_set, pbc_config); simulation_engine.GenerateSyntheticDataWithArbitraryStationaryVelocity(); // AbcRejectionEngine abc_rejection_engine; // abc_rejection_engine.PrepareSyntheticData(); // abc_rejection_engine.RunAbcTowardsSyntheticData(); // AbcSmcEngineSynthetic abc_smc_engine; // abc_smc_engine.PrepareSyntheticData(); // abc_smc_engine.RunAbcTowardsSyntheticData(); // AbcSmcEngineExperimental abc_smc_engine; // abc_smc_engine.RunAbcTowardsExperimentalData(); FinalizeParallelSession(); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2009 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ /** * @file OpSSLSocket.cpp * * SSL-capable socket creation function. * * @author Alexei Khlebnikov <alexeik@opera.com> * */ #include "core/pch.h" #ifdef EXTERNAL_SSL_OPENSSL_IMPLEMENTATION #include "modules/externalssl/src/OpSSLSocket.h" #include "modules/externalssl/src/openssl_impl/OpenSSLSocket.h" OP_STATUS OpSSLSocket::Create(OpSocket** socket, OpSocketListener* listener, BOOL secure) { if (!socket || !listener) return OpStatus::ERR; OpenSSLSocket* ssl_socket = OP_NEW(OpenSSLSocket, (listener, secure)); if (!ssl_socket) return OpStatus::ERR_NO_MEMORY; OP_STATUS status = ssl_socket->Init(); if (status != OpStatus::OK) { OP_DELETE(ssl_socket); return status; } *socket = ssl_socket; return OpStatus::OK; } #endif // EXTERNAL_SSL_OPENSSL_IMPLEMENTATION
#include "_pch.h" #include "ReportListModel.h" #include "globaldata.h" using namespace wh; //----------------------------------------------------------------------------- ReportListModel::ReportListModel() //:IModelWindow() { } //----------------------------------------------------------------------------- void ReportListModel::UpdateList() { { auto p0 = GetTickCount(); mRepList.clear(); wxLogMessage(wxString::Format("ReprtListModel:\t%d\t clear list", GetTickCount() - p0)); } wxString query = " SELECT id, title, note "//, script " " FROM report ORDER BY title " ; whDataMgr::GetDB().BeginTransaction(); auto table = whDataMgr::GetDB().ExecWithResultsSPtr(query); auto p0 = GetTickCount(); if (table) { //wxString rid; //wxString rtitle; //wxString rnote; //wxString rscript; unsigned int rowQty = table->GetRowCount(); if (rowQty) { mRepList.reserve(rowQty); for (unsigned int i = 0; i < rowQty; ++i) { auto item = std::make_shared<rec::ReportItem>(); table->GetAsString(0, i, item->mId); table->GetAsString(1, i, item->mTitle); table->GetAsString(2, i, item->mNote); //table->GetAsString(3, i, item.mScript); mRepList.emplace_back(std::move(item)); }//for }//if (rowQty) }//if (table) whDataMgr::GetDB().Commit(); wxLogMessage(wxString::Format("ReprtListModel:\t%d\t download results", GetTickCount() - p0)); sigListUpdated(mRepList); } //----------------------------------------------------------------------------- std::shared_ptr<const rec::ReportItem> ReportListModel::LoadAll(const wxString& rep_id) { auto& idxRepId = mRepList.get<1>(); auto& it = idxRepId.find(rep_id); if (idxRepId.end() == it) return nullptr; auto rep = std::make_shared<rec::ReportItem>(); rep->mId = rep_id; wxString query = wxString::Format( " SELECT title, note, script " " FROM report " " WHERE id = %s " , rep_id ); whDataMgr::GetDB().BeginTransaction(); auto table = whDataMgr::GetDB().ExecWithResultsSPtr(query); if (table && table->GetRowCount()) { table->GetAsString(0, 0, rep->mTitle); table->GetAsString(1, 0, rep->mNote); table->GetAsString(2, 0, rep->mScript); } whDataMgr::GetDB().Commit(); idxRepId.replace(it, rep ); sigChReport(rep, rep_id); return rep; } //----------------------------------------------------------------------------- std::shared_ptr<const rec::ReportItem> ReportListModel::GetRep(const wxString& rep_id)const { const auto& idxRepId = mRepList.get<1>(); const auto& it = idxRepId.find(rep_id); if (idxRepId.end() == it) return nullptr; return *it; } //----------------------------------------------------------------------------- void ReportListModel::Mk(const std::shared_ptr<rec::ReportItem>& rep) { wxString s = rep->mScript; s.Replace("'", "''"); wxString query = wxString::Format( " INSERT INTO public.report(title, note, script) " " VALUES('%s', '%s', '%s') RETURNING id" , rep->mTitle, rep->mNote, s ); whDataMgr::GetDB().BeginTransaction(); auto table = whDataMgr::GetDB().ExecWithResultsSPtr(query); if (table && table->GetRowCount()) table->GetAsString(0, 0, rep->mId); whDataMgr::GetDB().Commit(); auto ins_it = mRepList.emplace_back(rep); sigMkReport( (*ins_it.first) ); } //----------------------------------------------------------------------------- void ReportListModel::Rm(const wxString& rep_id) { auto& idxRepId = mRepList.get<1>(); auto& it = idxRepId.find(rep_id); if (idxRepId.end() == it) return; const auto& rep = *it; wxString query = wxString::Format( " DELETE FROM report WHERE id = %s " , rep->mId ); whDataMgr::GetDB().BeginTransaction(); whDataMgr::GetDB().Exec(query); whDataMgr::GetDB().Commit(); sigRmReport(rep); idxRepId.erase(it); } //----------------------------------------------------------------------------- void ReportListModel::Ch(const wxString& rep_id, const std::shared_ptr<rec::ReportItem>& rep) { auto& idxRepId = mRepList.get<1>(); auto& it = idxRepId.find(rep_id); if (idxRepId.end() == it) return; wxString s = rep->mScript; s.Replace("'", "''"); wxString query = wxString::Format( " UPDATE report " " SET title = '%s' , note = '%s' , script = '%s' " " WHERE id = %s " , rep->mTitle, rep->mNote, s , rep_id ); whDataMgr::GetDB().BeginTransaction(); whDataMgr::GetDB().Exec(query); whDataMgr::GetDB().Commit(); idxRepId.replace(it, rep); sigChReport(rep, rep_id); } //-----------------------------------------------------------------------------
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 100 //Maximum degree possible #define max(a,b) (a>b?a:b) typedef struct{ int row; int column; int value; }SM; void input(SM *a) { cout<<"Enter number of rows and columns: "; int m,n,k=1,item; int i,j; cin>>m>>n; a[0].row=m; a[0].column=n; cout<<"Enter the elements: "; for(i=0;i<m;i++){ for(j=0;j<n;j++){ cin>>item; if(item==0) continue; a[k].row=i; a[k].column=j; a[k].value=item; k++; } } a[0].value=k-1; } void display(SM *a) { cout<<"Matrix is : "<<endl<<"Row\t"<<"Column\t"<<"Value\t"<<endl; for(int i=0;i<=a[0].value;i++) { cout<<a[i].row<<"\t"<<a[i].column<<"\t"<<a[i].value<<endl; } } int main() { SM a[100],b[100]; input(a); input(b); display(a); display(b); SM m[200]; //multiply(m); return 0; }
// GML2CityGML.cpp : Defines the entry point for the console application. // #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <windows.h> #include <map> #include <vector> struct S_Point { char x[15]; char y[15]; }; struct S_Surface { int nrPoints; S_Point points[20000]; S_Surface() { nrPoints = 0; }; }; struct S_Interior { S_Surface surface; S_Interior *next; S_Interior() { next = NULL; }; }; struct S_Geometry { S_Surface exterior; S_Interior* interior; S_Geometry() { interior = NULL; }; }; struct S_DestData { char name[25]; float color[3]; float height; }; S_DestData Bestemmingen[] = { {"Argrarisch", {0.922f, 0.941f, 0.824f}, 0.5f}, {"Argrarisch met waarden", {0.824f, 0.882f, 0.647f}, 0.5f}, {"Bedrijf", {0.706f, 0.373f, 0.824f}, 0.5f}, {"Bedrijventerrein", {0.784f, 0.627f, 0.843f}, 0.5f}, {"Bos", {0.392f, 0.667f, 0.176f}, 0.5f}, {"Centrum", {1.000f, 0.784f, 0.745f}, 0.5f}, {"Cultuur en ontspanning", {1.000f, 0.235f, 0.510f}, 0.5f}, {"Detailhandel", {1.000f, 0.627f, 0.588f}, 0.5f}, {"Dienstverlening", {0.941f, 0.569f, 0.745f}, 0.5f}, {"Gemengd", {1.000f, 0.745f, 0.529f}, 0.5f}, {"Groen", {0.157f, 0.784f, 0.275f}, 0.5f}, {"Horeca", {1.000f, 0.412f, 0.137f}, 0.5f}, {"Kantoor", {0.922f, 0.765f, 0.843f}, 0.5f}, {"Maatschappelijk", {0.863f, 0.608f, 0.471f}, 0.5f}, {"Natuur", {0.510f, 0.647f, 0.569f}, 0.5f}, {"Recreatie", {0.725f, 0.843f, 0.275f}, 0.5f}, {"Sport", {0.510f, 0.784f, 0.275f}, 0.5f}, {"Tuin", {0.784f, 0.843f, 0.431f}, 0.5f}, {"Verkeer", {0.804f, 0.804f, 0.804f}, 0.5f}, {"Water", {0.686f, 0.804f, 0.882f}, 0.5f}, {"Wonen", {1.000f, 1.000f, 0.000f}, 0.5f}, {"Woongebied", {1.000f, 1.000f, 0.706f}, 0.5f}, {"Overig", {0.922f, 0.922f, 0.922f}, 0.5f}}; enum ObjectType { OT_ARGRARISCH, OT_ARGRARISCH_WAARDEN, OT_BEDRIJF, OT_BEDRIJVENTERREIN, OT_BOS, OT_CENTRUM, OT_CULTUUR_ONTSPANNING, OT_DETAILHANDEL, OT_DIENSTVERLENING, OT_GEMENGD, OT_GROEN, OT_HORECA, OT_KANTOOR, OT_MAATSCHAPPELIJK, OT_NATUUR, OT_RECREATIEF, OT_SPORT, OT_TUIN, OT_VERKEER, OT_WATER, OT_WONEN, OT_WOONGEBIED, OT_OVERIG, OT_UNKNOWN }; struct S_ImroRelations { // char id[30]; int descPos; ObjectType type; int nrSurfaces; int surfaceId[2000]; S_ImroRelations *parent; S_ImroRelations() { parent = NULL; type = OT_UNKNOWN; nrSurfaces = 0; descPos = -1;}; }; struct cmp_str { bool operator()(char const *a, char const *b) { return std::strcmp(a, b) < 0; } }; void ClearInterior(S_Interior *interior) { if (interior->next != NULL) { ClearInterior(interior->next); } delete interior; } void ClearGeometry(S_Geometry *geom) { if (geom->interior != NULL) ClearInterior(geom->interior); geom->interior = NULL; geom->exterior.nrPoints = 0; } #define PI 3.141592 struct S_PointVal { double x; double y; S_PointVal(double _x, double _y) : x(_x), y(_y) {}; }; struct S_LineString { // int nrPoints; std::vector<S_PointVal> points; // S_Point points[200]; // S_LineString() { nrPoints = 0; }; }; struct S_MultiLines { S_LineString lineString; S_MultiLines *next; S_MultiLines() { next = NULL; }; }; void ClearRoads(S_MultiLines *road) { if (road->next != NULL) { ClearRoads(road->next); delete road->next; } road->lineString.points.clear(); // road->lineString.nrPoints = 0; } int ReadRoadGeometry(FILE* inFile, S_MultiLines *mlines) { int nrLines = 0; char endTag[2]; char prefix[20]; char name[200]; char attributes[1000]; char content[20000]; S_MultiLines* curMLine = mlines; bool first = true; while (fscanf(inFile, " <%20[a-zA-Z?/0-9_] %200[^>]>%20000[^<]", prefix, name, content) > 0) { if (strcmp(name, ":poslist") == 0) { if (prefix[0] == '/') first = false; else { if (!first) { nrLines += curMLine->lineString.points.size() - 1; curMLine->next = new S_MultiLines; curMLine = curMLine->next; } double val = 0, x, y; bool readX = true; int pos = 0; while (content[pos] != '\0' && sscanf(&content[pos], "%lf", &val) > 0) { if (readX) x = val; else { y = val; curMLine->lineString.points.push_back(S_PointVal(x, y)); // [curMLine->lineString.points.size()].y = val; // curMLine->lineString.nrPoints++; /* if (curMLine->lineString.nrPoints == 200) { printf("buffer overrun \"points\"\n"); Sleep(2000); } */ } readX = !readX; while (content[pos] != ' ' && content[pos] != '\0') pos++; pos++; } } } else if (strcmp(name, ":multilinestring") == 0 && prefix[0] == '/') return nrLines; fscanf(inFile, "%*[^<]"); } } void WriteRoadGeometry(FILE* outFile, S_MultiLines* road, int roadNr) { fputs("\t\t\t<bldg:lod4MultiSurface>\n", outFile); fputs("\t\t\t\t<gml:MultiSurface srsName=\"epsg:7415\" srsDimension=\"3\">\n", outFile); double xvec, xvec2; double yvec, yvec2; double angle; double length; double zvec[19]; double dist = 8.0; double *px0, *py0, *px1, *py1; double xl0, xl1, yl0, yl1, z0, z1, xe0, xe1, ye0, ye1; zvec[0] = 0.0; for (int a = 1; a < 18; a++) zvec[a] = sin(a * PI / 36.0); zvec[18] = 1.0; int count = 0; while (road != NULL) { px1 = &road->lineString.points[0].x; py1 = &road->lineString.points[0].y; for (int i = 0; i < road->lineString.points.size() - 1; i++) { px0 = px1; py0 = py1; px1 = &road->lineString.points[i + 1].x; py1 = &road->lineString.points[i + 1].y; xvec = *py1 - *py0; yvec = *px1 - *px0; angle = atan2(xvec, yvec); length = sqrt(xvec * xvec + yvec * yvec); xvec /= length; yvec /= length; for (int a = 1; a < 37; a++) { if (a < 19) { xl0 = xvec * zvec[19 - a] * dist; xl1 = xvec * zvec[18 - a] * dist; yl0 = -yvec * zvec[19 - a] * dist; yl1 = -yvec * zvec[18 - a] * dist; z0 = zvec[a - 1] * dist; z1 = zvec[a] * dist; } else { xl0 = -xvec * zvec[a - 19] * dist; xl1 = -xvec * zvec[a - 18] * dist; yl0 = yvec * zvec[a - 19] * dist; yl1 = yvec * zvec[a - 18] * dist; z0 = zvec[37 - a] * dist; z1 = zvec[36 - a] * dist; } //tunnel fputs("\t\t\t\t\t<gml:surfaceMember>\n", outFile); fprintf(outFile, "\t\t\t\t\t\t<gml:Polygon gml:id=\"Road_%04d_Surface_%05d\">\n", roadNr, count); fputs("\t\t\t\t\t\t\t<gml:exterior>\n", outFile); fputs("\t\t\t\t\t\t\t\t<gml:LinearRing>\n", outFile); fputs("\t\t\t\t\t\t\t\t\t<gml:posList>", outFile); fprintf(outFile, "%.6lf %.6lf %.6lf ", *px0 + xl0, *py0 + yl0, z0); fprintf(outFile, "%.6lf %.6lf %.6lf ", *px1 + xl0, *py1 + yl0, z0); fprintf(outFile, "%.6lf %.6lf %.6lf ", *px1 + xl1, *py1 + yl1, z1); fprintf(outFile, "%.6lf %.6lf %.6lf ", *px0 + xl1, *py0 + yl1, z1); fprintf(outFile, "%.6lf %.6lf %.6lf" , *px0 + xl0, *py0 + yl0, z0); fputs("</gml:posList>\n", outFile); fputs("\t\t\t\t\t\t\t\t</gml:LinearRing>\n", outFile); fputs("\t\t\t\t\t\t\t</gml:exterior>\n", outFile); fputs("\t\t\t\t\t\t</gml:Polygon>\n", outFile); fputs("\t\t\t\t\t</gml:surfaceMember>\n", outFile); count++; //ending top for (int ta = 1; ta < 37; ta++) { if (a < 19) { xe0 = cos(angle + (ta * PI / 36.0)) * zvec[19 - a] * dist; xe1 = cos(angle + (ta * PI / 36.0)) * zvec[18 - a] * dist; ye0 = sin(angle + (ta * PI / 36.0)) * zvec[19 - a] * dist; ye1 = sin(angle + (ta * PI / 36.0)) * zvec[18 - a] * dist; } else { xe0 = cos(angle + (ta * PI / 36.0)) * zvec[19 - a] * dist; xe1 = cos(angle + (ta * PI / 36.0)) * zvec[18 - a] * dist; ye0 = sin(angle + (ta * PI / 36.0)) * zvec[19 - a] * dist; ye1 = sin(angle + (ta * PI / 36.0)) * zvec[18 - a] * dist; } fputs("\t\t\t\t\t<gml:surfaceMember>\n", outFile); fprintf(outFile, "\t\t\t\t\t\t<gml:Polygon gml:id=\"Road_%04d_Surface_%05d\">\n", roadNr, count); fputs("\t\t\t\t\t\t\t<gml:exterior>\n", outFile); fputs("\t\t\t\t\t\t\t\t<gml:LinearRing>\n", outFile); fputs("\t\t\t\t\t\t\t\t\t<gml:posList>", outFile); fprintf(outFile, "%.6lf %.6lf %.6lf ", *px1 + xl0, *py1 + yl0, z0); fprintf(outFile, "%.6lf %.6lf %.6lf ", *px1 + xe0, *py1 + ye0, z0); fprintf(outFile, "%.6lf %.6lf %.6lf ", *px1 + xe1, *py1 + ye1, z1); if (a != 18 && a != 19) fprintf(outFile, "%.6lf %.6lf %.6lf ", *px1 + xl1, *py1 + yl1, z1); fprintf(outFile, "%.6lf %.6lf %.6lf ", *px1 + xl0, *py1 + yl0, z0); fputs("</gml:posList>\n", outFile); fputs("\t\t\t\t\t\t\t\t</gml:LinearRing>\n", outFile); fputs("\t\t\t\t\t\t\t</gml:exterior>\n", outFile); fputs("\t\t\t\t\t\t</gml:Polygon>\n", outFile); fputs("\t\t\t\t\t</gml:surfaceMember>\n", outFile); count++; xl0 = xe0; xl1 = xe1; yl0 = ye0; yl1 = ye1; } //ending bottom for (int ta = 1; ta < 37; ta++) { if (a < 19) { xe0 = cos(angle + (ta * PI / 36.0)) * zvec[19 - a] * dist; xe1 = cos(angle + (ta * PI / 36.0)) * zvec[18 - a] * dist; ye0 = sin(angle + (ta * PI / 36.0)) * zvec[19 - a] * dist; ye1 = sin(angle + (ta * PI / 36.0)) * zvec[18 - a] * dist; } else { xe0 = cos(angle + (ta * PI / 36.0)) * zvec[19 - a] * dist; xe1 = cos(angle + (ta * PI / 36.0)) * zvec[18 - a] * dist; ye0 = sin(angle + (ta * PI / 36.0)) * zvec[19 - a] * dist; ye1 = sin(angle + (ta * PI / 36.0)) * zvec[18 - a] * dist; } fputs("\t\t\t\t\t<gml:surfaceMember>\n", outFile); fprintf(outFile, "\t\t\t\t\t\t<gml:Polygon gml:id=\"Road_%04d_Surface_%05d\">\n", roadNr, count); fputs("\t\t\t\t\t\t\t<gml:exterior>\n", outFile); fputs("\t\t\t\t\t\t\t\t<gml:LinearRing>\n", outFile); fputs("\t\t\t\t\t\t\t\t\t<gml:posList>", outFile); fprintf(outFile, "%.6lf %.6lf %.6lf ", *px0 + xl0, *py0 + yl0, z0); fprintf(outFile, "%.6lf %.6lf %.6lf ", *px0 + xe0, *py0 + ye0, z0); fprintf(outFile, "%.6lf %.6lf %.6lf ", *px0 + xe1, *py0 + ye1, z1); if (a != 18 && a != 19) fprintf(outFile, "%.6lf %.6lf %.6lf ", *px0 + xl1, *py0 + yl1, z1); fprintf(outFile, "%.6lf %.6lf %.6lf ", *px0 + xl0, *py0 + yl0, z0); fputs("</gml:posList>\n", outFile); fputs("\t\t\t\t\t\t\t\t</gml:LinearRing>\n", outFile); fputs("\t\t\t\t\t\t\t</gml:exterior>\n", outFile); fputs("\t\t\t\t\t\t</gml:Polygon>\n", outFile); fputs("\t\t\t\t\t</gml:surfaceMember>\n", outFile); count++; xl0 = xe0; xl1 = xe1; yl0 = ye0; yl1 = ye1; } } } road = road->next; } fprintf(outFile, "\t\t\t\t</gml:MultiSurface>\n"); fprintf(outFile, "\t\t\t</bldg:lod4MultiSurface>\n"); } void ReadRoads(FILE *inFile, FILE *outFile) { //Read file char id[200]; char prefix[20]; char name[200]; char attributes[1000]; char content[2000]; S_MultiLines *proad; std::vector<S_MultiLines> roads; int nrLines[10000]; bool inVak = false; int nrRoads = 0; printf("Writting to file\n"); while (fscanf(inFile, " <%20[a-zA-Z?/0-9_] %200[^> ] %1000[^>]>%10000[^<]", prefix, name, attributes, content) > 0) { //check if there is an end tag as well in the current line if (strcmp(name, ":wegvakken") == 0) { if (prefix[0] != '/') { sscanf(attributes, " %*[^\"]\"%[^\"]\"", id); inVak = true; } else inVak = false; } else if (inVak && (strcmp(name, ":geom") == 0)) { if (prefix[0] != '/') { fputs("\t<core:cityObjectMember>\n", outFile); fprintf(outFile, "\t\t<bldg:Building gml:id=\"%s\">\n", id); fprintf(outFile, "\t\t\t<gml:name>NoiseContour_%04d</gml:name>\n", nrRoads); fscanf(inFile, "%*[^<]"); //Write the geometry roads.push_back(S_MultiLines()); proad = &roads.back(); ReadRoadGeometry(inFile, proad); WriteRoadGeometry(outFile, proad, nrRoads); nrRoads++; fputs("\t\t</bldg:Building>\n", outFile); fputs("\t</core:cityObjectMember>\n", outFile); } id[0] = '\0'; } fscanf(inFile, "%*[^<]"); prefix[0] = '\0'; name[0] = '\0'; attributes[0] = '\0'; content[0] = '\0'; } } void ReadGeometry(FILE* inFile, S_Geometry *geom) { bool readingX = true; char buf[10000]; S_Surface* curSurface = &(geom->exterior); S_Interior** curInterior = &geom->interior; char* curCoord = curSurface->points[0].x; geom->exterior.nrPoints = 0; int rpos = 0, wpos = 0; while (fgets(buf, 10000, inFile) != NULL) { for (rpos = 0; buf[rpos] != '<'; rpos++); if (strncmp(&buf[rpos], "<gml:posList>", 13) == 0) { rpos += 12; do { rpos++; if (buf[rpos] == ' ' || buf[rpos] == '<') //end reading of this point { if (readingX) curSurface->points[curSurface->nrPoints].x[wpos] = '\0'; else curSurface->points[curSurface->nrPoints].y[wpos] = '\0'; // check if a new point needs to be read if (!readingX && (curSurface->nrPoints == 0 || strcmp(curSurface->points[curSurface->nrPoints].x, curSurface->points[curSurface->nrPoints - 1].x) != 0 || strcmp(curSurface->points[curSurface->nrPoints].y, curSurface->points[curSurface->nrPoints - 1].y) != 0)) { curSurface->nrPoints++; if (curSurface->nrPoints == 20000) { printf("buffer overrun \"points\"\n"); Sleep(2000); } } readingX = !readingX; wpos = 0; } else //store character to point { if (readingX) curSurface->points[curSurface->nrPoints].x[wpos] = buf[rpos]; else curSurface->points[curSurface->nrPoints].y[wpos] = buf[rpos]; wpos++; } // check if the buffer needs a refill (end reached) if (rpos == 9999) { fgets(buf, 10000, inFile); rpos = 0; } } while (buf[rpos] != '<'); } else if (strncmp(&buf[rpos], "<gml:interior>", 14) == 0) { *curInterior = new (S_Interior); if (*curInterior == NULL) { printf("Out of memory at \"new S_Interior\"\n)"); Sleep(2000); } curSurface = &((*curInterior)->surface); curInterior = &((*curInterior)->next); } else if (strncmp(&buf[rpos], "</gml:Surface>", 14) == 0) return; } } bool IsNormalUp(S_Surface* surf) { int xMinId = 0, xMaxId = 0, yMinId = 0, yMaxId = 0; unsigned char match = 0; //get bounding box for (int i = 1; i < surf->nrPoints - 1; i++) { if (atof(surf->points[i].x) > atof(surf->points[xMaxId].x)) xMaxId = i; else if (atof(surf->points[i].x) < atof(surf->points[xMinId].x)) xMinId = i; if (atof(surf->points[i].y) > atof(surf->points[yMaxId].y)) yMaxId = i; else if (atof(surf->points[i].y) < atof(surf->points[yMinId].y)) yMinId = i; } for (int i = 0; i < surf->nrPoints; i++) { if (match == 0) { if (i == xMinId) match |= 1; if (i == yMaxId) match |= 2; if (i == xMaxId) match |= 4; if (i == yMinId) match |= 8; } else { if (((match & 0x1) && i == yMaxId) || ((match & 0x2) && i == xMaxId) || ((match & 0x4) && i == yMinId) || ((match & 0x8) && i == xMinId)) return true; else if (i == xMinId || i == xMaxId || i == yMinId || i == yMaxId) return false; } } } void WriteHeader(FILE* outFile) { fputs("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n", outFile); fputs("<core:CityModel\n", outFile); fputs(" xsi:schemaLocation=\"http://www.opengis.net/citygml/1.0 http://schemas.opengis.net/citygml/1.0/cityGMLBase.xsd\n", outFile); fputs(" http://www.opengis.net/citygml/appearance/1.0 http://schemas.opengis.net/citygml/appearance/1.0/appearance.xsd\n", outFile); fputs(" http://www.opengis.net/citygml/building/1.0 http://schemas.opengis.net/citygml/building/1.0/building.xsd\n", outFile); fputs(" http://www.opengis.net/citygml/generics/1.0 http://schemas.opengis.net/citygml/generics/1.0/generics.xsd\n", outFile); fputs(" http://www.opengis.net/citygml/landuse/1.0 http://schemas.opengis.net/citygml/landuse/1.0/landUse.xsd\n", outFile); fputs(" http://www.opengis.net/citygml/transportation/1.0 http://schemas.opengis.net/citygml/transportation/1.0/transportation.xsd\n", outFile); fputs(" http://www.opengis.net/citygml/vegetation/1.0 http://schemas.opengis.net/citygml/vegetation/1.0/vegetation.xsd\n", outFile); fputs(" http://www.opengis.net/citygml/waterbody/1.0 http://schemas.opengis.net/citygml/waterbody/1.0/waterBody.xsd\"\n", outFile); fputs(" xmlns=\"http://www.opengis.net/citygml/profiles/base/1.0\"\n", outFile); fputs(" xmlns:gml=\"http://www.opengis.net/gml\"\n", outFile); fputs(" xmlns:core=\"http://www.opengis.net/citygml/1.0\"\n", outFile); fputs(" xmlns:app=\"http://www.opengis.net/citygml/appearance/1.0\"\n", outFile); fputs(" xmlns:bldg=\"http://www.opengis.net/citygml/building/1.0\"\n", outFile); fputs(" xmlns:gen=\"http://www.opengis.net/citygml/generics/1.0\"\n", outFile); fputs(" xmlns:luse=\"http://www.opengis.net/citygml/landuse/1.0\"\n", outFile); fputs(" xmlns:trans=\"http://www.opengis.net/citygml/transportation/1.0\"\n", outFile); fputs(" xmlns:veg=\"http://www.opengis.net/citygml/vegetation/1.0\"\n", outFile); fputs(" xmlns:wtr=\"http://www.opengis.net/citygml/waterbody/1.0\"\n", outFile); fputs(" xmlns:xAL=\"urn:oasis:names:tc:ciq:xsdschema:xAL:2.0\"\n", outFile); fputs(" xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n", outFile); fputs(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n", outFile); } void WriteBeginSurface(FILE* outFile, S_ImroRelations* rel) { static int curId = 0; fputs("\t\t\t\t\t<gml:surfaceMember>\n", outFile); fprintf(outFile, "\t\t\t\t\t\t<gml:Polygon gml:id=\"Surface_%06d\">\n", curId); rel->surfaceId[rel->nrSurfaces] = curId; rel->nrSurfaces++; if (rel->nrSurfaces == 2000) { printf("buffer overrun \"surfaces\"\n"); Sleep(2000); } curId++; } void WriteEndSurface(FILE* outFile) { fputs("\t\t\t\t\t\t</gml:Polygon>\n", outFile); fputs("\t\t\t\t\t</gml:surfaceMember>\n", outFile); } void WriteHorizontalSurface(FILE* outFile, S_Geometry *geom, float height, bool reverse) { // write exterior fputs("\t\t\t\t\t\t\t<gml:exterior>\n", outFile); fputs("\t\t\t\t\t\t\t\t<gml:LinearRing>\n", outFile); fputs("\t\t\t\t\t\t\t\t\t<gml:posList>", outFile); if (reverse) { for (int i = geom->exterior.nrPoints - 1; i >= 0; i--) { fputs(geom->exterior.points[i].x, outFile); fputc(' ', outFile); fputs(geom->exterior.points[i].y, outFile); fputc(' ', outFile); fprintf(outFile, "%.1lf", height); if (i > 0) fputc(' ', outFile); } } else { for (int i = 0; i < geom->exterior.nrPoints; i++) { fputs(geom->exterior.points[i].x, outFile); fputc(' ', outFile); fputs(geom->exterior.points[i].y, outFile); fputc(' ', outFile); fprintf(outFile, "%.1lf", height); if (i < geom->exterior.nrPoints - 1) fputc(' ', outFile); } } fputs("</gml:posList>\n", outFile); fputs("\t\t\t\t\t\t\t\t</gml:LinearRing>\n", outFile); fputs("\t\t\t\t\t\t\t</gml:exterior>\n", outFile); //write interior parts S_Interior* curInterior = geom->interior; while (curInterior != NULL) { bool rev = reverse ^ IsNormalUp(&curInterior->surface); fputs("\t\t\t\t\t\t\t<gml:interior>\n", outFile); fputs("\t\t\t\t\t\t\t\t<gml:LinearRing>\n", outFile); fputs("\t\t\t\t\t\t\t\t\t<gml:posList>", outFile); if (reverse) { for (int i = curInterior->surface.nrPoints -1; i >= 0; i--) { fputs(curInterior->surface.points[i].x, outFile); fputc(' ', outFile); fputs(curInterior->surface.points[i].y, outFile); fputc(' ', outFile); fprintf(outFile, "%.1lf", height); if (i > 0) fputc(' ', outFile); } } else { for (int i = 0; i < curInterior->surface.nrPoints; i++) { fputs(curInterior->surface.points[i].x, outFile); fputc(' ', outFile); fputs(curInterior->surface.points[i].y, outFile); fputc(' ', outFile); fprintf(outFile, "%.1lf", height); if (i < curInterior->surface.nrPoints - 1) fputc(' ', outFile); } } fputs("</gml:posList>\n", outFile); fputs("\t\t\t\t\t\t\t\t</gml:LinearRing>\n", outFile); fputs("\t\t\t\t\t\t\t</gml:interior>\n", outFile); curInterior = curInterior->next; } } void WriteExtrudingOfSurface(FILE* outFile, S_Surface* surf, float &height, S_ImroRelations* rel, bool reverse) { float offset = height != 0.5 ? 0.0 : -0.5; for (int i = 0; i < surf->nrPoints - 1; i++) { WriteBeginSurface(outFile, rel); fputs("\t\t\t\t\t\t\t<gml:exterior>\n", outFile); fputs("\t\t\t\t\t\t\t\t<gml:LinearRing>\n", outFile); fputs("\t\t\t\t\t\t\t\t\t<gml:posList>", outFile); if (reverse) { fprintf(outFile, "%s %s %.1f ", surf->points[i + 1].x, surf->points[i + 1].y, offset); fprintf(outFile, "%s %s %.1f ", surf->points[i].x, surf->points[i].y, offset); fprintf(outFile, "%s %s %.1f ", surf->points[i].x, surf->points[i].y, height + offset); fprintf(outFile, "%s %s %.1f ", surf->points[i + 1].x, surf->points[i + 1].y, height + offset); fprintf(outFile, "%s %s %.1f", surf->points[i + 1].x, surf->points[i + 1].y, offset); } else { fprintf(outFile, "%s %s %.1f ", surf->points[i].x, surf->points[i].y, offset); fprintf(outFile, "%s %s %.1f ", surf->points[i + 1].x, surf->points[i + 1].y, offset); fprintf(outFile, "%s %s %.1f ", surf->points[i + 1].x, surf->points[i + 1].y, height + offset); fprintf(outFile, "%s %s %.1f ", surf->points[i].x, surf->points[i].y, height + offset); fprintf(outFile, "%s %s %.1f", surf->points[i].x, surf->points[i].y, offset); } fputs("</gml:posList>\n", outFile); fputs("\t\t\t\t\t\t\t\t</gml:LinearRing>\n", outFile); fputs("\t\t\t\t\t\t\t</gml:exterior>\n", outFile); WriteEndSurface(outFile); } } void WriteGeometry(FILE* outFile, S_Geometry* geom, float &height, S_ImroRelations* rel) { float offset = height != 0.5 ? 0.0 : -0.5; fputs("\t\t\t<bldg:lod4MultiSurface>\n", outFile); fputs("\t\t\t\t<gml:MultiSurface srsName=\"epsg:7415\" srsDimension=\"3\">\n", outFile); bool reverse = IsNormalUp(&geom->exterior); if (height == 0.0) //write bottom surface (2D) { WriteBeginSurface(outFile, rel); WriteHorizontalSurface(outFile, geom, 0.0, reverse); WriteEndSurface(outFile); } else // draw 3D surfaces { WriteBeginSurface(outFile, rel); WriteHorizontalSurface(outFile, geom, offset, !reverse); WriteEndSurface(outFile); WriteBeginSurface(outFile, rel); WriteHorizontalSurface(outFile, geom, height + offset, reverse); WriteEndSurface(outFile); WriteExtrudingOfSurface(outFile, &geom->exterior, height, rel, reverse); S_Interior* curInterior = geom->interior; while (curInterior != NULL) { WriteExtrudingOfSurface(outFile, &curInterior->surface, height, rel, IsNormalUp(&curInterior->surface)); curInterior = curInterior->next; } } fprintf(outFile, "\t\t\t\t</gml:MultiSurface>\n"); fprintf(outFile, "\t\t\t</bldg:lod4MultiSurface>\n"); } void WrongUsage() { printf("GML2CityGML input-file output-file"); printf(" input-file: 2D Imro data-file"); printf(" output-file: 3D CityGML representation of the Imro data"); } int main(int argc, char** argv) { FILE *inFile, *outFile; if (argc != 3) { WrongUsage(); return 0; } //Check input file if ((inFile = fopen(argv[1],"r")) == NULL) { printf("Could not open file %s \n", argv[1]); return 0; } //check if output can be generated if ((outFile = fopen(argv[2], "w")) == NULL) { printf("Could not create file %s \n", argv[2]); return 0; } //write header WriteHeader(outFile); //Read file int i; char buf[10000]; char name[200]; name[199]= '\0'; char id[200]; id[199]= '\0'; char ref[200]; ref[199]= '\0'; double flt; S_Geometry geom; std::map<char*, S_ImroRelations*, cmp_str> rel; S_ImroRelations* curRel; fpos_t begin, end; bool afterGeometry = false; bool isMaatvoering = false; bool isEnkelbestemming = false; float height = 0.0f; int curPos; printf("Writting to file\n"); while (fgets(buf, 10000, inFile) != NULL) { //check if there is an end tag as well in the current line for (i = 0; buf[i] != '<'; i++); if (strncmp(&buf[i], "<imro:featureMember>", 20) == 0) { fgets(buf, 10000, inFile); sscanf(buf, " <%*[^:]:%s gml:id=\"%[^\"]\"", name, id); if (id[199] != '\0') { printf("buffer overrun \"id\"\n"); Sleep(2000); } if (name[199] != '\0') { printf("buffer overrun \"name\"\n"); Sleep(2000); } isMaatvoering = (strcmpi(name, "Maatvoering") == 0); isEnkelbestemming = (strcmpi(name, "Enkelbestemming") == 0); if (rel.count(id) == 0) { curRel = new S_ImroRelations(); if (curRel == NULL) { printf("Out of memory at \"new S_ImroRelations\"\n)"); Sleep(2000); } char* tmp = new char[strlen(id) + 1]; strcpy(tmp, id); rel[tmp] = curRel; } else { curRel = rel[id]; } fgetpos(inFile, &begin); } else if (afterGeometry && strncmp(&buf[i + 7], name, strlen(name)) == 0) { fputs("\t\t</bldg:Building>\n", outFile); fputs("\t</core:cityObjectMember>\n", outFile); height = 0.0; isMaatvoering = false; isEnkelbestemming = false; afterGeometry = false; curRel = NULL; } else if (strncmp(&buf[i], "<imro:geometrie>", 16) == 0) { if (strcmpi(id, "Metadata") != 0) { fputs("\t<core:cityObjectMember>\n", outFile); fprintf(outFile, "\t\t<bldg:Building gml:id=\"%s\">\n", id); fprintf(outFile, "\t\t\t<gml:name>%s (%s)</gml:name>\n", name, id); fprintf(outFile, "\t\t\t<gml:description>"); curRel->descPos = ftell(outFile); fprintf(outFile, " </gml:description>\n"); } //add the part between the root element containing this geometry and this geometry element fgetpos(inFile, &end); fsetpos(inFile, &begin); while (begin != end) { fgets(buf, 10000, inFile); fgetpos(inFile, &begin); // if (begin != end) // fputs(buf, outFile); } //Write the geometry ReadGeometry(inFile, &geom); if (isEnkelbestemming) WriteGeometry(outFile, &geom, Bestemmingen[curRel->type].height, curRel); else WriteGeometry(outFile, &geom, height, curRel); ClearGeometry(&geom); } else if (strncmp(&buf[i], "</imro:geometrie>", 17) == 0) { afterGeometry = true; } else if (isMaatvoering && strncmp(&buf[i], "<imro:waarde>", 13) == 0) { sscanf(&buf[i + 13], "%lf", &flt); fgets(buf, 10000, inFile); for (i = 0; buf[i] != '<'; i++); if (strncmp(&buf[i], "<imro:waardeType>maximum bouwhoogte (m)", 39) == 0) height = flt; } else if (isEnkelbestemming && strncmp(&buf[i], "<imro:bestemmingshoofdgroep>", 28) == 0) { int end; i += 28; for (end = i; buf[end] != '<'; end++); buf[end] = '\0'; for (int n = 0; n < 23; n++) { if (strcmpi(Bestemmingen[n].name, &buf[i]) == 0) { curRel->type = (ObjectType) n; break; } } buf[end] = '<'; } else if (strncmp(&buf[i], "<imro:bestemmingsvlak", 21) == 0 || strncmp(&buf[i], "<imro:aanduiding", 16) == 0) { sscanf(buf, " <%*s xlink:href=\"#%[^\"]\"", ref); if (ref[199] != '\0') { printf("buffer overrun \"ref\"\n"); Sleep(2000); } if (rel.count(ref) == 0) { curRel->parent = new S_ImroRelations(); char* tmp = new char[strlen(ref) + 1]; strcpy(tmp, ref); rel[tmp] = curRel->parent; } else { curRel->parent = rel[ref]; } } else if (afterGeometry) { //store data // fputs(buf, outFile); } } // set the color at the description for (std::map<char*, S_ImroRelations*, cmp_str>::iterator it = rel.begin(); it != rel.end(); it++) { S_ImroRelations *curRel = (*it).second; while (curRel->type == OT_UNKNOWN && curRel->parent != NULL) curRel = curRel->parent; if (curRel->type != OT_UNKNOWN) { fseek(outFile, (*it).second->descPos, SEEK_SET); fprintf(outFile, "%03d %03d %03d", (int) (Bestemmingen[curRel->type].color[0] * 255), (int) (Bestemmingen[curRel->type].color[1] * 255), (int)(Bestemmingen[curRel->type].color[2] * 255)); } } fseek(outFile, 0, SEEK_END); //Write the used materials for (int i= 0 ; i < 23; i++) // 23 bestemmingstypes { bool first = true; for (std::map<char*, S_ImroRelations*, cmp_str>::iterator it = rel.begin(); it != rel.end(); it++) { S_ImroRelations *curRel = (*it).second; while (curRel->type == OT_UNKNOWN && curRel->parent != NULL) curRel = curRel->parent; if (curRel->type == i && (*it).second->nrSurfaces > 0) { if (first) { fputs("\t<app:appearanceMember>\n", outFile); fputs("\t\t<app:Appearance>\n", outFile); fputs("\t\t\t<app:surfaceDataMember>\n", outFile); fprintf(outFile, "\t\t\t\t<app:X3DMaterial gml:id=\"%s\">\n", Bestemmingen[i].name); fputs("\t\t\t\t\t<app:ambientIntensity>0.2</app:ambientIntensity>\n", outFile); fprintf(outFile, "\t\t\t\t\t<app:diffuseColor>%.3f %.3f %.3f</app:diffuseColor>\n", Bestemmingen[i].color[0], Bestemmingen[i].color[1], Bestemmingen[i].color[2]); fputs("\t\t\t\t\t<app:emissiveColor>0 0 0</app:emissiveColor>\n", outFile); fputs("\t\t\t\t\t<app:specularColor>1 1 1</app:specularColor>\n", outFile); fputs("\t\t\t\t\t<app:shininess>0.2</app:shininess>\n", outFile); fputs("\t\t\t\t\t<app:transparency>0.5</app:transparency>\n", outFile); fputs("\t\t\t\t\t<app:isSmooth>false</app:isSmooth>\n", outFile); first = false; } for (int n = 0; n < (*it).second->nrSurfaces; n++) fprintf(outFile, "\t\t\t\t\t<app:target>#Surface_%06d</app:target>\n", (*it).second->surfaceId[n]); } } if (!first) { fputs("\t\t\t\t</app:X3DMaterial>\n", outFile); fputs("\t\t\t</app:surfaceDataMember>\n", outFile); fputs("\t\t</app:Appearance>\n", outFile); fputs("\t</app:appearanceMember>\n", outFile); } } fprintf(outFile, "</core:CityModel>\n"); fclose(outFile); fclose(inFile); return 0; }
#include <iostream> using namespace std; int main() { // int - устанавливает целые числа (и только) int a, b; cin >> a >> b; // деление нацело т.к. числа => int // cout << a / b; // округление в большую сторону cout << (a + b - 1) / b; return 0; }
#include <iostream> #define vx vertex* #include <random> using namespace std; #define SEED 12345 mt19937 getRand(SEED); struct vertex { int key; vx parent; vx left; vx right; }; vx make_v(int value, vx parent) { auto *v = new vertex; v->key = value; v->parent = parent; v->left = v->right = nullptr; return v; } class SplayTree{ public: SplayTree(vector<vector<int>> &ss){ } explicit SplayTree(vx v) : root(v){ } vx splay(vx v){ while (v->parent != nullptr){ if (v == v->parent->left){ if (gParent(v) == nullptr){ rzig(v); }else if (v->parent == gParent(v)->left){ rzig(v->parent); rzig(v); } else { rzig(v); lzig(v); } } else { if (gParent(v) == nullptr){ lzig(v); } else if (v->parent == gParent(v)->right){ lzig(v->parent); lzig(v); } else { lzig(v); rzig(v); } } } } SplayTree split(vx v){ splay(v); vx r = v->right; v->right = nullptr; if (r) r->parent = nullptr; return SplayTree(r); } vx merge(SplayTree s){ vx maxi = root; while (maxi->right) maxi = maxi->right; splay(maxi); maxi->right = s.root; } private: vx root; void dfs(){ } vx parent(vx v){ return v ? v->parent : nullptr; } vx gParent(vx v) { return v ? parent(v->parent) : nullptr; } vx rzig(vx v){ v->parent->left = v->right; v->right->parent = v->parent; v->right = v->parent; v->parent->parent = v; // x отец p v->parent = nullptr; } vx lzig(vx v){ v->parent->right = v->left; v->left->parent = v->parent; v->left = v->parent; v->parent->parent = v; v->parent = nullptr; } }; int main() { return 0; }
#include "mOpenCL.h" mOpenCL::mOpenCL(cl_device_type devtype) { //register cl_int i, j; this->devtype = devtype; SELECT_PLATFORMS_AND_DEVICES(pidx, didx, devtype); context1 = createContextFromIndex(pidx, didx, devtype); ContextDevice(context1); try { cl::CommandQueue queue = cl::CommandQueue(context1, context1.getInfo<CL_CONTEXT_DEVICES>()[0], CL_QUEUE_PROFILING_ENABLE); } catch (cl::Error &e) { std::cout << "Error in function " << e.what() << ": " << e.err() << std::endl; } } mOpenCL::~mOpenCL(){} cl::Context mOpenCL::createContextFromIndex(int pidx, int didx, cl_device_type devtype) { std::vector < cl::Device > devices; std::vector < cl::Device > device; std::vector < cl::Platform > platforms; try { cl::Platform::get(&platforms); } catch (cl::Error &e) { std::cout << "Error in function " << e.what() << ": " << e.err() << std::endl; } try { platforms[pidx].getDevices(devtype, &devices); } catch (cl::Error &e) { std::cout << "Error in function " << e.what() << ": " << e.err() << std::endl; } cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[pidx])(), 0 }; device.push_back(devices[didx]); cl::Context context; try { context = cl::Context(device, cps, NULL, NULL); } catch (cl::Error &e) { std::cout << "Error in function " << e.what() << ": " << e.err() << std::endl; } return context; } cl_int mOpenCL::SHOW_PLATFORMS_AND_DEVICES() { register cl_int i, j; std::vector < cl::Platform> platforms; std::vector < cl::Device > devices; cl::Platform::get(&platforms); cl_int numOfPlatforms, numOfDevices; numOfPlatforms = cl_int(platforms.size()); std::cout << "Number of platforms: " << numOfPlatforms << std::endl; for (i = 0; i < numOfPlatforms; i++) { std::cout << "CL_PLATFORM_VENDOR: " << platforms[i].getInfo <CL_PLATFORM_VENDOR>() << std::endl; std::cout << "CL_PLATFORM_NAME: " << platforms[i].getInfo < CL_PLATFORM_NAME >() << std::endl; std::cout << "CL_PLATFORM_VERSION: " << platforms[i].getInfo < CL_PLATFORM_VERSION >() << std::endl; std::cout << "CL_PLATFORM_PROFILE: " << platforms[i].getInfo < CL_PLATFORM_PROFILE >() << std::endl; std::cout << "CL_PLATFORM_EXTENSIONS: " << platforms[i].getInfo < CL_PLATFORM_EXTENSIONS >() << std::endl; } for (i = 0; i < numOfPlatforms; i++) { platforms[i].getDevices(CL_DEVICE_TYPE_ALL, &devices); numOfDevices = cl_int(devices.size()); if (devices.size() > 0) { for (j = 0; j < numOfDevices; j++) { std::cout << std::endl << "Platform " << i << " , Device " << j << std::endl; std::cout << "CL_DEVICE_NAME: " << devices[j].getInfo <CL_DEVICE_NAME>() << std::endl; std::cout << "CL_DEVICE_VENDOR: " << devices[j].getInfo < CL_DEVICE_VENDOR >() << std::endl; std::cout << "CL_DEVICE_MAX_COMPUTE_UNITS: " << devices[j].getInfo < CL_DEVICE_MAX_COMPUTE_UNITS >() << std::endl; std::cout << "CL_DEVICE_MAX_CLOCK_FREQUENCY: " << devices[j].getInfo < CL_DEVICE_MAX_CLOCK_FREQUENCY >() << std::endl; std::cout << "CL_DEVICE_LOCAL_MEM_SIZE: " << devices[j].getInfo < CL_DEVICE_LOCAL_MEM_SIZE >() << std::endl; std::cout << "CL_DEVICE_GLOBAL_MEM_SIZE: " << devices[j].getInfo < CL_DEVICE_GLOBAL_MEM_SIZE >() << std::endl; } } } return 0; } cl_int mOpenCL::SELECT_PLATFORMS_AND_DEVICES(cl_int &pidx, cl_int &didx, cl_device_type devtype) { std::vector < cl::Platform> platforms; std::vector < cl::Device > devices; try { cl::Platform::get(&platforms); } catch (cl::Error &e) { std::cout << "Error in function " << e.what() << ": " << e.err() << std::endl; } cl_int maxNumDevices, maxNumPlatforms; cl_uint s; do { s = 0; SHOW_PLATFORMS_AND_DEVICES(); std::cout << std::endl << "SELECT PLATFORM NUMBER: " << std::endl; std::cin >> pidx; std::cout << "SELECT DEVICE NUMBER: " << std::endl; std::cin >> didx; if (pidx > int(platforms.size()) - 1) { std::cout << "Platform is out of range." << std::endl; s = 1; } else { try { platforms[pidx].getDevices(devtype, &devices); } catch (cl::Error &e) { std::cout << "Error in function " << e.what() << ": " << e.err() << std::endl; } if (didx > int(devices.size()) - 1) { std::cout << "Device is out of range." << std::endl; s = 1; } } } while (s); return 0; } cl_int mOpenCL::ContextDevice(cl::Context & context) { std::vector < cl::Device > devices = context.getInfo<CL_CONTEXT_DEVICES>(); if (devices.size() > 0) { for (size_t i = 0; i < devices.size(); i++) { std::cout << "Device " << i << std::endl; std::cout << "CL_DEVICE_NAME: " << devices[i].getInfo <CL_DEVICE_NAME>() << std::endl; std::cout << "CL_DEVICE_VENDOR: " << devices[i].getInfo < CL_DEVICE_VENDOR >() << std::endl; } } return 0; }
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // idea of node-base locking from 'C++ Concurrency in Action', Anthony Williams #ifndef BOOST_FIBERS_qUEUE_H #define BOOST_FIBERS_qUEUE_H #include <cstddef> #include <deque> #include <stdexcept> #include <utility> #include <boost/atomic.hpp> #include <boost/chrono/system_clocks.hpp> #include <boost/config.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/move/move.hpp> #include <boost/throw_exception.hpp> #include <boost/utility.hpp> #include <boost/thread.hpp> #include <boost/task/detail/queue_op_status.hpp> #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_PREFIX #endif namespace boost { namespace tasks { namespace detail { template< typename T > class queue : private noncopyable { public: typedef T value_type; private: enum state { OPEN = 0, CLOSED }; atomic< state > state_; std::deque< T > queue_; mutable mutex mtx_; condition_variable not_empty_cond_; bool is_closed_() const { return CLOSED == state_; } void close_() { state_ = CLOSED; not_empty_cond_.notify_all(); } bool is_empty_() const { return queue_.empty(); } public: queue() : state_( OPEN), queue_(), mtx_(), not_empty_cond_() {} bool is_closed() const { mutex::scoped_lock lk( mtx_); return is_closed_(); } void close() { mutex::scoped_lock lk( mtx_); close_(); } bool is_empty() const { mutex::scoped_lock lk( mtx_); return is_empty_(); } queue_op_status push( value_type const& va) { mutex::scoped_lock lk( mtx_); if ( is_closed_() ) return queue_op_status::closed; queue_.push_back( va); not_empty_cond_.notify_one(); return queue_op_status::success; } queue_op_status pop( value_type & va) { mutex::scoped_lock lk( mtx_); while ( ! is_closed_() && is_empty_() ) not_empty_cond_.wait( lk); if ( is_closed_() && is_empty_() ) return queue_op_status::closed; BOOST_ASSERT( ! is_empty_() ); try { va = boost::move( queue_.front() ); queue_.pop_front(); return queue_op_status::success; } catch (...) { close_(); throw; } } queue_op_status try_pop( value_type & va) { mutex::scoped_lock lk( mtx_); if ( is_closed_() && is_empty_() ) return queue_op_status::closed; if ( is_empty_() ) return queue_op_status::empty; va = boost::move( queue_.front() ); queue_.pop_front(); return queue_op_status::success; } }; }}} #ifdef BOOST_HAS_ABI_HEADERS # include BOOST_ABI_SUFFIX #endif #endif // BOOST_FIBERS_qUEUE_H
// Adapted cloning algorithm from RLJ. #ifndef CLONINGSERIAL_HPP #define CLONINGSERIAL_HPP #include <random> #include <vector> #include <chrono> #include <experimental/filesystem> // note this is called CloningSerial even if it also supports openMP // all loops over clones should be parallelised via openMP if supported #ifdef _OPENMP #include <omp.h> #endif #include "dat.hpp" #include "particle.hpp" #include "iteration.hpp" #include "readwrite.hpp" ///////////// // CLASSES // ///////////// /* CLONINGSERIAL * ------------- * Cloning algorithm. */ template<class SystemClass> class CloningSerial { /* Contains all the parameters relevant to the cloning algorithm and the * clones themselves. * (see https://yketa.github.io/DAMTP_MSC_2019_Wiki/#Cloning%20algorithm) */ public: // CONSTRUCTORS // lightweight constructor CloningSerial( int nClones, int nWork, double s, int method = 2, std::string cDir = "", std::string lFile = "", std::string sFile = "") : nc (nClones), cloneMethod (method), tau (nWork), sValue(s), clonesDirectory(cDir), loadInput(lFile), saveOutput(sFile) { systems.resize(2*nc); // save parameters to file saveOutput.write<int>(nc); saveOutput.write<int>(cloneMethod); saveOutput.write<int>(tau); saveOutput.write<double>(sValue); } // DESTRUCTORS // simple destructor, we delete the systems but the vector deals with itself ~CloningSerial() { deleteClones(); } // METHODS std::string cloneFilename(int i) { return clonesDirectory == "" ? "" : std::experimental::filesystem::path( std::experimental::filesystem::path(clonesDirectory) / [](int index) { return std::string(6 - std::to_string(index).length(), '0') + std::to_string(index) + std::string(".tmp.dat"); } (i) ).u8string(); } void loadState(); // load cloning configurations from input file void saveState(); // save cloning configurations to output file void outSyncRandomGenerator() { // just for extra safety we can opt to throw our random number generators out of sync here // (the risk is that in a very big population, several clones might have the same seed, // the effect here is to increase the effective range of seeds by safetyFactor #if 1 for (int i=0;i<nc;i++) { int dum = 0; int safetyFactor = 1000; //int k = i % nc; if ( i==0 ) std::cout << "#seed safetyFactor " << safetyFactor << std::endl; for (int r=0; r < i % safetyFactor; r++ ) { dum += (systems[i]->getRandomGenerator())->random01(); dum += (systems[i+nc]->getRandomGenerator())->random01(); } } #endif } void init(SystemClass* dummy, int masterSeed); // initialise list of clones template<typename F, typename G, typename H> void doCloning( double tmax, int initSim, F iterate, G getSWeight, H control); // this runs the cloning for total time tmax void writeTrajFiles(Write& clonesLog); void selectClones(int newClones[], double key[], int pullOffset); int binsearch(double key[], double val, int keylength); // this is a binary search used in clone selection void deleteClones() { for (int i=0; i<2*nc; i++) delete systems[i]; } // delete clones SystemClass* finalSystem(int index) { return systems[finalOffset + index]; } // ATTRIBUTES std::vector<SystemClass*> systems; // these are the clones, the vector has size (2.nc) int const nc; // how many clones int const cloneMethod; // this determines which clone selection method to use (default 2?) int const tau; // number of simulation steps between cloning steps double sValue; // biasing parameter int iter = 0; // number of iterations performed int runIndex = 0; // index of run std::string const clonesDirectory; // if != "": directory where trajectories are saved Read loadInput; // if file != "": input class from where initial configurations are loaded Write saveOutput; // if file != "": write class to where final configurations at each call of doCloning are saved int arrswitch = 0; // set of clones of considered double outputPsi; // this is the estimate of Psi double outputPsiOffset[2] {0, 0}; // used to consider values of psi from previous simulation via loadState std::vector<double> outputOP; // averages over the trajectories of the different clones of (0) active work (1) force part of the active work (2) orientation part of the active work (3) order parameter double outputWalltime; // time taken int finalOffset; // used to access the final population at the end of the run std::mt19937 cloneTwister; // random numbers }; template<class SystemClass> void CloningSerial<SystemClass>:: loadState() {} // specialisation to be written in individual cloning *.cpp files template<class SystemClass> void CloningSerial<SystemClass>:: saveState() {} // specialisation to be written in individual cloning *.cpp files template<class SystemClass> void CloningSerial<SystemClass>:: init(SystemClass* dummy, int masterSeed) { // initialise systems array with 2.nc copies of the "dummy" input // and gives a new seed to the random number generator on each copy // (also makes sure to clean up any old systems that are already in the array) // ... but note this does not initialise the state of the actual systems // std::cout << "#init CloningSerial" << std::endl; // delete any existing clones deleteClones(); cloneTwister.seed(masterSeed); // std::uniform_int_distribution<int> sdist(0, 10000000); // 7 digit random number std::uniform_int_distribution<int> sdist(0, 0x7fffffff); // 31-bit integer, avoids any ambiguity with signed/unsigned int processSeeds[2*nc]; // BIG array of seeds(!), generate them here in order to ensure reproducibility for (int i=0;i<2*nc;i++) processSeeds[i] = sdist(cloneTwister); #ifdef _OPENMP #pragma omp parallel for #endif for (int i=0;i<2*nc;i++) { systems[i] = new SystemClass(dummy, processSeeds[i], tau, cloneFilename(i)); // create new system from copy of dummy, with random seed from processSeeds, computing active work and order parameter for every tau iterations } outSyncRandomGenerator(); for (int i=0;i<2*nc;i++) systems[i]->saveInitialState(); // important if trajectories are actually saved } template<class SystemClass> template<typename F, typename G, typename H> void CloningSerial<SystemClass>:: doCloning( double tmax, int initSim, F iterate, G getSWeight, H control) { // this runs the cloning for total time tmax // input functions: // void iterate(SystemClass* system, int Niter): iterate system for Niter iterations // double getSWeight(SystemClass* system): returns product of biasing parameter and trajectory weight over last cloning step // void control(std::vector<SystemClass*> systems, int pullOffset, int pushOffset): modifications to controlled dynamics at the end of each cloning step // !! this is the main cloning algorithm // std::cout << "#cloning: cloneMethod is " << cloneMethod << std::endl; // clones log Write clonesLog(clonesDirectory == "" ? "" : std::experimental::filesystem::path (std::experimental::filesystem::path(clonesDirectory) / "clones.log") .u8string()); // slightly fancy c++ clock std::chrono::system_clock::time_point startTime = std::chrono::system_clock::now(); // random initial condition for the nc systems that form the current population if ( loadInput.getInputFile() == "" ) { arrswitch = 0; // is otherwise set in loadState #ifdef _OPENMP #pragma omp parallel for #endif for (int i=0;i<nc;i++) { systems[i]->setBiasingParameter(0); // setting 0 biasing parameter (unmodified dynamics to sample initial configurations) iterate(systems[i], tau*initSim); // simulate an elementary number of steps systems[i]->resetDump(); // reset dumps: important between different runs and to only count the relevant quantities within the cloning framework } } // load configurations from file else { loadState(); } // biasing parameter #ifdef _OPENMP #pragma omp parallel for #endif for (int i=0; i<2*nc; i++) systems[i]->setBiasingParameter(sValue); // setting desired biasing parameter double lnX = 0.0; // this is used in our final estimate of psi std::vector<double> sWeight; sWeight.resize(nc); // this is the main loop for (iter = 0; iter < tmax / (tau*systems[0]->getTimeStep()); iter++) // for each iteration of the algorithm { std::vector<double> upsilon(nc); // these are the cloning factors // pushOffset refers to the current population, pullOffset will be the new population // (the systems array is of size 2.nc, only one half is "active" at each time) int pushOffset = arrswitch *nc; int pullOffset = (1-arrswitch)*nc; #ifdef _OPENMP #pragma omp parallel for #endif for (int i = 0; i < nc; i++) // for each clone in the current population { iterate(systems[pushOffset+i], tau); // run dynamics sWeight[i] = getSWeight(systems[pushOffset+i]); upsilon[i] = exp(-sWeight[i]); } #ifdef DEBUG // diagnostic printing (for debug) std::cout << "#logUps"; for (int i=0;i<nc;i++) std::cout << " " << log( upsilon[i] ); std::cout << std::endl; // std::cout << "#s w_mod"; // for (int i=0; i<nc; i++) std::cout << " " << sWeight[i]; // std::cout << std::endl; #endif // construct key based on the upsilon params std::vector<double> key(nc+1); key[0] = 0.0; for (int i = 0; i < nc; i++) { key[i + 1] = key[i] + upsilon[i]; } double totups = key[nc]; //Extract total of upsilons //Calculate cloning factor and store as log to avoid very large values double X = double(totups) / double(nc); lnX = lnX + log(X); // decide who to copy (from which old clone does each new clone "pull" its state) int newClones[nc]; selectClones(newClones,key.data(),pullOffset); #ifdef DEBUG // diagnostic printing (for debug) std::cout << "#pull"; for (int i=0;i<nc;i++) std::cout << " " << newClones[i] ; std::cout << std::endl; #endif for (int i=0;i<nc;i++) clonesLog.write<int>(newClones[i]); // this is the actual cloning step #ifdef _OPENMP #pragma omp parallel for #endif for (int i=0; i<nc; i++) { systems[pullOffset + i]->copyState(systems[ pushOffset + newClones[i] ]); // clone particles systems[pullOffset + i]->copyDump(systems[ pushOffset + newClones[i] ]); // clone dumps } // CONTROLLED DYNAMICS control(systems, pullOffset, pushOffset); arrswitch = 1 - arrswitch; //Set the other set of systems to be used in next time loop } finalOffset = arrswitch * nc; outputPsi = (double(lnX) + outputPsiOffset[0]*outputPsiOffset[1]) /(iter*tau*systems[0]->getTimeStep() + outputPsiOffset[0]); // C++ clocks again std::chrono::system_clock::time_point endTime = std::chrono::system_clock::now(); // this horrible syntax just computes elapsed time in seconds, at microsecond resolution outputWalltime = 1e-6*std::chrono::duration_cast<std::chrono::microseconds> (endTime - startTime).count(); // WRITE TRAJECTORY FILES if ( clonesDirectory != "" ) writeTrajFiles(clonesLog); // SAVE FINAL CONFIGURATIONS if ( saveOutput.getOutputFile() != "" ) saveState(); // RUN INDEX runIndex++; // this line must be at the END of the function } template<class SystemClass> void CloningSerial<SystemClass>:: writeTrajFiles(Write& clonesLog) {} // specialisation to be written in individual cloning *.cpp files template<class SystemClass> void CloningSerial<SystemClass>:: selectClones(int newClones[], double key[], int pullOffset) { std::uniform_real_distribution<double> randc(0,1.0); // random double in [0,1] // this offset determines who is pulling (it is either 0 or nc) double totups = key[nc]; if ( cloneMethod == 1 ) { // this is the iid method #ifdef _OPENMP #pragma omp parallel for #endif for(int i=0; i<nc; i++) { // RLJ: we use the system rng of the destination system to decide where to "pull" from double rr = (systems[pullOffset+i]->getRandomGenerator())->random01() *totups; //cout << rr << " " << totups << " " << offset+i << endl; newClones[i] = binsearch(key, rr, nc+1); } } else if ( cloneMethod == 2 ) { // this is the eq method (should be default) double alpha = (systems[pullOffset]->getRandomGenerator())->random01() *totups/nc; #ifdef _OPENMP #pragma omp parallel for #endif for(int i=0; i<nc; i++) { double rr = alpha + (i*totups/(double)nc); newClones[i] = binsearch(key, rr, nc+1); } } // if not method 1 or 2 then just copy everyone equally (should never happen) else { for(int i=0; i<nc; i++) newClones[i] = i; } } template<class SystemClass> int CloningSerial<SystemClass>:: binsearch(double *key, double val, int keylength) { // this is a binary search used in clone selection int l = 0; /*Left hand limit*/ int r = keylength - 1; /*Right hand limit*/ int m; /*Midpoint*/ int k; /*Element containing value*/ bool elementfound = false; /*True when the element containing the value has been found*/ while (elementfound == false) { m = int(floor(float(l + r) / 2)); /*Calculate midpoint*/ if (val<key[m]) /*If value lower than midpoint, shift the right hand limit*/ { r = m; } else /*Otherwise shift the left hand limit*/ { l = m; } if (l == r - 1) /*Value lies in element between limits*/ { elementfound = true; } } k = r - 1; /*Element index is index of upper limit when disregarding the index of the 0 value at the beginning of the key*/ return k; } #endif
// // Created by Christofer on 20/08/2017. // #include "SpriteRenderer.h" const char *shaderSources[] = { "" "#version 330\n" "\n" "layout(location = 0) in vec3 position;\n" "layout(location = 1) in vec2 texCoords;\n" "\n" "uniform mat4 projectionViewMatrix = mat4(1.0);\n" "\n" "out vec2 texCoord;\n" "\n" "void main() {\n" " gl_Position = projectionViewMatrix * vec4(position, 1);\n" " texCoord = texCoords;\n" "}", "" "#version 330\n" "out vec4 outColor;\n" "uniform sampler2D tex0;\n" "in vec2 texCoord;\n" "void main() {\n" " outColor = texture(tex0, texCoord);\n" "}\n" }; SpriteRenderer::SpriteRenderer() { GLuint types[] = {GL_VERTEX_SHADER, GL_FRAGMENT_SHADER}; this->shader.create(shaderSources, types, 2); } void SpriteRenderer::begin(const glm::mat4 &projectionViewMatrix) { this->projectionViewMatrix = projectionViewMatrix; } void SpriteRenderer::end() { for (auto &spritePair : sprites) { Sprite &sprite = spritePair.second; flush(sprite); } } void SpriteRenderer::flush(SpriteRenderer::Sprite &sprite) { sprite.texture->bind(); this->shader.use(); glUniformMatrix4fv(this->shader.getUniformLocation("projectionViewMatrix"), 1, 0, glm::value_ptr(this->projectionViewMatrix)); vertexBuffer.setVertices(sprite.vertices.data(), sprite.vertices.size()); vertexBuffer.setIndices(sprite.indices.data(), sprite.indices.size()); sprite.vertices.clear(); sprite.indices.clear(); vertexBuffer.draw(); } void SpriteRenderer::draw(Texture &texture, glm::vec2 position) { draw(texture, position, glm::vec2(texture.getWidth(), texture.getHeight())); } void SpriteRenderer::draw(Texture &texture, glm::vec2 position, glm::vec2 size) { Sprite &currentSprite = sprites[texture]; currentSprite.texture = &texture; // Position float x = position.x, y = position.y, w = currentScale.x * size.x, h = currentScale.y * size.y; // Texture coordinates float u = 0, v = 0, us = 1, vs = 1; GLuint startVertex = currentSprite.vertices.size(); currentSprite.vertices.emplace_back(glm::vec3(x, y, 0), glm::vec2(u, v)); currentSprite.vertices.emplace_back(glm::vec3(x, y + h, 0), glm::vec2(u, v + vs)); currentSprite.vertices.emplace_back(glm::vec3(x + w, y + h, 0), glm::vec2(u + us, v + vs)); currentSprite.vertices.emplace_back(glm::vec3(x + w, y, 0), glm::vec2(u + us, v)); currentSprite.indices.push_back(startVertex + 0); currentSprite.indices.push_back(startVertex + 1); currentSprite.indices.push_back(startVertex + 2); currentSprite.indices.push_back(startVertex + 2); currentSprite.indices.push_back(startVertex + 3); currentSprite.indices.push_back(startVertex + 0); } void SpriteRenderer::draw(const TextureRegion& region, glm::vec2 position, glm::vec2 size) { Sprite &currentSprite = sprites[*region.texture]; currentSprite.texture = region.texture; // Position float x = position.x, y = position.y, w = currentScale.x * size.x, h = currentScale.y * size.y; // Texture coordinates float u = region.offset.x, v = region.offset.y, us = region.size.x, vs = region.size.y; GLuint startVertex = currentSprite.vertices.size(); currentSprite.vertices.emplace_back(glm::vec3(x, y, 0), glm::vec2(u, v)); currentSprite.vertices.emplace_back(glm::vec3(x, y + h, 0), glm::vec2(u, v + vs)); currentSprite.vertices.emplace_back(glm::vec3(x + w, y + h, 0), glm::vec2(u + us, v + vs)); currentSprite.vertices.emplace_back(glm::vec3(x + w, y, 0), glm::vec2(u + us, v)); currentSprite.indices.push_back(startVertex + 0); currentSprite.indices.push_back(startVertex + 1); currentSprite.indices.push_back(startVertex + 2); currentSprite.indices.push_back(startVertex + 2); currentSprite.indices.push_back(startVertex + 3); currentSprite.indices.push_back(startVertex + 0); } void SpriteRenderer::scale(glm::vec2 scale) { this->currentScale = scale; }
#include "Stage.h" #include <DxLib.h> Stage::Stage() { int fmf_h = DxLib::FileRead_open("Stage/Stage2.fmf", false); DxLib::FileRead_read(&_fmfdata, sizeof(_fmfdata), fmf_h); std::vector<char> _tmp; _tmp.resize(_fmfdata.mapWidth * _fmfdata.mapHeight); DxLib::FileRead_read(&_tmp[0], _tmp.size(), fmf_h); DxLib::FileRead_close(fmf_h); _stageRange.size.width = _fmfdata.mapWidth*_fmfdata.chipW * 2; _stageRange.size.height = _fmfdata.mapHeight*_fmfdata.chipH * 2; _stageRange.center.x = _stageRange.size.width / 2; _stageRange.center.y = _stageRange.size.height / 2; data.range.size.width = _fmfdata.mapWidth; data.range.size.height = _fmfdata.mapHeight; data.chipSize = _fmfdata.chipH; _stagedata.resize(_fmfdata.mapWidth * _fmfdata.mapHeight); for (int i = 0; i < _fmfdata.mapHeight; i++) { for (int j = 0; j < _fmfdata.mapWidth; j++) { _stagedata[i * _fmfdata.mapWidth + j] = _tmp[i * _fmfdata.mapWidth + j]; } } int e_fmf_h = DxLib::FileRead_open("Stage/Enemy.fmf", false); DxLib::FileRead_read(&e_fmfdata, sizeof(e_fmfdata), e_fmf_h); std::vector<char> e_tmp; e_tmp.resize(e_fmfdata.mapWidth * e_fmfdata.mapHeight); DxLib::FileRead_read(&e_tmp[0], e_tmp.size(), e_fmf_h); DxLib::FileRead_close(e_fmf_h); _enemydata.resize(e_fmfdata.mapWidth * e_fmfdata.mapHeight); for (int i = 0; i < e_fmfdata.mapHeight; i++) { for (int j = 0; j < e_fmfdata.mapWidth; j++) { _enemydata[i*e_fmfdata.mapWidth + j] = e_tmp[i*e_fmfdata.mapWidth + j]; } } _readX = 0; } Stage::~Stage() { } const Rect & Stage::GetStageRange() const { return _stageRange; } const std::vector<char> Stage::GetEnemyData(int minX, int maxX) { int L = max(minX / (e_fmfdata.chipW * 2), _readX); int R = maxX / (e_fmfdata.chipW * 2) + 1; if (R <= _readX)return std::vector<char>(); auto idxL = L * e_fmfdata.mapHeight; auto idxR = min(R * e_fmfdata.mapHeight, _enemydata.size()); auto begin = _enemydata.begin() + idxL; auto end = min(_enemydata.begin() + idxR, _enemydata.end()); _readX = R; return std::vector<char>(begin, end); } const std::vector<char> Stage::GetStageData() { return std::vector<char>(_stagedata.begin(), _stagedata.end()); } void Stage::SetStageData(int num,int id) { _stagedata[num] = id; } const STAGE & Stage::GetData() { return data; }
/*********************************************************\ * Copyright (c) 2012-2018 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ // TODO(co) Code-style adoptions and extensions //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace RendererRuntime { template <typename RetType> ThreadPool<RetType>::ThreadPool(size_t threads) { if (isUninitialized(threads)) { threads = std::thread::hardware_concurrency(); } if (threads == 0) { threads = 1; } this->threads = threads; } template <typename RetType> ThreadPool<RetType>::~ThreadPool() { // If thread is running then wait for it to complete if (thread.joinable()) { thread.join(); } } template <typename RetType> void ThreadPool<RetType>::queueTask(const Task &task) { tasks.push(task); } template <typename RetType> void ThreadPool<RetType>::queueTask(Task &&task) { tasks.emplace(std::move(task)); } template <typename RetType> void ThreadPool<RetType>::process(Callback callback) { if (callback) { thread = std::thread([&]{ _process(); callback(); }); } else { _process(); } } template <typename RetType> void ThreadPool<RetType>::_process() { std::lock_guard<std::mutex> lock(processMutex); futuresDone.clear(); while (!tasks.empty()) { const size_t taskAmount = tasks.size(); const size_t amount = (threads > taskAmount ? taskAmount : threads); for (size_t i = 0; i < amount; ++i) { auto task = tasks.front(); tasks.pop(); auto future = std::async(std::launch::async, [=] { return task(); }); futuresPending.emplace_back(std::move(future)); } for (auto &future : futuresPending) { future.wait(); futuresDone.emplace_back(std::move(future)); } futuresPending.clear(); } } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // RendererRuntime
#include <iostream> #include <string> #include "UndirectedGraph.hpp" class Point { public: Point() {} Point(int x_in, int y_in) {x = x_in; y = y_in;} bool operator==(const Point& other) { return (x == other.x && y == other.y); } int x; int y; }; inline int index_of(int x, int y, int width) { return y * width + x; } inline Point point_from_index(int index, int width) { return Point(index % width, index / width); } bool is_inaccessible(Point p, const cs202::LinearList<Point>& inaccessible_points) { return inaccessible_points.find(p) != inaccessible_points.size(); } bool is_valid_point(Point p, int width, int height) { return (p.x >= 0 && p.x < width && p.y >= 0 && p.y < height); } cs202::UndirectedGraph build_graph(int width, int height, const cs202::LinearList<Point>& inaccessible_points) { cs202::UndirectedGraph graph(width * height, cs202::LIST); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { if (is_inaccessible(Point(x, y), inaccessible_points)) { continue; // in this case we don't want to do anything } // Add all offsets for (int xoffset = -1; xoffset <= 1; xoffset++) { for (int yoffset = -1; yoffset <=1; yoffset++) { Point p(x + xoffset, y + yoffset); if (!(xoffset == 0 && yoffset == 0) // if both offsets are zero then we'd add a self loop && is_valid_point(p, width, height) // must be a valid point to be added && !is_inaccessible(p, inaccessible_points)) { // must be accessible to be added graph.add(index_of(x, y, width), index_of(p.x, p.y, width)); } } } } } return graph; } void no_work(int& param) { } cs202::list<int> path_from_pred(cs202::LinearList<int> pred, int source, int dest) { cs202::list<int> path; int cur = dest; while (cur != -1) { path.cons(cur); cur = pred[cur]; } if (path[0] == source) { return path; } else { return cs202::list<int> (); // no path exists, so we should return an empty list } } int main() { int width, height; std::cout << "Enter the width and the height of the matrix: "; std::cin >> width >> height; Point source, dest; std::cout << "Enter the source and destination vertices (x, y): "; std::cin >> source.x >> source.y >> dest.x >> dest.y; int num_inaccessible; std::cout << "Enter the number of inaccessible nodes: "; std::cin >> num_inaccessible; cs202::LinearList<Point> inaccessible_points(num_inaccessible); for (int i = 0; i < num_inaccessible; i++) { Point p; std::cin >> p.x >> p.y; inaccessible_points.push_back(p); } cs202::UndirectedGraph graph = build_graph(width, height, inaccessible_points); cs202::LinearList<int> pred = graph.dfs(index_of(source.x, source.y, width), &no_work); cs202::list<int> path = path_from_pred(pred, index_of(source.x, source.y, width), index_of(dest.x, dest.y, width)); if (path.empty()) { std::cout << "Can't reach destination from source." << std::endl; } else { std::cout << "Can reach the destination from the source. Here's the path: " << std::endl; for (auto elem : path) { Point p = point_from_index(elem, width); std::cout << "(" << p.x << ", " << p.y << ") " << " "; } std::cout << std::endl; } return 0; }
#pragma once #include "config/behavior_tree_ptts.hpp" #include "proto/data_base.pb.h" #include "proto/data_behavior_tree.pb.h" #include "scene/log.hpp" #include "utils/service_thread.hpp" #include <memory> #include <queue> #include <chrono> using namespace std; using namespace std::chrono; namespace pc = proto::config; #define SCENE_BT_TLOG __TLOG << setw(20) << "[SCENE_BT] " #define SCENE_BT_DLOG __DLOG << setw(20) << "[SCENE_BT] " #define SCENE_BT_ILOG __ILOG << setw(20) << "[SCENE_BT] " #define SCENE_BT_ELOG __ELOG << setw(20) << "[SCENE_BT] " namespace nora { namespace scene { template <typename T> class behavior_tree : public enable_shared_from_this<behavior_tree<T>> { public: behavior_tree(T *owner, const shared_ptr<service_thread>& st, uint32_t default_root) : owner_(owner), st_(st), default_root_(default_root), cur_root_(default_root) { ASSERT(owner_); next_frequency_ = system_clock::duration::zero(); } void set_rand_func(const function<int()>& func) { rand_ = func; } void run() { ASSERT(st_ && st_->check_in_thread()); if (timer_) { return; } if (stop_) { stop_ = false; return; } timer_ = ADD_TIMER( st_, ([this, self = this->shared_from_this()] (auto canceled, const auto& timer) { if (timer_ == timer) { timer_.reset(); } if (!canceled && !stop_) { this->process_root(); this->run(); } }), next_frequency_ == system_clock::duration::zero() ? default_frequency_ : next_frequency_); next_frequency_ = system_clock::duration::zero(); } bool running() const { return !stop_; } void rebuild_root_node(uint32_t behavior_tree_root, uint32_t children_node) { cur_root_ = behavior_tree_root; auto& ptt = PTTS_GET(behavior_tree, cur_root_); ptt.clear_children(); ptt.add_children(children_node); pd::behavior_tree_node ret; ret.set_pttid(cur_root_); for (auto i : ptt.children()) { *ret.add_children() = build_node(i); } roots_[cur_root_] = ret; } void process_root() { if (!root_queue_.empty()) { cur_root_ = root_queue_.front(); root_queue_.pop(); } ASSERT(cur_root_ > 0); if (roots_.count(cur_root_) == 0) { roots_[cur_root_] = build_node(cur_root_); } auto& root = roots_.at(cur_root_); try { auto result = process(root); if (result == pd::OK || result == pd::FAILED) { reset(root); if (!root_queue_.empty()) { cur_root_ = root_queue_.front(); root_queue_.pop(); } else { if (only_queue_) { stop(); } cur_root_ = default_root_; } } } catch (...) { SCENE_BT_TLOG << "process exception"; reset(root); } } void set_only_queue(bool only_queue) { only_queue_ = only_queue; } void push_root(uint32_t root) { root_queue_.push(root); } pd::result process(pd::behavior_tree_node& node) { const auto& ptt = PTTS_GET(behavior_tree, node.pttid()); auto result = pd::NONE; if (node.cache().has_status() && node.cache().status() != pd::RUNNING) { SCENE_BT_TLOG << "bt node use cache status"; result = node.cache().status(); } else { switch (ptt.type()) { case pc::BNT_ACTION: { cur_action_node_ = &node; result = owner_->behavior_tree_action(node); if (result == pd::OK || result == pd::FAILED) { cur_action_node_ = nullptr; } break; } case pc::BNT_CONDITION: result = owner_->behavior_tree_condition(node); break; case pc::BNT_FALLBACK: ASSERT(node.children_size() > 0); SCENE_BT_TLOG << "BNT_FALLBACK node cache child_idx is " << node.cache().child_idx(); for (auto i = node.cache().child_idx(); i < node.children_size(); ++i) { auto& child = *node.mutable_children(i); result = process(child); if (result == pd::FAILED) { node.mutable_cache()->set_child_idx(i + 1); continue; } else { break; } } break; case pc::BNT_RANDOM_FALLBACK: { ASSERT(node.children_size() > 0); if (node.cache().children_idx_size() > 0) { auto child_idx = node.cache().children_idx(node.cache().children_idx_size() - 1); auto& child = *node.mutable_children(child_idx); result = process(child); } if (result == pd::NONE || result == pd::FAILED) { set<int> not_tried_children_idxs; for (auto i = 0; i < node.children_size(); ++i) { not_tried_children_idxs.insert(i); } for (auto i : node.cache().children_idx()) { not_tried_children_idxs.erase(i); } while (!not_tried_children_idxs.empty()) { auto iter = not_tried_children_idxs.begin(); auto randnumber = rand_ ? rand_() : rand(); SCENE_BT_TLOG << "BNT_RANDOM_FALLBACK rand number is " << randnumber << " index is " << randnumber % not_tried_children_idxs.size(); auto dis = randnumber % not_tried_children_idxs.size(); advance(iter, dis); auto& child = *node.mutable_children(*iter); result = process(child); node.mutable_cache()->add_children_idx(*iter); not_tried_children_idxs.erase(*iter); if (result == pd::OK || result == pd::RUNNING) { break; } else { continue; } } } if (result == pd::OK || result == pd::FAILED) { node.mutable_cache()->clear_children_idx(); } break; } case pc::BNT_SEQUENCE: ASSERT(node.children_size() > 0); SCENE_BT_TLOG << "BNT_SEQUENCE node cache child_idx is " << node.cache().child_idx(); for (auto i = node.cache().child_idx(); i < node.children_size(); ++i) { auto& child = *node.mutable_children(i); result = process(child); if (result == pd::OK) { node.mutable_cache()->set_child_idx(i + 1); continue; } else { break; } } break; case pc::BNT_PARALLEL: { ASSERT(node.children_size() > 0); int ok_count = 0; int failed_count = 0; for (auto& i : *node.mutable_children()) { result = process(i); if (result == pd::OK) { ok_count += 1; break; } else if (result == pd::FAILED) { failed_count += 1; break; } else { break; } } if (ok_count >= ptt.parallel().threshold()) { result = pd::OK; } else if (failed_count > node.children_size() - ptt.parallel().threshold()) { result = pd::FAILED; } else { result = pd::RUNNING; } break; } } ASSERT(result != pd::NONE); node.mutable_cache()->set_status(result); if (result == pd::RUNNING) { auto running_times = node.cache().running_times(); running_times += 1; node.mutable_cache()->set_running_times(running_times); if (ptt.has_desc() && running_times > 32) { SCENE_BT_ELOG << *owner_ << " possible dead end: " << ptt.desc() << " running times: " << running_times; } } } SCENE_BT_DLOG << *owner_ << " process node: " << ptt.desc() << " result: " << pd::result_Name(result); return result; } pd::behavior_tree_node *cur_action_node() { return cur_action_node_; } void stop() { ASSERT(st_->check_in_thread()); if (stop_) { return; } stop_ = true; if (timer_) { timer_->cancel(); timer_.reset(); } for (auto& i : roots_) { reset(i.second); } } void set_next_frequency(const system_clock::duration& du) { next_frequency_ = du; } private: pd::behavior_tree_node build_node(uint32_t pttid) { pd::behavior_tree_node ret; ret.set_pttid(pttid); const auto& ptt = PTTS_GET(behavior_tree, pttid); for (auto i : ptt.children()) { *ret.add_children() = build_node(i); } return ret; } void reset(pd::behavior_tree_node& node) { node.clear_cache(); for (auto& i : *node.mutable_children()) { reset(i); } cur_action_node_ = nullptr; } T *owner_; shared_ptr<service_thread> st_; map<uint32_t, pd::behavior_tree_node> roots_; uint32_t default_root_ = 0; uint32_t cur_root_ = 0; queue<uint32_t> root_queue_; pd::behavior_tree_node *cur_action_node_ = nullptr; shared_ptr<timer_type> timer_; bool stop_ = false; system_clock::duration next_frequency_; system_clock::duration default_frequency_ = 3s; function<int()> rand_; bool only_queue_ = false; }; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. ** It may not be distributed under any circumstances. */ #ifndef SINGLEBTREE_H #define SINGLEBTREE_H #include "modules/search_engine/BTree.h" #define SBTREE_MAX_CACHE_BRANCHES 50 /** * @brief BTree stored in a file. * @author Pavel Studeny <pavels@opera.com> * * SingleBTree is a BTree stored on disk. * Unlike DiskBTree, you can use it directly, since there is only one BTree in the file. */ template <typename KEY> class SingleBTree : public TBTree<KEY>, public TPool<KEY> { public: SingleBTree(int max_cache_branches = SBTREE_MAX_CACHE_BRANCHES) : TBTree<KEY>(this, 0), TPool<KEY>(max_cache_branches) {} SingleBTree(TypeDescriptor::ComparePtr compare, int max_cache_branches = SBTREE_MAX_CACHE_BRANCHES) : TBTree<KEY>(this, 0, compare), TPool<KEY>(compare, max_cache_branches) {} /** * SingleBTree must be opened before you call any other method * @param path file storing the data; file is always created if it doesn't exist * @param mode Read/ReadWrite mode * @param blocksize one block consists of 12 B of internal BlockStorage data, 4 B rightmost pointer and the rest is divided into (sizeof(data) + 4 B pointer) chunks * @param folder might be one of predefind folders */ CHECK_RESULT(OP_STATUS Open(const uni_char* path, BlockStorage::OpenMode mode, int blocksize = 512, OpFileFolder folder = OPFILE_ABSOLUTE_FOLDER)) { RETURN_IF_ERROR((TPool<KEY>::Open(path, mode, blocksize, folder))); if (this->m_storage.GetFileSize() > (OpFileLength)this->m_storage.GetBlockSize() * 2) this->m_root = 2; return OpStatus::OK; } /** Recovery function for corrupted SingleBTree * SingleBTree must be closed before you call this function * @param path file name of the original SingleBTree * @param blocksize blocksize of original SingleBTree * @param folder might be one of predefind folders */ CHECK_RESULT(OP_STATUS Recover(const uni_char* path, int blocksize = 512, OpFileFolder folder = OPFILE_ABSOLUTE_FOLDER)) { OpString temp_filename; RETURN_IF_ERROR(temp_filename.AppendFormat(UNI_L("%s.temp"),path)); SingleBTree<KEY> temp_tree; // Open new btree RETURN_IF_ERROR(temp_tree.Open(temp_filename.CStr(), BlockStorage::OpenReadWrite, blocksize, folder)); // Open old btree RETURN_IF_ERROR(Open(path, BlockStorage::OpenRead, blocksize, folder)); OpAutoPtr<SearchIterator<KEY> > tree_iterator(this->SearchFirst()); if (!tree_iterator.get()) return OpStatus::ERR_NO_MEMORY; if (!tree_iterator->Empty()) { // loop through the old tree and add stuff as we find them do { RETURN_IF_ERROR(temp_tree.Insert(KEY(tree_iterator->Get()))); } while (tree_iterator->Next()); } // open iterators need to be closed before closing the tree tree_iterator.reset(); RETURN_IF_ERROR(this->Close()); RETURN_IF_ERROR(temp_tree.Close()); // Delete the old tree and move new tree to the correct location RETURN_IF_ERROR(BlockStorage::DeleteFile(path, folder)); return BlockStorage::RenameFile(temp_filename.CStr(), path, folder); } protected: CHECK_RESULT(virtual OP_STATUS NewBranch(BTreeBase::BTreeBranch **branch, BTreeBase::BTreeBranch *parent)) { if (this->m_root == 0 && this->m_head != NULL) RETURN_IF_ERROR(this->Flush()); RETURN_IF_ERROR(TBTree<KEY>::NewBranch(branch, parent)); if (this->m_root < 0 && this->m_root == (*branch)->disk_id) TBTree<KEY>::SafePointer(*branch); // SafePointer will set this->m_root return OpStatus::OK; } }; #endif // SINGLEBTREE_H
#ifndef CUSTOMGRAPH_H #define CUSTOMGRAPH_H /* Copyright (c) 2008-2018, Benoit AUTHEMAN All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author or Destrat.io nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR 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 file is a part of the QuickQanava software library. // // \file cpp_sample.h // \author benoit@destrat.io // \date 2018 05 24 //----------------------------------------------------------------------------- // Qt headers #include <QGuiApplication> #include <QtQml> #include <QQuickStyle> // QuickQanava headers #include <QuickQanava.h> #include <QMap> #include <QDebug> #include "customnode.h" class CustomGraph : public qan::Graph { Q_OBJECT public: explicit CustomGraph(QQuickItem *parent = nullptr) : qan::Graph{parent} { /* Nil */ } virtual ~CustomGraph() override { /* Nil */ } private: CustomGraph(const CustomGraph &) = delete; QMap<qan::Node, qan::StyleManager> style_managers_map; public: Q_INVOKABLE qan::Group* insertCustomGroup(); Q_INVOKABLE qan::Node* insertCustomNode(); Q_INVOKABLE qan::Edge* insertCustomEdge(qan::Node* source, qan::Node* destination); }; QML_DECLARE_TYPE(CustomGraph) #endif // CUSTOMGRAPH_H
#ifndef _STACK_H_ #define _STACK_H_ #include "Maze.h" static const int STACK_SIZE = 1024; class Stack { public: Stack() { Initialize(); } //~Stack(); bool Initialize(); bool Push(Node); Node Pop(); bool IsEmpty(); private: Node stack[STACK_SIZE]; int front; bool empty; }; bool Stack::Initialize() { #ifdef DEBUG cout<< "Initialize the stack." <<endl; #endif front = 0; empty = true; return true; } bool Stack::Push(Node node) { if(front < STACK_SIZE-1) { stack[++front] = node; empty = false; return true; } else { #ifdef DEBUG cout<< "Stack is full now." <<endl; #endif return false; } } Node Stack::Pop() { if(front > -1) { Node node = stack[front--]; return node; } else { #ifdef DEBUG cout<< "Stack is empty now." <<endl; #endif empty = true; } } bool Stack::IsEmpty() { return empty; } #endif //_STACK_H_
int state; void setup() { Serial.begin(38400); pinMode(LED_BUILTIN,OUTPUT); } void loop() { if(Serial.available()>0){ state=Serial.read(); Serial.println(state); if(state==120) digitalWrite(LED_BUILTIN,HIGH); else if(state==0) digitalWrite(LED_BUILTIN,LOW); } }
#include <iostream> #include <cstring> using namespace std; #define FASTIO \ ios_base::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0); int main() { FASTIO; int start, end; char dash, letter, colon; string line; int count = 0; while (cin >> start) { cin >> dash >> end >> letter >> colon >> line; start--; end--; // xor: either one or the other if ((line[start] == letter) ^ (line[end] == letter)) { count++; } } cout << count << endl; return 0; }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // Copyright (C) 1995-2003 Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // #ifndef WINDOWSCOMPLEXSCRIPT_H #define WINDOWSCOMPLEXSCRIPT_H namespace WIN32ComplexScriptSupport { void GetTextExtent(HDC hdc, const uni_char* str, int len, SIZE* s, INT32 extra_char_spacing); void TextOut(HDC hdc, int x, int y, const uni_char* text, int len); }; #endif // WINDOWSCOMPLEXSCRIPT_H
#ifndef MANGASTREAM_H #define MANGASTREAM_H #include "isdebug.h" #include <QObject> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QStringList> #include <QUrl> #include <QEventLoop> #include <QByteArray> #include <QIODevice> #include <QRegularExpression> class MangaStream : public QObject { Q_OBJECT public: Q_INVOKABLE QStringList getListOfManga(); Q_INVOKABLE QStringList getListOfChapters(QString url); Q_INVOKABLE QStringList getImages(QString url); private: QString getContentOfUrl(QString url); }; #endif // MANGASTREAM_H
/* =========================================================================== Copyright (C) 2017 waYne (CAM) =========================================================================== */ #pragma once #ifndef ELYSIUM_GRAPHICS_COMMANDPOOL #define ELYSIUM_GRAPHICS_COMMANDPOOL #endif #ifndef ELYSIUM_CORE_OBJECT #include "../../../Core/01-Shared/Elysium.Core/Object.hpp" #endif #ifndef ELYSIUM_GRAPHICS_GRAPHICSDEVICE #include "GraphicsDevice.hpp" #endif #ifndef ELYSIUM_GRAPHICS_COMMANDBUFFER #include "CommandBuffer.hpp" #endif #ifndef ELYSIUM_GRAPHICS_RENDERING_IWRAPPEDCOMMANDPOOL #include "IWrappedCommandPool.hpp" #endif using namespace Elysium::Core; using namespace Elysium::Graphics::Rendering; namespace Elysium { namespace Graphics { class EXPORT CommandPool : public Object { public: // constructors & destructor CommandPool(GraphicsDevice* GraphicsDevice, uint32_t QueueFamilyIndex); ~CommandPool(); // properties IWrappedCommandPool* GetWrappedCommandPool(); // methods CommandBuffer* AllocatedCommandBuffer(bool IsPrimaryBuffer); private: // fields IWrappedGraphicsDevice* _WrappedGraphicsDevice; IWrappedCommandPool* _WrappedCommandPool; }; } }
#include <ros.h> #include <std_msgs/UInt16.h> #include <Servo.h> #define SERVO_PIN 9 ros::NodeHandle nh; Servo servo; void servo_callback( const std_msgs::UInt16& cmd_msg){ servo.write(cmd_msg.data); // set servo angle digitalWrite(13, HIGH-digitalRead(13)); // toggle the led } ros::Subscriber<std_msgs::UInt16> sub("servo", servo_callback ); void setup() { pinMode(13, OUTPUT); nh.initNode(); nh.subscribe(sub); servo.attach(SERVO_PIN); } void loop() { nh.spinOnce(); }
#include <vector> #include <string> #include <gtest/gtest.h> #include "StringUtils.h" #include <TranscriberUI/PhoneticDictionaryViewModel.h> namespace PticaGovorunTests { using namespace PticaGovorun; struct StringEditDistanceTest : public testing::Test { }; template <typename Letter> class WordErrorCosts { public: typedef float CostType; static CostType getZeroCosts() { return 0; } inline CostType getInsertSymbolCost(Letter x) const { return 1; } inline CostType getRemoveSymbolCost(Letter x) const { return 1; } inline CostType getSubstituteSymbolCost(Letter x, Letter y) const { return x == y ? 0 : 1; } }; float charDist(const char* str1, const char* str2) { using namespace std; WordErrorCosts<char> c; float result = findEditDistanceNew<char, WordErrorCosts<char> >(string(str1), string(str2), c); return result; } float wordDist(const std::vector<std::wstring>& str1, const std::vector<std::wstring>& str2) { using namespace std; WordErrorCosts<std::wstring> c; float result = findEditDistanceNew<std::wstring, WordErrorCosts<std::wstring> >(str1, str2, c); return result; } TEST_F(StringEditDistanceTest, simple1) { ASSERT_EQ(1, charDist("a1", "b1")); // rests // stres~s ASSERT_EQ(3, charDist("rests", "stress")); // tea t~ea // toe toe~ ASSERT_EQ(2, charDist("tea", "toe")); } TEST_F(StringEditDistanceTest, wordAsLetter) { ASSERT_EQ(1, wordDist({ L"a", L"1" }, { L"b", L"1" })); // inserted ASSERT_EQ(1, wordDist({ L"a", L"1" }, { L"pre", L"a", L"1" })); // removed ASSERT_EQ(1, wordDist({ L"a", L"1" }, { L"1" })); } }
#include <iostream> #include <sstream> #include <cstdlib> #include <cstdio> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <iomanip> #include <set> #include <climits> #include <ctime> #include <complex> #include <cmath> #include <string> #include <cctype> #include <cstring> #include <algorithm> using namespace std; #define endl '\n' typedef pair<int,int> pii; typedef long double ld; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; const int maxn=105; const int INF=0x3f3f3f3f; const double pi=acos(-1.0); const double eps=1e-9; inline int sgn(double a) { return a<-eps? -1:a>eps; } int n; int a[maxn]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); // freopen("in.txt","r",stdin); // freopen("out.txt","w",stdout); int flag=0; cin>>n; for(int i=0; i<n; i++) cin>>a[i]; for(int i=1; i<n; i++) { if(flag==0) { if(a[i]>a[i-1]) continue; if(a[i]==a[i-1]) { flag=1; continue; } else { flag=3; continue; } } else if(flag==1) { if(a[i]==a[i-1]) continue; if(a[i]>a[i-1]) { cout<<"NO"; return 0; } if(a[i]<a[i-1]) { flag=3; continue; } } else if(flag==3) { if(a[i]<a[i-1]) continue; else { cout<<"NO"; return 0; } } } cout<<"YES"; return 0; }
#include "bsdf.h" #include <warpfunctions.h> BSDF::BSDF(const Intersection& isect, float eta /*= 1*/) //TODO: Properly set worldToTangent and tangentToWorld : worldToTangent(glm::transpose(Matrix3x3(isect.tangent,isect.bitangent,isect.normalGeometric))), tangentToWorld(Matrix3x3(isect.tangent,isect.bitangent,isect.normalGeometric)), // worldToTangent(Matrix3x3(isect.tangent,isect.bitangent,isect.normalGeometric)), // tangentToWorld(glm::transpose(worldToTangent)), normal(isect.normalGeometric), eta(eta), numBxDFs(0), bxdfs{nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr} {} BSDF::~BSDF() { for(int i=0;i<numBxDFs;i++) { delete bxdfs[i]; } } void BSDF::UpdateTangentSpaceMatrices(const Normal3f& n, const Vector3f& t, const Vector3f b) { //TODO: Update worldToTangent and tangentToWorld based on the normal, tangent, and bitangent // worldToTangent=Matrix3x3(t,b,n); // tangentToWorld=glm::transpose(Matrix3x3(t,b,n)); worldToTangent=glm::transpose(Matrix3x3(t,b,n)); tangentToWorld=Matrix3x3(t,b,n); } // Color3f BSDF::f(const Vector3f &woW, const Vector3f &wiW, BxDFType flags /*= BSDF_ALL*/) const { //TODO //return Color3f(0.f); //compute all BSDF Color3f f(0.0f); Vector3f wo=worldToTangent*woW; Vector3f wi=worldToTangent*wiW; bool is_reflect= glm::dot(wiW, normal)*glm::dot(woW,normal)>0; f=Color3f(0.0f); for(int i=0;i<numBxDFs;i++) { if(bxdfs[i]->MatchesFlags(flags) && ((is_reflect && (bxdfs[i]->type & BSDF_REFLECTION))|| (!is_reflect && (bxdfs[i]->type &BSDF_TRANSMISSION)))) { f += bxdfs[i]->f(wo,wi); } } return f; } // Use the input random number _xi_ to select // one of our BxDFs that matches the _type_ flags. // After selecting our random BxDF, rewrite the first uniform // random number contained within _xi_ to another number within // [0, 1) so that we don't bias the _wi_ sample generated from // BxDF::Sample_f. // Convert woW and wiW into tangent space and pass them to // the chosen BxDF's Sample_f (along with pdf). // Store the color returned by BxDF::Sample_f and convert // the _wi_ obtained from this function back into world space. // Iterate over all BxDFs that we DID NOT select above (so, all // but the one sampled BxDF) and add their PDFs to the PDF we obtained // from BxDF::Sample_f, then average them all together. // Finally, iterate over all BxDFs and sum together the results of their // f() for the chosen wo and wi, then return that sum. Color3f BSDF::Sample_f(const Vector3f &woW, Vector3f *wiW, const Point2f &xi, float *pdf, BxDFType type, BxDFType *sampledType) const { //TODO //choose BxDF int matchtype=BxDFsMatchingFlags(type); if(matchtype==0) { *pdf=0.0f; if(sampledType) *sampledType=BxDFType(0); return Color3f(0.0f); } //generate random BxDF type using xi int bxdf_type = std::min((int)std::floor(xi[0]*matchtype),matchtype-1); BxDF* bxdf = nullptr; int count=bxdf_type; for(int i=0;i<numBxDFs;i++) { if(bxdfs[i]->MatchesFlags(type) && count--==0) { bxdf=bxdfs[i]; break; } } //rewrite xi Point2f xi_new=Point2f(std::min(xi[0]*matchtype-bxdf_type,OneMinusEpsilon),xi[1]); //sample chosen BxDF Vector3f wi; Vector3f wo=worldToTangent*woW; //wo=glm::normalize(wo); if(fabs(wo.z)<FLT_EPSILON) return Color3f(0.0f); *pdf=0.0f; if(sampledType) *sampledType=bxdf->type; //compute f of BxDF Color3f f=bxdf->Sample_f(wo,&wi,xi_new,pdf,sampledType); if(fabs(*pdf)<FLT_EPSILON) { if(sampledType) *sampledType=BxDFType(0); return Color3f(0.0f); } *wiW=tangentToWorld*wi; //wiW=glm::normalize(*wiW); //compute all pdf if(!(bxdf->type & BSDF_SPECULAR)&& matchtype>1) { for(int i=0;i<numBxDFs;++i) { if(bxdfs[i]!=bxdf && bxdfs[i]->MatchesFlags(type)) { *pdf+=bxdfs[i]->Pdf(wo,wi); } } } if(matchtype>1) *pdf/=matchtype; //compute all BSDF if(!(bxdf->type &BSDF_SPECULAR) && matchtype>1) { bool is_reflect= glm::dot(*wiW, normal)*glm::dot(woW,normal)>0; f=Color3f(0.0f); for(int i=0;i<numBxDFs;i++) { if(bxdfs[i]->MatchesFlags(type) && ((is_reflect && (bxdfs[i]->type & BSDF_REFLECTION))|| (!is_reflect && (bxdfs[i]->type &BSDF_TRANSMISSION)))) { f += bxdfs[i]->f(wo,wi); } } } // if(!(bxdf->type & BSDF_SPECULAR)&& matchtype>1) // { // *pdf+=this->Pdf(woW,*wiW,type); // } // if(!(bxdf->type &BSDF_SPECULAR) && matchtype>1) // { // f += this->f(woW,*wiW,type); // } return f; // //return Color3f(0.f); // Choose which BxDF to sample // int matchingComps = BxDFsMatchingFlags(type); // if (matchingComps == 0) // { // *pdf = 0; // if (sampledType) *sampledType = BxDFType(0); // return Color3f(0.f); // } // // Choose a BxDF at random from the set of candidates: // // Get an index that falls within the set of matching BxDFs using one of our // // pair of uniform random variables // //int comp = std::min((int)std::floor(xi[0] * matchingComps), matchingComps ‐ 1); // int comp=std::min((int)std::floor(xi[0]*matchingComps),matchingComps-1); // BxDF* bxdf = nullptr; // int count = comp; // for (int i = 0; i < numBxDFs; ++i) // { // if(bxdfs[i]->MatchesFlags(type) &&count-- ==0) // { // bxdf=bxdfs[i]; // break; // } // } // // Remap BxDF sample xi to [0,1)^2 // // If we don't do this, then we bias the _wi_ sample // // we'll get from BxDF::Sample_f, e.g. if we have two // // BxDFs each with a probability of 0.5 of being chosen, then // // when we sample the first BxDF (xi[0] = [0, 0.5)) we'll ALWAYS // // use a value between 0 and 0.5 to generate our wi for that BxDF. // //Point2f xiRemapped(std::min(xi[0] * matchingComps ‐ comp,OneMinusEpsilon),xi[1]); // Point2f xiRemapped(std::min(xi[0]*matchingComps-comp,OneMinusEpsilon),xi[1]); // // Sample chosen BxDF // Vector3f wi; // Vector3f wo = worldToTangent * woW; // Remember to convert woW to tangent space! // if (wo.z == 0) return Color3f(0.f); // The tangent‐space wo is perpendicular to the normal, // // so Lambert's law reduces its contribution to 0. // *pdf = 0; // if (sampledType) {*sampledType = bxdf->type;} // // Sample a tangent‐space wi based on the BxDF's PDF and then // // compute the BxDF::f of the chosen BxDF based on wi. // Color3f f = bxdf->Sample_f(wo, &wi, xiRemapped, pdf, sampledType); // if (*pdf == 0) // { // if (sampledType) {*sampledType = BxDFType(0);} // return Color3f(0.f); // } // *wiW = tangentToWorld * wi; // // Compute overall PDF with all matching BxDFs // // We treat specular BxDFs differently because their PDFs // // are delta distributions (0 in all cases but the *one* case // // where wi = reflect(wo, N), and 1 in that case) // if(!(bxdf->type & BSDF_SPECULAR) && matchingComps > 1) // { // for (int i = 0; i < numBxDFs; ++i) // { // if (bxdfs[i] != bxdf && bxdfs[i]->MatchesFlags(type)) // { // *pdf += bxdfs[i]->Pdf(wo, wi); // } // } // } // if (matchingComps > 1) *pdf /= matchingComps; // // Compute the overall value of this BSDF for sampled direction wiW // // This means looking at the rest of the BxDFs that match _type_ // // and invoking their implementations of BxDF::f. // // Again, we're going to skip this if the randomly chosen // // BxDF is specular because its PDF is a delta distribution. // if (!(bxdf->type & BSDF_SPECULAR) && matchingComps > 1) // { // bool reflect = glm::dot(*wiW, normal) * glm::dot(woW, normal) > 0; // f = Color3f(0.f); // for (int i = 0; i < numBxDFs; ++i) // { // if (bxdfs[i]->MatchesFlags(type) && // ((reflect && (bxdfs[i]->type & BSDF_REFLECTION)) || // (!reflect && (bxdfs[i]->type & BSDF_TRANSMISSION)))) // { // f += bxdfs[i]->f(wo, wi); // } // } // } // return f; } float BSDF::Pdf(const Vector3f &woW, const Vector3f &wiW, BxDFType flags) const { //TODO if(numBxDFs ==0) return 0.0f; Vector3f wo=worldToTangent*woW; Vector3f wi=worldToTangent*wiW; if(wo.z==0.0f) return 0.0f; Float pdf=0.0f; int matchNum=0; for(int i=0;i<numBxDFs;i++) { if(bxdfs[i]->MatchesFlags(flags)) { ++matchNum; pdf+=bxdfs[i]->Pdf(wo,wi); } } float final_pdf=0.0f; if(matchNum>0) final_pdf=pdf/matchNum; return final_pdf; //return 0.f; } Color3f BxDF::Sample_f(const Vector3f &wo, Vector3f *wi, const Point2f &xi, Float *pdf, BxDFType *sampledType) const { //TODO if(!sampledType) { *sampledType=BxDFType(0); return Color3f(0.0f); } *wi=WarpFunctions::squareToHemisphereUniform(xi); if(wo.z<0.0f) wi->z*=-1.0f; Color3f s_f=f(wo,*wi); *pdf=Pdf(wo,*wi); return s_f; } // The PDF for uniform hemisphere sampling float BxDF::Pdf(const Vector3f &wo, const Vector3f &wi) const { return SameHemisphere(wo, wi) ? Inv2Pi : 0; }
#include <LPD8806.h> #include <SPI.h> #include <Adafruit_NeoPixel.h> #include "Animation.h" #include "MovingAnimation.h" #include "SpinningAnimation.h" #include "PulseAnimation.h" #include "BouncingAnimation.h" #include "FireBearsAnimation.h" #include "BlinkAnimation.h" #include "CatchFire.h" #include "OneColor.h" #include "Words.h" #include "Glowing.h" #include <Wire.h> #include "strips.h" #include "comm.h" Adafruit_NeoPixel strips[3] = { Adafruit_NeoPixel(NUM_PIXL_0, PIN_STRIP_0, NEO_GRB + NEO_KHZ800), Adafruit_NeoPixel(NUM_PIXL_1, PIN_STRIP_1, NEO_GRB + NEO_KHZ800), Adafruit_NeoPixel(NUM_PIXL_2, PIN_STRIP_2, NEO_GRB + NEO_KHZ800) }; LPD8806 dc_strips[3] = { LPD8806(NUM_PICL_0, DAT_STRIP_0, CLK_STRIP_0), LPD8806(NUM_PICL_1, DAT_STRIP_1, CLK_STRIP_1), LPD8806(NUM_PICL_2, DAT_STRIP_2, CLK_STRIP_2) }; variables_t *G_Vars; FireBearsAnimation *fb; MovingAnimation *mv; BlinkAnimation *bl; BouncingAnimation *bn; CatchFire *cf; OneColor *oc; Words *wd; Glowing *gl; char ByteA = LT_NERROR; //error char ByteB = LT_ERR_RWS; //request without send char RecvA[16]; char RecvB[16]; char AtRcv = 0; boolean NullPacket = false; //Temporary Variable Values For Recieving Stuff boolean FirstByte = true; char fc[2]; uint8_t DoDecode = 0; uint8_t GDefCol = 1; uint8_t GDefStr = 0; void reset_gvars(int strip, uint8_t animType) { G_Vars[strip].anim_type = animType; G_Vars[strip].progress = 0; G_Vars[strip].time = 0; G_Vars[strip].isSparking = true; G_Vars[strip].isPausing = true; G_Vars[strip].toQuit = false; G_Vars[strip].lastTime = 0; G_Vars[strip].SLastTime = 0; G_Vars[strip].reset = true; G_Vars[strip].mode = 0; G_Vars[strip].defColInPallet = 9; G_Vars[strip].Goto_Anim = ALLL_ANIM; } void strip_init(boolean isSPI, int strip, uint8_t len, uint8_t animType) { // Initialize and reset the LED strip if(isSPI) { dc_strips[strip-3].begin(); for (int p=0; p<G_Vars[strip-3].color_len; p++) { dc_strips[strip-3].setPixelColor(p, 0); dc_strips[strip-3].show(); } }else{ strips[strip].begin(); for (int p=0; p<G_Vars[strip].color_len; p++) { strips[strip].setPixelColor(p, 0); strips[strip].show(); } } //global vars... Serial.println("strip initing"); int objectCount = (len/5)+1; G_Vars[strip].color = new uint32_t[len]; G_Vars[strip].color_store = new uint32_t[len]; G_Vars[strip].color_pos = new uint8_t[objectCount]; G_Vars[strip].color_hom = new uint8_t[objectCount]; G_Vars[strip].color_dir = new uint8_t[objectCount*5]; G_Vars[strip].objectCount = objectCount; reset_gvars(strip, animType); G_Vars[strip].color_len = len; G_Vars[strip].isCopper = isSPI; Serial.println("strip inited"); return; } static inline void na_reset(void) { int i, p; Serial.println("reset"); delay(100); // delay(100); cf = new CatchFire(); fb = new FireBearsAnimation(); mv = new MovingAnimation(); bl = new BlinkAnimation(); bn = new BouncingAnimation(); oc = new OneColor(); // wd = new Words(); gl = new Glowing(); Serial.print("classes made, "); print_free_bytes(); delay(100); Serial.println("set strips.."); delay(100); strip_init(false,0, NUM_PIXL_0, ALLL_ANIM); strip_init(false,1, NUM_PIXL_1, ALLL_ANIM); strip_init(false,2, NUM_PIXL_2, ALLL_ANIM); strip_init(true,3, NUM_PICL_0, CAFR_ANIM); strip_init(true,4, NUM_PICL_1, CAFR_ANIM); strip_init(true,5, NUM_PICL_2, CAFR_ANIM); } void setup() { G_Vars = new variables_t[/*STRIP_COUNT+SPIIP_COUNT*/6]; Serial.begin(9600); Serial.print("JLights: loading.... / "); print_free_bytes(); delay(100); Wire.begin(SLAVE_ADDRESS); // join i2c bus with address SLAVE_ADRESS Wire.onReceive(na_receiveEvent); // register event Wire.onRequest(na_requestEvent); // register event delay(10); na_reset(); Serial.print("ANIMATION(done loading!), "); print_free_bytes(); delay(100); #ifdef BACKUP pinMode(12, INPUT); #endif } void na_animate(int strip) { if((G_Vars[strip].anim_type==ALLL_ANIM) && (G_Vars[strip].SLastTime+5000 <= millis())) { G_Vars[strip].SLastTime += 5000; G_Vars[strip].mode++; if(G_Vars[strip].mode >4) { G_Vars[strip].mode= 0; } G_Vars[strip].reset = true; } if(G_Vars[strip].anim_type == FIRE_ANIM || ((G_Vars[strip].mode == 0)&&G_Vars[strip].anim_type==ALLL_ANIM)) { if(G_Vars[strip].reset) { fb->reset(&G_Vars[strip]); } fb->loop(&G_Vars[strip]); }else if(G_Vars[strip].anim_type == MOVE_ANIM || ((G_Vars[strip].mode == 1)&&G_Vars[strip].anim_type==ALLL_ANIM)) { if(G_Vars[strip].reset) { mv->reset(&G_Vars[strip]); } mv->loop(&G_Vars[strip]); }else if(G_Vars[strip].anim_type == BLNK_ANIM || ((G_Vars[strip].mode == 2)&&G_Vars[strip].anim_type==ALLL_ANIM)) { if(G_Vars[strip].reset) { bl->reset(&G_Vars[strip]); } bl->loop(&G_Vars[strip]); }else if(G_Vars[strip].anim_type == BNCE_ANIM || ((G_Vars[strip].mode == 3)&&G_Vars[strip].anim_type==ALLL_ANIM)) { if(G_Vars[strip].reset) { bn->reset(&G_Vars[strip]); } bn->loop(&G_Vars[strip]); }else if(G_Vars[strip].anim_type == CAFR_ANIM) { if(G_Vars[strip].reset) { cf->reset(&G_Vars[strip]); } cf->loop(&G_Vars[strip]); if(G_Vars[strip].toQuit) { G_Vars[strip].anim_type = G_Vars[strip].Goto_Anim; G_Vars[strip].Goto_Anim = FIRE_ANIM; G_Vars[strip].lastTime = millis(); G_Vars[strip].SLastTime = millis(); G_Vars[strip].mode = 0; } }else if(G_Vars[strip].anim_type == ONCO_ANIM) { if(G_Vars[strip].reset) { oc->reset(&G_Vars[strip], GDefCol); } oc->loop(&G_Vars[strip]); }else if(G_Vars[strip].anim_type == WORD_ANIM) { if(G_Vars[strip].reset) { wd->reset(&G_Vars[strip]); } wd->loop(&G_Vars[strip]); if(G_Vars[strip].toQuit) { G_Vars[strip].anim_type = ONCO_ANIM; } }else if((G_Vars[strip].anim_type == GLOW_ANIM) || ((G_Vars[strip].mode == 4)&&G_Vars[strip].anim_type==ALLL_ANIM)) { if(G_Vars[strip].reset) { gl->reset(&G_Vars[strip]); } gl->loop(&G_Vars[strip]); } int i; if(strip >= 3) { for (i = 0; i < G_Vars[strip].color_len; i++) {//draw dc_strips[strip-3].setPixelColor(i, G_Vars[strip].color[i]); } dc_strips[strip-3].show(); }else{ for (i = 0; i < G_Vars[strip].color_len; i++) {//draw strips[strip].setPixelColor(i, G_Vars[strip].color[i]); } strips[strip].show(); } G_Vars[strip].reset = false; } void loop() { // Serial.println("loop"); delay(100); while(DoDecode) { na_decodeRecieve(RecvA[DoDecode],RecvB[DoDecode]); DoDecode--; } for(int ii = 0; ii < STRIP_COUNT+SPIIP_COUNT; ii++) { na_animate(ii); } #ifdef BACKUP if(digitalRead(12)) { na_setStrip(0, ONCO_ANIM); na_setStrip(1, ONCO_ANIM); na_setStrip(2, ONCO_ANIM); na_setStrip(3, ONCO_ANIM); na_setStrip(4, ONCO_ANIM); na_setStrip(5, ONCO_ANIM); }else{ na_setStrip(0, ALLL_ANIM); na_setStrip(1, ALLL_ANIM); na_setStrip(2, ALLL_ANIM); na_setStrip(3, ALLL_ANIM); na_setStrip(4, ALLL_ANIM); na_setStrip(5, ALLL_ANIM); } #endif } void na_setStrip(int stripToSet, char setTo) { G_Vars[stripToSet].reset = true; if(setTo == 0x21) { reset_gvars(stripToSet, FIRE_ANIM); } else if(setTo == 0x22) { reset_gvars(stripToSet, MOVE_ANIM); } else if(setTo == 0x23) { reset_gvars(stripToSet, BLNK_ANIM); } else if(setTo == 0x24) { reset_gvars(stripToSet, BNCE_ANIM); } else if(setTo == 0x25) { reset_gvars(stripToSet, ALLL_ANIM); } else if(setTo == 0x26) { reset_gvars(stripToSet, SPIN_ANIM); } else if(setTo == 0x27) { reset_gvars(stripToSet, PULS_ANIM); } else if(setTo == 0x28) { reset_gvars(stripToSet, CAFR_ANIM); } else if(setTo == 0x29) { reset_gvars(stripToSet, ONCO_ANIM); } else if(setTo == 0x2A) { reset_gvars(stripToSet, GLOW_ANIM); } else { ByteA = LT_NERROR; //error ByteB = LT_ERR_NSA; //no such animation } } static void na_set_s00(char p_B2) { na_setStrip(0, p_B2); } static void na_set_s11(char p_B2) { na_setStrip(1, p_B2); } static void na_set_s22(char p_B2) { na_setStrip(2, p_B2); } static void na_set_s33(char p_B2) { na_setStrip(3, p_B2); } static void na_set_s44(char p_B2) { na_setStrip(4, p_B2); } static void na_set_s55(char p_B2) { na_setStrip(5, p_B2); } static void na_set_s01(char p_B2) { na_set_s00(p_B2); na_set_s11(p_B2); } static inline void na_set_all(char p_B2) { na_set_s01(p_B2); //0, 1 na_set_s22(p_B2); na_set_s33(p_B2); na_set_s44(p_B2); na_set_s55(p_B2); } const char *setCodes[8] = { "all strips", "strip 1", "strip 2", "strip 3", "strip 1 & 2", "strip 2 & 3", "strip 1 & 3", "verify" }; void na_decodeRecieve(char p_B1, char p_B2) { uint8_t f_B = p_B2 - 0x10; ByteB = p_B2; //to: value of p_B2 Serial.print((int)ByteB); Serial.print(","); Serial.print((int)0x53); if(f_B < 8) Serial.println(setCodes[f_B]); if(p_B1 == 0x10) { na_set_all(p_B2); ByteA = LT_HAS_ALL; //set all strips }else if(p_B1 == 0x11) { na_set_s00(p_B2); ByteA = LT_HAS_S01; //set strip 1 }else if(p_B1 == 0x12) { na_set_s11(p_B2); ByteA = LT_HAS_S02; //set strip 2 }else if(p_B1 == 0x13) { na_set_s22(p_B2); ByteA = LT_HAS_S03; //set strip 3 }else if(p_B1 == 0x14) { na_set_s01(p_B2); //0, 1 ByteA = LT_HAS_S12; //set strip 1&2 }else if(p_B1 == 0x15) { na_setStrip(1, p_B2); na_setStrip(2, p_B2); ByteA = LT_HAS_S23; //set strip 2&3 }else if(p_B1 == 0x16) { na_setStrip(0, p_B2); na_setStrip(2, p_B2); ByteA = LT_HAS_S13; //set strip 1&3 }else if(p_B1 == 0x17) { //test connection if(p_B2 == 0x4C) { ByteA = LT_VERIFY; //verification ByteB = LT_MAGIC; //magic byte }else{ ByteA = LT_NERROR; //error ByteB = LT_ERR_WSB; //wrong second byte[verify] } }else if(p_B1 == 0x18) { //Set Default Color GDefCol = p_B2; ByteA = LT_HAS_DCS; }else if(p_B1 == 0x19) { //Set Default String GDefStr = p_B2; ByteA = LT_HAS_DCS; }else if(p_B1 == 0x1A) { //Set Copper Strip 1 na_setStrip(3, p_B2); ByteA = LT_HAS_C01; }else if(p_B1 == 0x1B) { //Set Copper Strip 2 na_setStrip(4, p_B2); ByteA = LT_HAS_C02; }else if(p_B1 == 0x1C) { //Set Copper Strip 3 na_setStrip(5, p_B2); ByteA = LT_HAS_C03; }else if(p_B1 == 0x1D) { //Set Copper Strip 1&2 na_setStrip(3, p_B2); na_setStrip(4, p_B2); ByteA = LT_HAS_C12; }else if(p_B1 == 0x1E) { //Set Copper Strip 2&3 na_setStrip(4, p_B2); na_setStrip(5, p_B2); ByteA = LT_HAS_C23; }else if(p_B1 == 0x1F) { //Set Copper Strip 1&3 na_setStrip(5, p_B2); na_setStrip(3, p_B2); ByteA = LT_HAS_C13; }else{ Serial.println("ERROR"); ByteA = LT_NERROR; //error ByteB = LT_ERR_NSS; //couldn't send strip: no such strip } } static inline void na_process_byte(byte p_byte) { if(FirstByte) { fc[0] = p_byte; // receive byte as a character FirstByte = false; }else{ fc[1] = p_byte; // receive byte as a character RecvA[DoDecode] = fc[0]; RecvB[DoDecode] = fc[1]; DoDecode++; FirstByte = true; } } void na_receiveEvent(int howMany) { // Serial.println("R"); //Check If Packet Is Null if(howMany == 0) { Serial.println("No byte packet!"); NullPacket = true; return; }else{ NullPacket = false; } //Check Byte Count if(howMany != 2) { Serial.println(); Serial.print("wrong packet size: not 2: "); Serial.println(howMany); return; } //loop through all bytes while(Wire.available() > 0) { na_process_byte(Wire.read()); // receive byte as a character } //Debugging Information Serial.print("RECV EVENT("); Serial.print(howMany); Serial.print("):"); Serial.print((int)RecvA); Serial.print(","); Serial.println((int)RecvB); } void na_requestEvent() { char Sender[2]; if(NullPacket) { return; } Serial.print("Sending:"); // respond with message of 2 bytes Serial.print((int)ByteA); Serial.print(","); Serial.print((int)ByteB); Serial.print("..."); Sender[0] = ByteA; Sender[1] = ByteB; Wire.write(Sender); Serial.println("sent!"); ByteA = LT_NERROR; //error ByteB = LT_ERR_RWS; //request without send } void print_free_bytes(void) { Serial.print("free:"); Serial.println(memoryFree()); } extern int __bss_end; extern void *__brkval; static inline int memoryFree() { int freeValue; if((int)__brkval == 0) freeValue = ((int)&freeValue) - ((int)&__bss_end); else freeValue = ((int)&freeValue) - ((int)__brkval); return freeValue; }