<commit_before>#include "genstoreDefines.sqf"

class genstored {

	idd = genstore_DIALOG;
	movingEnable = true;
	enableSimulation = true;
	onLoad = "[0] execVM 'client\systems\generalStore\populateGenStore.sqf'";

	class controlsBackground {

		class MainBackground: w_RscPicture
		{
			idc = -1;
			colorText[] = {1, 1, 1, 1};
		    colorBackground[] = {0,0,0,0};
			text = "#(argb,8,8,3)color(0,0,0,0.6)";
			moving = true;
			x = 0.1875 * safezoneW + safezoneX;
			y = 0.15 * safezoneH + safezoneY;
			w = 0.55 * safezoneW;
			h = 0.65 * safezoneH;
		};

		class TopBar: w_RscPicture
		{
			idc = -1;
			colorText[] = {1, 1, 1, 1};
			colorBackground[] = {0,0,0,0};
			text = "#(argb,8,8,3)color(0.25,0.51,0.96,0.8)";

			x = 0.1875 * safezoneW + safezoneX;
			y = 0.15 * safezoneH + safezoneY;
			w = 0.55 * safezoneW;
			h = 0.05 * safezoneH;
		};

		class DialogTitleText: w_RscText
		{
			idc = -1;
			text = "General Store Menu";
			font = "PuristaMedium";
			sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
			x = 0.20 * safezoneW + safezoneX;
			y = 0.155 * safezoneH + safezoneY;
			w = 0.19 * safezoneW;
			h = 0.0448148 * safezoneH;
		};

		class PlayerMoneyText: w_RscText
		{
			idc = genstore_money;
			text = "Cash:";
			font = "PuristaMedium";
			sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
			x = 0.640 * safezoneW + safezoneX;
			y = 0.155 * safezoneH + safezoneY;
			w = 0.0844792 * safezoneW;
			h = 0.0448148 * safezoneH;
		};

		class ItemSelectedPrice: w_RscStructuredTextLeft
		{
			idc = genstore_item_TEXT;
			text = "";

			x = 0.299 * safezoneW + safezoneX;
			y = 0.664 * safezoneH + safezoneY;
			w = 0.0891667 * safezoneW;
			h = 0.068889 * safezoneH;
		};

		class SellSelectedPrice: w_RscStructuredTextLeft
		{
			idc = genstore_sell_TEXT;
			text = "";

			x = 0.517 * safezoneW + safezoneX;
			y = 0.664 * safezoneH + safezoneY;
			w = 0.0891667 * safezoneW;
			h = 0.068889 * safezoneH;
		};
	};

	class controls {

		class SelectionList: w_RscList
		{
			idc = genstore_item_list;
			onLBSelChanged = "[] execvm 'client\systems\generalStore\itemInfo.sqf'";
			font = "PuristaMedium";
			sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
			x = 0.3025 * safezoneW + safezoneX;
			y = 0.225 * safezoneH + safezoneY;
			w = 0.207 * safezoneW;
			h = 0.338222 * safezoneH;
		};

		class ItemDescription: w_RscStructuredTextLeft
		{
			idc = genstore_item_desc;
			text = "";
			sizeEx = 0.02;
			colorBackground[] = { 0, 0, 0, 0.1 };
			x = 0.3025 * safezoneW + safezoneX;
			y = 0.567 * safezoneH + safezoneY;
			w = 0.207 * safezoneW;
			h = 0.088 * safezoneH;
		};

		class SellList: w_RscList
		{
			idc = genstore_sell_list;
			onLBSelChanged = "[] execvm 'client\systems\generalStore\sellInfo.sqf'";
			font = "PuristaMedium";
			sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
			x = 0.520 * safezoneW + safezoneX;
			y = 0.225 * safezoneH + safezoneY;
			w = 0.207 * safezoneW;
			h = 0.422222 * safezoneH;
		};

		class SellWeapon: w_RscButton
		{
			idc = -1;
			onButtonClick = "[] execVM 'client\systems\selling\sellWeapon.sqf'";
			text = "Sell Weapon";

			x = 0.360 * safezoneW + safezoneX;
			y = 0.740 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class SellUniform: w_RscButton
		{
			idc = -1;
			onButtonClick = "[] execVM 'client\systems\selling\sellUniform.sqf'";
			text = "Sell Uniform";
			x = 0.453 * safezoneW + safezoneX;
			y = 0.740 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

        class SellVest: w_RscButton
		{
			idc = -1;
			onButtonClick = "[] execVM 'client\systems\selling\sellVest.sqf'";
			text = "Sell Vest";

			x = 0.546 * safezoneW + safezoneX;
			y = 0.740 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class SellBackpack: w_RscButton
		{
			idc = -1;
			onButtonClick = "[] execVM 'client\systems\selling\sellBackpack.sqf'";
			text = "Sell Backpack";

			x = 0.639 * safezoneW + safezoneX;
			y = 0.740 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class CancelButton : w_RscButton {

			idc = -1;
			text = "Cancel";
			onButtonClick = "closeDialog 0;";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.740 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class SellItem: w_RscButton
		{
			idc = genstore_sell;
			onButtonClick = "[0] execVM 'client\systems\generalStore\sellItems.sqf'";
			text = "Sell";

			x = 0.655 * safezoneW + safezoneX;
			y = 0.657 * safezoneH + safezoneY;
			w = 0.072 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class BuyItem: w_RscButton
		{
			idc = -1;
			onButtonClick = "[0] execVM 'client\systems\generalStore\buyItems.sqf'";
			text = "Buy";

			x = 0.438 * safezoneW + safezoneX;
			y = 0.657 * safezoneH + safezoneY;
			w = 0.072 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class StoreButton0: w_RscButton
		{
			idc = -1;
			onButtonClick = "[0] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Headgear";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.225 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;

		};

		class StoreButton1: w_RscButton
		{
			idc = -1;
			onButtonClick = "[1] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Uniforms";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.275 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;

		};

		class StoreButton2: w_RscButton
		{
			idc = -1;
			onButtonClick = "[2] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Vests";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.325 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class StoreButton3: w_RscButton
		{
			idc = -1;
			onButtonClick = "[3] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Backpacks";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.375 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class StoreButton4: w_RscButton
		{
			idc = -1;
			onButtonClick = "[4] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Equipment";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.425 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class StoreButton5: w_RscButton
		{
			idc = -1;
			onButtonClick = "[5] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Items";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.475 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class StoreButton6: w_RscButton
		{
			idc = -1;
			onButtonClick = "[6] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Objects";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.525 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};
	};
};

<commit_msg>Changed genstore categories text<commit_after>#include "genstoreDefines.sqf"

class genstored {

	idd = genstore_DIALOG;
	movingEnable = true;
	enableSimulation = true;
	onLoad = "[0] execVM 'client\systems\generalStore\populateGenStore.sqf'";

	class controlsBackground {

		class MainBackground: w_RscPicture
		{
			idc = -1;
			colorText[] = {1, 1, 1, 1};
		    colorBackground[] = {0,0,0,0};
			text = "#(argb,8,8,3)color(0,0,0,0.6)";
			moving = true;
			x = 0.1875 * safezoneW + safezoneX;
			y = 0.15 * safezoneH + safezoneY;
			w = 0.55 * safezoneW;
			h = 0.65 * safezoneH;
		};

		class TopBar: w_RscPicture
		{
			idc = -1;
			colorText[] = {1, 1, 1, 1};
			colorBackground[] = {0,0,0,0};
			text = "#(argb,8,8,3)color(0.25,0.51,0.96,0.8)";

			x = 0.1875 * safezoneW + safezoneX;
			y = 0.15 * safezoneH + safezoneY;
			w = 0.55 * safezoneW;
			h = 0.05 * safezoneH;
		};

		class DialogTitleText: w_RscText
		{
			idc = -1;
			text = "General Store Menu";
			font = "PuristaMedium";
			sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
			x = 0.20 * safezoneW + safezoneX;
			y = 0.155 * safezoneH + safezoneY;
			w = 0.19 * safezoneW;
			h = 0.0448148 * safezoneH;
		};

		class PlayerMoneyText: w_RscText
		{
			idc = genstore_money;
			text = "Cash:";
			font = "PuristaMedium";
			sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
			x = 0.640 * safezoneW + safezoneX;
			y = 0.155 * safezoneH + safezoneY;
			w = 0.0844792 * safezoneW;
			h = 0.0448148 * safezoneH;
		};

		class ItemSelectedPrice: w_RscStructuredTextLeft
		{
			idc = genstore_item_TEXT;
			text = "";

			x = 0.299 * safezoneW + safezoneX;
			y = 0.664 * safezoneH + safezoneY;
			w = 0.0891667 * safezoneW;
			h = 0.068889 * safezoneH;
		};

		class SellSelectedPrice: w_RscStructuredTextLeft
		{
			idc = genstore_sell_TEXT;
			text = "";

			x = 0.517 * safezoneW + safezoneX;
			y = 0.664 * safezoneH + safezoneY;
			w = 0.0891667 * safezoneW;
			h = 0.068889 * safezoneH;
		};
	};

	class controls {

		class SelectionList: w_RscList
		{
			idc = genstore_item_list;
			onLBSelChanged = "[] execvm 'client\systems\generalStore\itemInfo.sqf'";
			font = "PuristaMedium";
			sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
			x = 0.3025 * safezoneW + safezoneX;
			y = 0.225 * safezoneH + safezoneY;
			w = 0.207 * safezoneW;
			h = 0.338222 * safezoneH;
		};

		class ItemDescription: w_RscStructuredTextLeft
		{
			idc = genstore_item_desc;
			text = "";
			sizeEx = 0.02;
			colorBackground[] = { 0, 0, 0, 0.1 };
			x = 0.3025 * safezoneW + safezoneX;
			y = 0.567 * safezoneH + safezoneY;
			w = 0.207 * safezoneW;
			h = 0.088 * safezoneH;
		};

		class SellList: w_RscList
		{
			idc = genstore_sell_list;
			onLBSelChanged = "[] execvm 'client\systems\generalStore\sellInfo.sqf'";
			font = "PuristaMedium";
			sizeEx = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";
			x = 0.520 * safezoneW + safezoneX;
			y = 0.225 * safezoneH + safezoneY;
			w = 0.207 * safezoneW;
			h = 0.422222 * safezoneH;
		};

		class SellWeapon: w_RscButton
		{
			idc = -1;
			onButtonClick = "[] execVM 'client\systems\selling\sellWeapon.sqf'";
			text = "Sell Weapon";

			x = 0.360 * safezoneW + safezoneX;
			y = 0.740 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class SellUniform: w_RscButton
		{
			idc = -1;
			onButtonClick = "[] execVM 'client\systems\selling\sellUniform.sqf'";
			text = "Sell Uniform";
			x = 0.453 * safezoneW + safezoneX;
			y = 0.740 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

        class SellVest: w_RscButton
		{
			idc = -1;
			onButtonClick = "[] execVM 'client\systems\selling\sellVest.sqf'";
			text = "Sell Vest";

			x = 0.546 * safezoneW + safezoneX;
			y = 0.740 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class SellBackpack: w_RscButton
		{
			idc = -1;
			onButtonClick = "[] execVM 'client\systems\selling\sellBackpack.sqf'";
			text = "Sell Backpack";

			x = 0.639 * safezoneW + safezoneX;
			y = 0.740 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class CancelButton : w_RscButton {

			idc = -1;
			text = "Cancel";
			onButtonClick = "closeDialog 0;";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.740 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class SellItem: w_RscButton
		{
			idc = genstore_sell;
			onButtonClick = "[0] execVM 'client\systems\generalStore\sellItems.sqf'";
			text = "Sell";

			x = 0.655 * safezoneW + safezoneX;
			y = 0.657 * safezoneH + safezoneY;
			w = 0.072 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class BuyItem: w_RscButton
		{
			idc = -1;
			onButtonClick = "[0] execVM 'client\systems\generalStore\buyItems.sqf'";
			text = "Buy";

			x = 0.438 * safezoneW + safezoneX;
			y = 0.657 * safezoneH + safezoneY;
			w = 0.072 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class StoreButton0: w_RscButton
		{
			idc = -1;
			onButtonClick = "[0] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Headgear";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.225 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;

		};

		class StoreButton1: w_RscButton
		{
			idc = -1;
			onButtonClick = "[1] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Uniforms";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.275 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;

		};

		class StoreButton2: w_RscButton
		{
			idc = -1;
			onButtonClick = "[2] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Vests";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.325 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class StoreButton3: w_RscButton
		{
			idc = -1;
			onButtonClick = "[3] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Backpacks";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.375 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class StoreButton4: w_RscButton
		{
			idc = -1;
			onButtonClick = "[4] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Items";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.425 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class StoreButton5: w_RscButton
		{
			idc = -1;
			onButtonClick = "[5] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Supplies";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.475 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};

		class StoreButton6: w_RscButton
		{
			idc = -1;
			onButtonClick = "[6] execVM 'client\systems\generalStore\populateGenStore.sqf'";
			text = "Objects";

			x = 0.20 * safezoneW + safezoneX;
			y = 0.525 * safezoneH + safezoneY;
			w = 0.088 * safezoneW;
			h = 0.040 * safezoneH;
		};
	};
};

<|endoftext|>


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

void main()
{

	cout << "Hello World" << endl;

}
<commit_msg>update func1<commit_after>
#include <iostream>
using namespace std;

void func1()
{
	cout << "func1" << endl;
}

void main()
{

	cout << "Hello World" << endl;

	func1();

}
<|endoftext|>


<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#include "libmesh/diff_system.h"
#include "libmesh/dof_map.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/petsc_diff_solver.h"
#include "libmesh/petsc_matrix.h"
#include "libmesh/petsc_vector.h"
#include "libmesh/petsc_auto_fieldsplit.h"

#ifdef LIBMESH_HAVE_PETSC

namespace libMesh
{

//--------------------------------------------------------------------
// Functions with C linkage to pass to PETSc.  PETSc will call these
// methods as needed.
//
// Since they must have C linkage they have no knowledge of a namespace.
// Give them an obscure name to avoid namespace pollution.
extern "C"
{
  // Older versions of PETSc do not have the different int typedefs.
  // On 64-bit machines, PetscInt may actually be a long long int.
  // This change occurred in Petsc-2.2.1.
#if PETSC_VERSION_LESS_THAN(2,2,1)
  typedef int PetscErrorCode;
  typedef int PetscInt;
#endif

  // Function to hand to PETSc's SNES,
  // which monitors convergence at X
  PetscErrorCode
  __libmesh_petsc_diff_solver_monitor (SNES snes, PetscInt its,
                                       PetscReal fnorm, void *ctx)
  {
    PetscDiffSolver& solver =
      *(static_cast<PetscDiffSolver*> (ctx));

    if (solver.verbose)
      libMesh::out << "  PetscDiffSolver step " << its
                   << ", |residual|_2 = " << fnorm << std::endl;
    if (solver.linear_solution_monitor.get()) {
      int ierr = 0;

      Vec petsc_delta_u;
      ierr = SNESGetSolutionUpdate(snes, &petsc_delta_u);
      CHKERRABORT(solver.comm().get(), ierr);
      PetscVector<Number> delta_u(petsc_delta_u, solver.comm());
      delta_u.close();

      Vec petsc_u;
      ierr = SNESGetSolution(snes, &petsc_u);
      CHKERRABORT(solver.comm().get(), ierr);
      PetscVector<Number> u(petsc_u, solver.comm());
      u.close();

      Vec petsc_res;
      ierr = SNESGetFunction(snes, &petsc_res, NULL, NULL);
      CHKERRABORT(solver.comm().get(), ierr);
      PetscVector<Number> res(petsc_res, solver.comm());
      res.close();

      (*solver.linear_solution_monitor)(
                                        delta_u, delta_u.l2_norm(),
                                        u, u.l2_norm(),
                                        res, res.l2_norm(), its);
    }
    return 0;
  }

  // Functions to hand to PETSc's SNES,
  // which compute the residual or jacobian at X
  PetscErrorCode
  __libmesh_petsc_diff_solver_residual (SNES, Vec x, Vec r, void *ctx)
  {
    libmesh_assert(x);
    libmesh_assert(r);
    libmesh_assert(ctx);

    PetscDiffSolver& solver =
      *(static_cast<PetscDiffSolver*> (ctx));
    ImplicitSystem &sys = solver.system();

    if (solver.verbose)
      libMesh::out << "Assembling the residual" << std::endl;

    PetscVector<Number>& X_system =
      *cast_ptr<PetscVector<Number>*>(sys.solution.get());
    PetscVector<Number>& R_system =
      *cast_ptr<PetscVector<Number>*>(sys.rhs);
    PetscVector<Number> X_input(x, sys.comm()), R_input(r, sys.comm());

    // DiffSystem assembles from the solution and into the rhs, so swap
    // those with our input vectors before assembling.  They'll probably
    // already be references to the same vectors, but PETSc might do
    // something tricky.
    X_input.swap(X_system);
    R_input.swap(R_system);

    // We may need to correct a non-conforming solution
    sys.get_dof_map().enforce_constraints_exactly(sys);

    // We may need to localize a parallel solution
    sys.update();

    // Do DiffSystem assembly
    sys.assembly(true, false);
    R_system.close();

    // Swap back
    X_input.swap(X_system);
    R_input.swap(R_system);

    // No errors, we hope
    return 0;
  }

#if PETSC_RELEASE_LESS_THAN(3,5,0)
PetscErrorCode
__libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat *libmesh_dbg_var(j), Mat *pc,
                                      MatStructure *msflag, void *ctx)
#else
PetscErrorCode
__libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat libmesh_dbg_var(j), Mat pc,
                                      void *ctx)
#endif
{
  libmesh_assert(x);
  libmesh_assert(j);
//  libmesh_assert_equal_to (pc, j);  // We don't use separate preconditioners yet
  libmesh_assert(ctx);

    PetscDiffSolver& solver =
      *(static_cast<PetscDiffSolver*> (ctx));
    ImplicitSystem &sys = solver.system();

    if (solver.verbose)
      libMesh::out << "Assembling the Jacobian" << std::endl;

    PetscVector<Number>& X_system =
      *cast_ptr<PetscVector<Number>*>(sys.solution.get());
    PetscVector<Number> X_input(x, sys.comm());

#if PETSC_RELEASE_LESS_THAN(3,5,0)
  PetscMatrix<Number> J_input(*pc, sys.comm());
#else
  PetscMatrix<Number> J_input(pc, sys.comm());
#endif
  PetscMatrix<Number>& J_system =
    *cast_ptr<PetscMatrix<Number>*>(sys.matrix);

    // DiffSystem assembles from the solution and into the jacobian, so
    // swap those with our input vectors before assembling.  They'll
    // probably already be references to the same vectors, but PETSc
    // might do something tricky.
    X_input.swap(X_system);
    J_input.swap(J_system);

    // We may need to correct a non-conforming solution
    sys.get_dof_map().enforce_constraints_exactly(sys);

    // We may need to localize a parallel solution
    sys.update();

    // Do DiffSystem assembly
    sys.assembly(false, true);
    J_system.close();

    // Swap back
    X_input.swap(X_system);
    J_input.swap(J_system);

#if PETSC_RELEASE_LESS_THAN(3,5,0)
  *msflag = SAME_NONZERO_PATTERN;
#endif
  // No errors, we hope
  return 0;
}

} // extern "C"

PetscDiffSolver::PetscDiffSolver (sys_type& s)
  : Parent(s)
{
}

void PetscDiffSolver::init ()
{
  START_LOG("init()", "PetscDiffSolver");

  Parent::init();

  int ierr=0;

#if PETSC_VERSION_LESS_THAN(2,1,2)
  // At least until Petsc 2.1.1, the SNESCreate had a different
  // calling syntax.  The second argument was of type SNESProblemType,
  // and could have a value of either SNES_NONLINEAR_EQUATIONS or
  // SNES_UNCONSTRAINED_MINIMIZATION.
  ierr = SNESCreate(this->comm().get(), SNES_NONLINEAR_EQUATIONS, &_snes);
  LIBMESH_CHKERRABORT(ierr);
#else
  ierr = SNESCreate(this->comm().get(),&_snes);
  LIBMESH_CHKERRABORT(ierr);
#endif

#if PETSC_VERSION_LESS_THAN(2,3,3)
  ierr = SNESSetMonitor (_snes, __libmesh_petsc_diff_solver_monitor,
                         this, PETSC_NULL);
#else
  // API name change in PETSc 2.3.3
  ierr = SNESMonitorSet (_snes, __libmesh_petsc_diff_solver_monitor,
                         this, PETSC_NULL);
#endif
  LIBMESH_CHKERRABORT(ierr);

  if (libMesh::on_command_line("--solver_system_names"))
    {
      ierr = SNESSetOptionsPrefix(_snes, (_system.name()+"_").c_str());
      LIBMESH_CHKERRABORT(ierr);
    }

  ierr = SNESSetFromOptions(_snes);
  LIBMESH_CHKERRABORT(ierr);

  KSP my_ksp;
  ierr = SNESGetKSP(_snes, &my_ksp);
  LIBMESH_CHKERRABORT(ierr);

  PC my_pc;
  ierr = KSPGetPC(my_ksp, &my_pc);
  LIBMESH_CHKERRABORT(ierr);

  petsc_auto_fieldsplit(my_pc, _system);

  STOP_LOG("init()", "PetscDiffSolver");
}

PetscDiffSolver::~PetscDiffSolver ()
{
}

void PetscDiffSolver::clear()
{
  START_LOG("clear()", "PetscDiffSolver");

  int ierr = LibMeshSNESDestroy(&_snes);
  LIBMESH_CHKERRABORT(ierr);

  STOP_LOG("clear()", "PetscDiffSolver");
}

void PetscDiffSolver::reinit()
{
  Parent::reinit();

  KSP my_ksp;
  int ierr = SNESGetKSP(_snes, &my_ksp);
  LIBMESH_CHKERRABORT(ierr);

  PC my_pc;
  ierr = KSPGetPC(my_ksp, &my_pc);
  LIBMESH_CHKERRABORT(ierr);

  petsc_auto_fieldsplit(my_pc, _system);
}

DiffSolver::SolveResult convert_solve_result(SNESConvergedReason r)
{
  switch (r)
    {
    case SNES_CONVERGED_FNORM_ABS:
      return DiffSolver::CONVERGED_ABSOLUTE_RESIDUAL;
    case SNES_CONVERGED_FNORM_RELATIVE:
      return DiffSolver::CONVERGED_RELATIVE_RESIDUAL;
#if PETSC_VERSION_LESS_THAN(3,2,1)
    case SNES_CONVERGED_PNORM_RELATIVE:
#else
    case SNES_CONVERGED_SNORM_RELATIVE:
#endif
      return DiffSolver::CONVERGED_RELATIVE_STEP;
#if !PETSC_VERSION_LESS_THAN(2,3,3)
    case SNES_CONVERGED_ITS:
#endif
    case SNES_CONVERGED_TR_DELTA:
      return DiffSolver::CONVERGED_NO_REASON;
    case SNES_DIVERGED_FUNCTION_DOMAIN:
    case SNES_DIVERGED_FUNCTION_COUNT:
    case SNES_DIVERGED_FNORM_NAN:
#if !PETSC_VERSION_LESS_THAN(3,3,0)
    case SNES_DIVERGED_INNER:
#endif
#if !PETSC_VERSION_LESS_THAN(2,3,2)
    case SNES_DIVERGED_LINEAR_SOLVE:
#endif
    case SNES_DIVERGED_LOCAL_MIN:
      return DiffSolver::DIVERGED_NO_REASON;
    case SNES_DIVERGED_MAX_IT:
      return DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;
#if PETSC_VERSION_LESS_THAN(3,2,0)
    case SNES_DIVERGED_LS_FAILURE:
#else
    case SNES_DIVERGED_LINE_SEARCH:
#endif
      return DiffSolver::DIVERGED_BACKTRACKING_FAILURE;
      // In PETSc, SNES_CONVERGED_ITERATING means
      // the solve is still iterating, but by the
      // time we get here, we must have either
      // converged or diverged, so
      // SNES_CONVERGED_ITERATING is invalid.
    case SNES_CONVERGED_ITERATING:
      return DiffSolver::INVALID_SOLVE_RESULT;
    default:
    }
  return DiffSolver::INVALID_SOLVE_RESULT;
}

unsigned int PetscDiffSolver::solve()
{
  this->init();

  START_LOG("solve()", "PetscDiffSolver");

  PetscVector<Number> &x =
    *(cast_ptr<PetscVector<Number>*>(_system.solution.get()));
  PetscMatrix<Number> &jac =
    *(cast_ptr<PetscMatrix<Number>*>(_system.matrix));
  PetscVector<Number> &r =
    *(cast_ptr<PetscVector<Number>*>(_system.rhs));

#ifdef LIBMESH_ENABLE_CONSTRAINTS
  _system.get_dof_map().enforce_constraints_exactly(_system);
#endif

  int ierr = 0;

  ierr = SNESSetFunction (_snes, r.vec(),
                          __libmesh_petsc_diff_solver_residual, this);
  LIBMESH_CHKERRABORT(ierr);

  ierr = SNESSetJacobian (_snes, jac.mat(), jac.mat(),
                          __libmesh_petsc_diff_solver_jacobian, this);
  LIBMESH_CHKERRABORT(ierr);

# if PETSC_VERSION_LESS_THAN(2,2,0)

  ierr = SNESSolve (_snes, x.vec(), &_outer_iterations);
  LIBMESH_CHKERRABORT(ierr);

  // 2.2.x style
#elif PETSC_VERSION_LESS_THAN(2,3,0)

  ierr = SNESSolve (_snes, x.vec());
  LIBMESH_CHKERRABORT(ierr);

  // 2.3.x & newer style
#else

  ierr = SNESSolve (_snes, PETSC_NULL, x.vec());
  LIBMESH_CHKERRABORT(ierr);

#endif

  STOP_LOG("solve()", "PetscDiffSolver");

  SNESConvergedReason reason;
  SNESGetConvergedReason(_snes, &reason);

  this->clear();

  return convert_solve_result(reason);
}

} // namespace libMesh

#endif // LIBMESH_HAVE_PETSC
<commit_msg>Fix syntax for missing-default warning fix<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

#include "libmesh/diff_system.h"
#include "libmesh/dof_map.h"
#include "libmesh/libmesh_logging.h"
#include "libmesh/petsc_diff_solver.h"
#include "libmesh/petsc_matrix.h"
#include "libmesh/petsc_vector.h"
#include "libmesh/petsc_auto_fieldsplit.h"

#ifdef LIBMESH_HAVE_PETSC

namespace libMesh
{

//--------------------------------------------------------------------
// Functions with C linkage to pass to PETSc.  PETSc will call these
// methods as needed.
//
// Since they must have C linkage they have no knowledge of a namespace.
// Give them an obscure name to avoid namespace pollution.
extern "C"
{
  // Older versions of PETSc do not have the different int typedefs.
  // On 64-bit machines, PetscInt may actually be a long long int.
  // This change occurred in Petsc-2.2.1.
#if PETSC_VERSION_LESS_THAN(2,2,1)
  typedef int PetscErrorCode;
  typedef int PetscInt;
#endif

  // Function to hand to PETSc's SNES,
  // which monitors convergence at X
  PetscErrorCode
  __libmesh_petsc_diff_solver_monitor (SNES snes, PetscInt its,
                                       PetscReal fnorm, void *ctx)
  {
    PetscDiffSolver& solver =
      *(static_cast<PetscDiffSolver*> (ctx));

    if (solver.verbose)
      libMesh::out << "  PetscDiffSolver step " << its
                   << ", |residual|_2 = " << fnorm << std::endl;
    if (solver.linear_solution_monitor.get()) {
      int ierr = 0;

      Vec petsc_delta_u;
      ierr = SNESGetSolutionUpdate(snes, &petsc_delta_u);
      CHKERRABORT(solver.comm().get(), ierr);
      PetscVector<Number> delta_u(petsc_delta_u, solver.comm());
      delta_u.close();

      Vec petsc_u;
      ierr = SNESGetSolution(snes, &petsc_u);
      CHKERRABORT(solver.comm().get(), ierr);
      PetscVector<Number> u(petsc_u, solver.comm());
      u.close();

      Vec petsc_res;
      ierr = SNESGetFunction(snes, &petsc_res, NULL, NULL);
      CHKERRABORT(solver.comm().get(), ierr);
      PetscVector<Number> res(petsc_res, solver.comm());
      res.close();

      (*solver.linear_solution_monitor)(
                                        delta_u, delta_u.l2_norm(),
                                        u, u.l2_norm(),
                                        res, res.l2_norm(), its);
    }
    return 0;
  }

  // Functions to hand to PETSc's SNES,
  // which compute the residual or jacobian at X
  PetscErrorCode
  __libmesh_petsc_diff_solver_residual (SNES, Vec x, Vec r, void *ctx)
  {
    libmesh_assert(x);
    libmesh_assert(r);
    libmesh_assert(ctx);

    PetscDiffSolver& solver =
      *(static_cast<PetscDiffSolver*> (ctx));
    ImplicitSystem &sys = solver.system();

    if (solver.verbose)
      libMesh::out << "Assembling the residual" << std::endl;

    PetscVector<Number>& X_system =
      *cast_ptr<PetscVector<Number>*>(sys.solution.get());
    PetscVector<Number>& R_system =
      *cast_ptr<PetscVector<Number>*>(sys.rhs);
    PetscVector<Number> X_input(x, sys.comm()), R_input(r, sys.comm());

    // DiffSystem assembles from the solution and into the rhs, so swap
    // those with our input vectors before assembling.  They'll probably
    // already be references to the same vectors, but PETSc might do
    // something tricky.
    X_input.swap(X_system);
    R_input.swap(R_system);

    // We may need to correct a non-conforming solution
    sys.get_dof_map().enforce_constraints_exactly(sys);

    // We may need to localize a parallel solution
    sys.update();

    // Do DiffSystem assembly
    sys.assembly(true, false);
    R_system.close();

    // Swap back
    X_input.swap(X_system);
    R_input.swap(R_system);

    // No errors, we hope
    return 0;
  }

#if PETSC_RELEASE_LESS_THAN(3,5,0)
PetscErrorCode
__libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat *libmesh_dbg_var(j), Mat *pc,
                                      MatStructure *msflag, void *ctx)
#else
PetscErrorCode
__libmesh_petsc_diff_solver_jacobian (SNES, Vec x, Mat libmesh_dbg_var(j), Mat pc,
                                      void *ctx)
#endif
{
  libmesh_assert(x);
  libmesh_assert(j);
//  libmesh_assert_equal_to (pc, j);  // We don't use separate preconditioners yet
  libmesh_assert(ctx);

    PetscDiffSolver& solver =
      *(static_cast<PetscDiffSolver*> (ctx));
    ImplicitSystem &sys = solver.system();

    if (solver.verbose)
      libMesh::out << "Assembling the Jacobian" << std::endl;

    PetscVector<Number>& X_system =
      *cast_ptr<PetscVector<Number>*>(sys.solution.get());
    PetscVector<Number> X_input(x, sys.comm());

#if PETSC_RELEASE_LESS_THAN(3,5,0)
  PetscMatrix<Number> J_input(*pc, sys.comm());
#else
  PetscMatrix<Number> J_input(pc, sys.comm());
#endif
  PetscMatrix<Number>& J_system =
    *cast_ptr<PetscMatrix<Number>*>(sys.matrix);

    // DiffSystem assembles from the solution and into the jacobian, so
    // swap those with our input vectors before assembling.  They'll
    // probably already be references to the same vectors, but PETSc
    // might do something tricky.
    X_input.swap(X_system);
    J_input.swap(J_system);

    // We may need to correct a non-conforming solution
    sys.get_dof_map().enforce_constraints_exactly(sys);

    // We may need to localize a parallel solution
    sys.update();

    // Do DiffSystem assembly
    sys.assembly(false, true);
    J_system.close();

    // Swap back
    X_input.swap(X_system);
    J_input.swap(J_system);

#if PETSC_RELEASE_LESS_THAN(3,5,0)
  *msflag = SAME_NONZERO_PATTERN;
#endif
  // No errors, we hope
  return 0;
}

} // extern "C"

PetscDiffSolver::PetscDiffSolver (sys_type& s)
  : Parent(s)
{
}

void PetscDiffSolver::init ()
{
  START_LOG("init()", "PetscDiffSolver");

  Parent::init();

  int ierr=0;

#if PETSC_VERSION_LESS_THAN(2,1,2)
  // At least until Petsc 2.1.1, the SNESCreate had a different
  // calling syntax.  The second argument was of type SNESProblemType,
  // and could have a value of either SNES_NONLINEAR_EQUATIONS or
  // SNES_UNCONSTRAINED_MINIMIZATION.
  ierr = SNESCreate(this->comm().get(), SNES_NONLINEAR_EQUATIONS, &_snes);
  LIBMESH_CHKERRABORT(ierr);
#else
  ierr = SNESCreate(this->comm().get(),&_snes);
  LIBMESH_CHKERRABORT(ierr);
#endif

#if PETSC_VERSION_LESS_THAN(2,3,3)
  ierr = SNESSetMonitor (_snes, __libmesh_petsc_diff_solver_monitor,
                         this, PETSC_NULL);
#else
  // API name change in PETSc 2.3.3
  ierr = SNESMonitorSet (_snes, __libmesh_petsc_diff_solver_monitor,
                         this, PETSC_NULL);
#endif
  LIBMESH_CHKERRABORT(ierr);

  if (libMesh::on_command_line("--solver_system_names"))
    {
      ierr = SNESSetOptionsPrefix(_snes, (_system.name()+"_").c_str());
      LIBMESH_CHKERRABORT(ierr);
    }

  ierr = SNESSetFromOptions(_snes);
  LIBMESH_CHKERRABORT(ierr);

  KSP my_ksp;
  ierr = SNESGetKSP(_snes, &my_ksp);
  LIBMESH_CHKERRABORT(ierr);

  PC my_pc;
  ierr = KSPGetPC(my_ksp, &my_pc);
  LIBMESH_CHKERRABORT(ierr);

  petsc_auto_fieldsplit(my_pc, _system);

  STOP_LOG("init()", "PetscDiffSolver");
}

PetscDiffSolver::~PetscDiffSolver ()
{
}

void PetscDiffSolver::clear()
{
  START_LOG("clear()", "PetscDiffSolver");

  int ierr = LibMeshSNESDestroy(&_snes);
  LIBMESH_CHKERRABORT(ierr);

  STOP_LOG("clear()", "PetscDiffSolver");
}

void PetscDiffSolver::reinit()
{
  Parent::reinit();

  KSP my_ksp;
  int ierr = SNESGetKSP(_snes, &my_ksp);
  LIBMESH_CHKERRABORT(ierr);

  PC my_pc;
  ierr = KSPGetPC(my_ksp, &my_pc);
  LIBMESH_CHKERRABORT(ierr);

  petsc_auto_fieldsplit(my_pc, _system);
}

DiffSolver::SolveResult convert_solve_result(SNESConvergedReason r)
{
  switch (r)
    {
    case SNES_CONVERGED_FNORM_ABS:
      return DiffSolver::CONVERGED_ABSOLUTE_RESIDUAL;
    case SNES_CONVERGED_FNORM_RELATIVE:
      return DiffSolver::CONVERGED_RELATIVE_RESIDUAL;
#if PETSC_VERSION_LESS_THAN(3,2,1)
    case SNES_CONVERGED_PNORM_RELATIVE:
#else
    case SNES_CONVERGED_SNORM_RELATIVE:
#endif
      return DiffSolver::CONVERGED_RELATIVE_STEP;
#if !PETSC_VERSION_LESS_THAN(2,3,3)
    case SNES_CONVERGED_ITS:
#endif
    case SNES_CONVERGED_TR_DELTA:
      return DiffSolver::CONVERGED_NO_REASON;
    case SNES_DIVERGED_FUNCTION_DOMAIN:
    case SNES_DIVERGED_FUNCTION_COUNT:
    case SNES_DIVERGED_FNORM_NAN:
#if !PETSC_VERSION_LESS_THAN(3,3,0)
    case SNES_DIVERGED_INNER:
#endif
#if !PETSC_VERSION_LESS_THAN(2,3,2)
    case SNES_DIVERGED_LINEAR_SOLVE:
#endif
    case SNES_DIVERGED_LOCAL_MIN:
      return DiffSolver::DIVERGED_NO_REASON;
    case SNES_DIVERGED_MAX_IT:
      return DiffSolver::DIVERGED_MAX_NONLINEAR_ITERATIONS;
#if PETSC_VERSION_LESS_THAN(3,2,0)
    case SNES_DIVERGED_LS_FAILURE:
#else
    case SNES_DIVERGED_LINE_SEARCH:
#endif
      return DiffSolver::DIVERGED_BACKTRACKING_FAILURE;
      // In PETSc, SNES_CONVERGED_ITERATING means
      // the solve is still iterating, but by the
      // time we get here, we must have either
      // converged or diverged, so
      // SNES_CONVERGED_ITERATING is invalid.
    case SNES_CONVERGED_ITERATING:
      return DiffSolver::INVALID_SOLVE_RESULT;
    default:
      break;
    }
  return DiffSolver::INVALID_SOLVE_RESULT;
}

unsigned int PetscDiffSolver::solve()
{
  this->init();

  START_LOG("solve()", "PetscDiffSolver");

  PetscVector<Number> &x =
    *(cast_ptr<PetscVector<Number>*>(_system.solution.get()));
  PetscMatrix<Number> &jac =
    *(cast_ptr<PetscMatrix<Number>*>(_system.matrix));
  PetscVector<Number> &r =
    *(cast_ptr<PetscVector<Number>*>(_system.rhs));

#ifdef LIBMESH_ENABLE_CONSTRAINTS
  _system.get_dof_map().enforce_constraints_exactly(_system);
#endif

  int ierr = 0;

  ierr = SNESSetFunction (_snes, r.vec(),
                          __libmesh_petsc_diff_solver_residual, this);
  LIBMESH_CHKERRABORT(ierr);

  ierr = SNESSetJacobian (_snes, jac.mat(), jac.mat(),
                          __libmesh_petsc_diff_solver_jacobian, this);
  LIBMESH_CHKERRABORT(ierr);

# if PETSC_VERSION_LESS_THAN(2,2,0)

  ierr = SNESSolve (_snes, x.vec(), &_outer_iterations);
  LIBMESH_CHKERRABORT(ierr);

  // 2.2.x style
#elif PETSC_VERSION_LESS_THAN(2,3,0)

  ierr = SNESSolve (_snes, x.vec());
  LIBMESH_CHKERRABORT(ierr);

  // 2.3.x & newer style
#else

  ierr = SNESSolve (_snes, PETSC_NULL, x.vec());
  LIBMESH_CHKERRABORT(ierr);

#endif

  STOP_LOG("solve()", "PetscDiffSolver");

  SNESConvergedReason reason;
  SNESGetConvergedReason(_snes, &reason);

  this->clear();

  return convert_solve_result(reason);
}

} // namespace libMesh

#endif // LIBMESH_HAVE_PETSC
<|endoftext|>


<commit_before>
#include "application.h"
SYSTEM_MODE(MANUAL);

#include "rgbled.h"

#include "RHT03.h"
#include "TMP3x.h"
#include "OledDisplay.h"
#include "font_lcd6x8.h"
#include "font_lcd11x16.h"
#include "font_12x16_bold.h"
#include "common.h"

// function prototypes
void drawPattern();
void drawText();
void drawTemp();
void getTemp();

int btnUp = D6;
int btnDn = D5;
int btnHome = D3;

bool btnUpLatch = false;
bool btnDnLatch = false;
bool btnHomeLatch = false;

double avgTemp = 0.0;

uint drawMode = 0;
uint textMode = 0;

OledDisplay display = OledDisplay(D1, D2, D0);;
RHT03 rht = RHT03(D4, D7);
TMP3x tmp36 = TMP3x(A0, 10, 1000);

const font_t* font_lcdSm = parseFont(FONT_LCD6X8);
const font_t* font_lcdLg = parseFont(FONT_LCD11X16);
const font_t* font_bold  = parseFont(FONT_12X16_BOLD);

void setup() {

  pinMode(btnUp, INPUT_PULLUP);
  pinMode(btnDn, INPUT_PULLUP);
  pinMode(btnHome, INPUT_PULLUP);

  // Spark.variable("reading", &reading, DOUBLE);
  // Spark.variable("volts", &volts, DOUBLE);
  // Spark.variable("temp", &avgTemp, DOUBLE);

  RGB.control(true);
  RGB.color(0, 0, 0);

  display.begin();
}

void loop() {
  tmp36.poll();
  if (rht.poll()) {
    drawTemp();
  }

  // curTime = millis();
  // // get temp once per second
  // if (lastTime + 3000 < curTime) {
  //   lastTime = curTime;
  //   display.clear(CLEAR_OLED);
  //   drawTemp();
  // }

  if (digitalRead(btnHome) == LOW) {
    if (btnHomeLatch) { // only draw once per press
      drawPattern();
      btnHomeLatch = false;
    }
  } else {
    btnHomeLatch = true;
  }

  if (digitalRead(btnUp) == LOW) {
    RGB.color(0,0,255);
    if (btnUpLatch) { // only draw once per press
      drawTemp();
      btnUpLatch = false;
    }
  } else {
    btnUpLatch = true;
  }

  if (digitalRead(btnDn) == LOW) {
    RGB.color(255,0,0);
    if (btnDnLatch) { // only draw once per press
      drawText();
      btnDnLatch = false;
    }
  } else {
    btnDnLatch = true;
  }
}

void initStat() {
}

void drawTemp() {
  display.clear(CLEAR_OLED);
  display.setFont(font_lcdLg);
  char tempStr[8];

  double ftemp = tmp36.getTempF();
  ftemp = (ftemp / 10);

  sprintf(tempStr, "%.1f\x7f", ftemp);
  display.writeText(0, 0, tempStr);

  ftemp = rht.getTempF();
  ftemp = ftemp / 10;
  sprintf(tempStr, "%.1f\x7f", ftemp);
  display.writeText(0, 1, tempStr);

  ftemp = rht.getRH();
  ftemp = ftemp / 10;
  sprintf(tempStr, "%.1f%%", ftemp);
  display.writeText(0, 2, tempStr);

  // sprintf(tempStr, "%d.%d  ", rht.getIntCount(), rht.getIgnCount());
  // display.writeText(1, 4, tempStr);
  display.display();
}

void drawPattern() {
  display.resetPage();

  switch (drawMode) {
    case 0: // blank page
      RGB.color(255,0,0);
      display.clear(CLEAR_BUFF);
      break;
    case 1: // horizontal lines
      RGB.color(0,255,0);
      display.fill(0xaa);
      break;
    case 2: // vertical lines
      RGB.color(0,0,255);
      for (int i=0; i<6; i++) {
        for (int j=0; j<32; j++) {
          int c = j*2;
          display.setByte(i, c, 0xff);
          display.setByte(i, c+1, 0x00);
        }
      }
      break;
    case 3: {// count
      RGB.color(255,255,0);
      byte val = 0x00;
      for (int i=0; i<6; i++) {
        for (int j=0; j<64; j++) {
          display.setByte(i, j, val++);
          if (val > 0xff) val = 0x00;
        }
      }
      break;
    }
    case 4: // diagnal lines
      RGB.color(255,0,255);
      for (int i=0; i<6; i++) {
        for (int j=0; j<8; j++) {
          int c = j*8;
          display.setByte(i, c,   0x01);
          display.setByte(i, c+1, 0x02);
          display.setByte(i, c+2, 0x04);
          display.setByte(i, c+3, 0x08);
          display.setByte(i, c+4, 0x10);
          display.setByte(i, c+5, 0x20);
          display.setByte(i, c+6, 0x40);
          display.setByte(i, c+7, 0x80);
        }
      }
      break;
    case 5: // progression
      RGB.color(0,255,255);
      for (int i=0; i<6; i++) {
        for (int j=0; j<8; j++) {
          int c = j*8;
          display.setByte(i, c,   0x01);
          display.setByte(i, c+1, 0x03);
          display.setByte(i, c+2, 0x07);
          display.setByte(i, c+3, 0x0f);
          display.setByte(i, c+4, 0x1f);
          display.setByte(i, c+5, 0x3f);
          display.setByte(i, c+6, 0x7f);
          display.setByte(i, c+7, 0xff);
        }
      }
      break;
  }
  display.display();

  drawMode += 1;
  if (drawMode > 5) {
      drawMode = 0;
  }
}

void drawText() {
  display.clear(CLEAR_OLED);
  // display.setFont(textMode);
  switch (textMode) {
    case 0: // small
    case 1: // med
    case 2: // bold
      // RGB.color(textMode==0?255:0, textMode==0?0:255, 0);
      display.writeText(0, 0, "12345");
      display.writeText(0, 1, "Hello");
      display.writeText(0, 2, "World");
      break;
    case 3: // large
    case 4:
    case 5:
      // RGB.color(0,0,255);
      display.writeText(0, 0, "12345");
      if (textMode < 5) {
        display.writeText(0, 1, "67890");
      }
      break;
  }

  textMode += 1;
  if (textMode > 5) {
    textMode = 0;
  }
}
<commit_msg>Use new buttons, layout screen, general cleanup<commit_after>
#include "application.h"
SYSTEM_MODE(MANUAL);

#include "rgbled.h"

#include "common.h"
#include "RHT03.h"
#include "ButtonInterrupt.h"
#include "OledDisplay.h"
#include "font_lcd6x8.h"
#include "font_lcd11x16.h"

// function prototypes
void drawPattern();
void drawText();
void drawTemp();
void drawSetTemp();
void getTemp();
void handleButtonHome(int mode);
void handleButtonUp(int mode);
void handleButtonDn(int mode);

#define DRAW_CUR_TEMP 1
#define DRAW_SET_TEMP 1
#define DRAW_MENU 2

#define PUFFIN_DEBUG true

bool btnHomeToggle = false;

int curTemp = 0;
int curRH = 0;
int setTemp = 72;
int setRH = 30;

uint drawMode = DRAW_CUR_TEMP;
uint textMode = 0;

OledDisplay *display;
RHT03 *rht;
ButtonInterrupt  *btnHome;
ButtonInterrupt  *btnUp;
ButtonInterrupt  *btnDn;

const font_t* font_lcdSm = parseFont(FONT_LCD6X8);
const font_t* font_lcdLg = parseFont(FONT_LCD11X16);

void setup() {
#ifdef PUFFIN_DEBUG
  Serial.begin(9600);
#endif

  pinMode(D7, OUTPUT);
  digitalWrite(D7, LOW);

  RGB.control(true);
  RGB.color(0, 0, 0);

  display = new OledDisplay(D1, D2, D0);
  display->begin();

  rht = new RHT03(D3);

  btnHome = new ButtonInterrupt(D4, 100, &handleButtonHome, 2000, 250);
  btnUp = new ButtonInterrupt(D6, 100, &handleButtonUp, 2000, 250);
  btnDn = new ButtonInterrupt(D5, 100, &handleButtonDn, 2000, 250);
}

void loop() {
  if (rht->poll()) {
    getTemp();
    if (drawMode == DRAW_CUR_TEMP) {
      drawTemp();
    }
  }

  btnHome->poll();
  btnUp->poll();
  btnDn->poll();
}

void initStat() {
}

void handleButtonHome(int mode) {
  switch(mode) {
    case UP:
      digitalWrite(D7, LOW);
      break;

    case FIRST:
      digitalWrite(D7, HIGH);
      btnHomeToggle = true;
      break;

    case REPEAT:
      digitalWrite(D7, btnHomeToggle ? HIGH : LOW);
      btnHomeToggle = !btnHomeToggle;
      break;

    default:
      break;
  }
}

void handleButtonUp(int mode) {
  switch(mode) {
    case FIRST:
    case REPEAT:
      setTemp++;
      drawSetTemp();
      break;

    default:
      break;
  }
}

void handleButtonDn(int mode) {
  switch(mode) {
    case FIRST:
    case REPEAT:
      setTemp--;
      drawSetTemp();
      break;

    default:
      break;
  }
}

void getTemp() {
  curTemp = rht->getTempF();
  curRH = rht->getRH();
  // TODO: Send to server
}

void drawTemp() {
  // todo: do this only once
  display->clear(CLEAR_BUFF);

  display->setFont(font_lcdLg);
  char tempStr[8];

  int ftemp = curTemp;
  int fdec = ftemp % 10;
  ftemp = ftemp / 10;

  display->setFont(font_lcdLg);
  sprintf(tempStr, "%d.", ftemp);
  display->writeText(0, 0, tempStr);
  display->setFont(font_lcdSm);
  sprintf(tempStr, "%d", fdec);
  display->writeText(5, 1, tempStr);

  int rh = curRH;
  int rhdec = rh % 10;
  rh = rh / 10;
  display->setFont(font_lcdLg);
  sprintf(tempStr, "%d.", rh);
  display->writeText(0, 1, tempStr);
  display->setFont(font_lcdSm);
  sprintf(tempStr, "%d%%", rhdec);
  display->writeText(5, 3, tempStr);

  display->setFont(font_lcdSm);
  const char *curDate = "10/14";
  const char *curTime = "12:34";
  display->writeText(0, 5, curDate);
  display->writeText(6, 5, curTime, -3);

  sprintf(tempStr, "%d", setTemp);
  display->writeText(8, 0, tempStr, 4);
  sprintf(tempStr, "%d", setRH);
  display->writeText(8, 2, tempStr, 4);

  display->display();
}

void drawSetTemp() {
  char tempStr[8];

  sprintf(tempStr, "%d", setTemp);
  display->writeText(8, 0, tempStr, 4);
  sprintf(tempStr, "%d", setRH);
  display->writeText(8, 2, tempStr, 4);

  display->display();
}
<|endoftext|>


<commit_before>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5cpp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Authors:
//   Eugen Wintersberger <eugen.wintersberger@desy.de>
//   Martin Shetty <martin.shetty@esss.se>
// Created on: May 14, 2018
//

#include <sstream>
#include <h5cpp/datatype/enum.hpp>
#include <h5cpp/error/error.hpp>

namespace hdf5
{
namespace datatype
{

Enum::Enum(ObjectHandle&& handle) :
    Datatype(std::move(handle)) {}

Enum::Enum(const Datatype& type) :
    Datatype(type)
{
  if (get_class() != Class::ENUM)
  {
    std::stringstream ss;
    ss << "Cannot create Enum datatype from " << get_class();
    throw std::runtime_error(ss.str());
  }
}

Enum Enum::create_underlying(const Datatype& base_type)
{
  hid_t ret = H5Tenum_create(static_cast<hid_t>(base_type));
  if (ret < 0)
  {
    std::stringstream ss;
    ss << "Could not create Enum of base type =" << base_type.get_class();
    error::Singleton::instance().throw_with_stack(ss.str());
  }
  return Enum(ObjectHandle(ret));
}

// implementation same as for Compound
size_t Enum::number_of_values() const
{
  int n = H5Tget_nmembers(static_cast<hid_t>(*this));
  if (n < 0)
  {
    error::Singleton::instance().throw_with_stack("Could not retrieve number of values for enum data type!");
  }
  return static_cast<size_t>(n);
}

// implementation same as for Compound
std::string Enum::name(size_t index) const
{
  char *buffer = H5Tget_member_name(static_cast<hid_t>(*this), static_cast<uint32_t>(index));
  if (buffer == nullptr) {
    std::stringstream ss;
    ss << "Failure to obtain name of value [" << index << "] in enum data type!";
    error::Singleton::instance().throw_with_stack(ss.str());
  }
  std::string name(buffer);

  if (H5free_memory(buffer) < 0) {
    std::stringstream ss;
    ss << "Failure freeing memory for name buffer of field [" << index << "]"
       << " in enum data type!";
    error::Singleton::instance().throw_with_stack(ss.str());
  }
  return name;
}

bool is_bool(const Enum & etype){
  int s = etype.number_of_values();
  if (s < 0) {
    error::Singleton::instance().throw_with_stack("Could not retrieve datatype");
    return false;
  }
  if(s != 2){
    return false;
  }
  if(etype.name(0) != "FALSE"){
    return false;
  }
  if(etype.name(1) != "TRUE"){
    return false;
  }
  return true;
}

} // namespace datatype
} // namespace hdf5
<commit_msg>remove duplicated checks<commit_after>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5cpp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Authors:
//   Eugen Wintersberger <eugen.wintersberger@desy.de>
//   Martin Shetty <martin.shetty@esss.se>
// Created on: May 14, 2018
//

#include <sstream>
#include <h5cpp/datatype/enum.hpp>
#include <h5cpp/error/error.hpp>

namespace hdf5
{
namespace datatype
{

Enum::Enum(ObjectHandle&& handle) :
    Datatype(std::move(handle)) {}

Enum::Enum(const Datatype& type) :
    Datatype(type)
{
  if (get_class() != Class::ENUM)
  {
    std::stringstream ss;
    ss << "Cannot create Enum datatype from " << get_class();
    throw std::runtime_error(ss.str());
  }
}

Enum Enum::create_underlying(const Datatype& base_type)
{
  hid_t ret = H5Tenum_create(static_cast<hid_t>(base_type));
  if (ret < 0)
  {
    std::stringstream ss;
    ss << "Could not create Enum of base type =" << base_type.get_class();
    error::Singleton::instance().throw_with_stack(ss.str());
  }
  return Enum(ObjectHandle(ret));
}

// implementation same as for Compound
size_t Enum::number_of_values() const
{
  int n = H5Tget_nmembers(static_cast<hid_t>(*this));
  if (n < 0)
  {
    error::Singleton::instance().throw_with_stack("Could not retrieve number of values for enum data type!");
  }
  return static_cast<size_t>(n);
}

// implementation same as for Compound
std::string Enum::name(size_t index) const
{
  char *buffer = H5Tget_member_name(static_cast<hid_t>(*this), static_cast<uint32_t>(index));
  if (buffer == nullptr) {
    std::stringstream ss;
    ss << "Failure to obtain name of value [" << index << "] in enum data type!";
    error::Singleton::instance().throw_with_stack(ss.str());
  }
  std::string name(buffer);

  if (H5free_memory(buffer) < 0) {
    std::stringstream ss;
    ss << "Failure freeing memory for name buffer of field [" << index << "]"
       << " in enum data type!";
    error::Singleton::instance().throw_with_stack(ss.str());
  }
  return name;
}

bool is_bool(const Enum & etype){
  int s = etype.number_of_values();
  if(s != 2){
    return false;
  }
  if(etype.name(0) != "FALSE"){
    return false;
  }
  if(etype.name(1) != "TRUE"){
    return false;
  }
  return true;
}

} // namespace datatype
} // namespace hdf5
<|endoftext|>


<commit_before>#include "core/global.h"
#include "core/messages.h"
#include <exception>
#include <stdexcept>

#include "DistributedObject.h"
#include "StateServer.h"

ConfigVariable<channel_t> cfg_channel("control", 0);

StateServer::StateServer(RoleConfig roleconfig) : Role(roleconfig)
{
	channel_t channel = cfg_channel.get_rval(m_roleconfig);
	MessageDirector::singleton.subscribe_channel(this, channel);

	std::stringstream name;
	name << "StateServer(" << channel << ")";
	m_log = new LogCategory("stateserver", name.str());
}

StateServer::~StateServer()
{
	delete m_log;
}

void StateServer::handle_generate(DatagramIterator &dgi, bool has_other)
{
	unsigned int parent_id = dgi.read_uint32();
	unsigned int zone_id = dgi.read_uint32();
	unsigned short dc_id = dgi.read_uint16();
	unsigned int do_id = dgi.read_uint32();

	if(dc_id >= gDCF->get_num_classes())
	{
		m_log->error() << "Received create for unknown dclass ID=" << dc_id << std::endl;
		return;
	}

	if(m_objs.find(do_id) != m_objs.end())
	{
		m_log->warning() << "Received generate for already-existing object ID=" << do_id << std::endl;
		return;
	}

	DCClass *dclass = gDCF->get_class(dc_id);
	DistributedObject *obj;
	try
	{
		obj = new DistributedObject(this, do_id, dclass, parent_id, zone_id, dgi, has_other);
	}
	catch(std::exception &e)
	{
		m_log->error() << "Received truncated generate for "
		               << dclass->get_name() << "(" << do_id << ")" << std::endl;
		return;
	}
	m_objs[do_id] = obj;
}

void StateServer::handle_datagram(Datagram &in_dg, DatagramIterator &dgi)
{
	channel_t sender = dgi.read_uint64();
	unsigned short msgtype = dgi.read_uint16();
	switch(msgtype)
	{
		case STATESERVER_OBJECT_GENERATE_WITH_REQUIRED:
		{
			handle_generate(dgi, false);
			break;
		}
		case STATESERVER_OBJECT_GENERATE_WITH_REQUIRED_OTHER:
		{
			handle_generate(dgi, true);
			break;
		}
		case STATESERVER_SHARD_RESET:
		{
			channel_t ai_channel = dgi.read_uint64();
			std::set <channel_t> targets;
			for(auto it = m_objs.begin(); it != m_objs.end(); ++it)
				if(it->second && it->second->m_ai_channel == ai_channel && it->second->m_ai_explicitly_set)
					targets.insert(it->second->m_do_id);

			if(targets.size())
			{
				Datagram dg(targets, sender, STATESERVER_SHARD_RESET);
				dg.add_uint64(ai_channel);
				send(dg);
			}
			break;
		}
		default:
			m_log->warning() << "Received unknown message: msgtype=" << msgtype << std::endl;
	}
}

RoleFactoryItem<StateServer> ss_fact("stateserver");
<commit_msg>StateServer: Fixed includes for clarity, from deletion in unpack_field<commit_after>#include "core/global.h"
#include "core/messages.h"
#include "dcparser/dcClass.h"
#include <exception>
#include <stdexcept>

#include "DistributedObject.h"
#include "StateServer.h"

ConfigVariable<channel_t> cfg_channel("control", 0);

StateServer::StateServer(RoleConfig roleconfig) : Role(roleconfig)
{
	channel_t channel = cfg_channel.get_rval(m_roleconfig);
	MessageDirector::singleton.subscribe_channel(this, channel);

	std::stringstream name;
	name << "StateServer(" << channel << ")";
	m_log = new LogCategory("stateserver", name.str());
}

StateServer::~StateServer()
{
	delete m_log;
}

void StateServer::handle_generate(DatagramIterator &dgi, bool has_other)
{
	unsigned int parent_id = dgi.read_uint32();
	unsigned int zone_id = dgi.read_uint32();
	unsigned short dc_id = dgi.read_uint16();
	unsigned int do_id = dgi.read_uint32();

	if(dc_id >= gDCF->get_num_classes())
	{
		m_log->error() << "Received create for unknown dclass ID=" << dc_id << std::endl;
		return;
	}

	if(m_objs.find(do_id) != m_objs.end())
	{
		m_log->warning() << "Received generate for already-existing object ID=" << do_id << std::endl;
		return;
	}

	DCClass *dclass = gDCF->get_class(dc_id);
	DistributedObject *obj;
	try
	{
		obj = new DistributedObject(this, do_id, dclass, parent_id, zone_id, dgi, has_other);
	}
	catch(std::exception &e)
	{
		m_log->error() << "Received truncated generate for "
		               << dclass->get_name() << "(" << do_id << ")" << std::endl;
		return;
	}
	m_objs[do_id] = obj;
}

void StateServer::handle_datagram(Datagram &in_dg, DatagramIterator &dgi)
{
	channel_t sender = dgi.read_uint64();
	unsigned short msgtype = dgi.read_uint16();
	switch(msgtype)
	{
		case STATESERVER_OBJECT_GENERATE_WITH_REQUIRED:
		{
			handle_generate(dgi, false);
			break;
		}
		case STATESERVER_OBJECT_GENERATE_WITH_REQUIRED_OTHER:
		{
			handle_generate(dgi, true);
			break;
		}
		case STATESERVER_SHARD_RESET:
		{
			channel_t ai_channel = dgi.read_uint64();
			std::set <channel_t> targets;
			for(auto it = m_objs.begin(); it != m_objs.end(); ++it)
				if(it->second && it->second->m_ai_channel == ai_channel && it->second->m_ai_explicitly_set)
					targets.insert(it->second->m_do_id);

			if(targets.size())
			{
				Datagram dg(targets, sender, STATESERVER_SHARD_RESET);
				dg.add_uint64(ai_channel);
				send(dg);
			}
			break;
		}
		default:
			m_log->warning() << "Received unknown message: msgtype=" << msgtype << std::endl;
	}
}

RoleFactoryItem<StateServer> ss_fact("stateserver");
<|endoftext|>


<commit_before>/*
 * Copyright 2006-2011 The FLWOR Foundation.
 *
 * 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 "json_loader.h"
#include "util/json_parser.h"
#include "json_items.h"
#include "simple_item_factory.h"
#include "store_defs.h"
#include "simple_store.h"
#include <cassert>
#include <vector>

namespace zorba
{

namespace simplestore
{

namespace json
{

/******************************************************************************

*******************************************************************************/
JSONLoader::JSONLoader(std::istream& s)
  : in(s)
{
}

/******************************************************************************

*******************************************************************************/
JSONLoader::~JSONLoader()
{
}

/******************************************************************************

*******************************************************************************/
store::Item_t
JSONLoader::next( )
{
  using namespace zorba::json;
  using namespace zorba::simplestore;
  using namespace zorba::simplestore::json;

  try
  {
    BasicItemFactory& lFactory = GET_FACTORY();

    JSONItem_t lRootItem;

    // stack of objects, arrays, and object pairs
    std::vector<JSONItem_t> lStack;

    parser lParser(in);

    token lToken;

    while (lParser.next(&lToken))
    {
      switch (lToken.get_type())
      {
        case token::begin_array:
          lStack.push_back(new SimpleJSONArray());
          break;

        case token::begin_object:
          lStack.push_back(new SimpleJSONObject());
          break;

        case token::end_array:
        case token::end_object:
          {
            JSONItem_t lItem = lStack.back();

            lStack.pop_back();

            if (lStack.empty())
            {
              lRootItem = lItem;
            }
            else
            {
              JSONObjectPair* lOPair = cast<JSONObjectPair>(lStack.back());
              lOPair->setValue(lItem);
              lStack.pop_back();
            }

            break;
          }
        case token::name_separator:
        case token::value_separator:
            break;
        case token::string:
          {
            store::Item_t lValue;
            zstring s = lToken.get_value();
            lFactory.createString(lValue, s);

            addValue(lStack, lValue);
            break;
          }
        case token::number:
          {
            store::Item_t lValue;
            zstring s = lToken.get_value();
            lFactory.createJSONNumber(lValue, s);
            // todo check return type
            addValue(lStack, lValue);
            break;
          }
        case token::json_false:
          {
            store::Item_t lValue;
            lFactory.createBoolean(lValue, false);
            addValue(lStack, lValue);
            break;
          }
        case token::json_true:
          {
            store::Item_t lValue;
            lFactory.createBoolean(lValue, true);
            addValue(lStack, lValue);
            break;
          }
        case token::json_null:
          {
            store::Item_t lValue;
            lFactory.createJSONNull(lValue);
            addValue(lStack, lValue);
            break;
          }
        default:
          assert(false);
      }
    }
    return lRootItem;
  }
  catch (zorba::json::exception& e)
  {
    std::cerr << e.what() << " at " << e.get_loc() << std::endl;
  }
  return NULL;
}

void
JSONLoader::addValue(
  std::vector<JSONItem_t>& aStack,
  const store::Item_t& aValue)
{
  JSONItem_t lLast = aStack.back();

  JSONObject* lObject = dynamic_cast<JSONObject*>(lLast.getp());

  if (lObject)
  {
    // if the top of the stack is an object, then
    // the value must be a string which is the name
    // of the object's name value pair
    JSONObjectPair_t lOPair = new SimpleJSONObjectPair();
    lOPair->setName(aValue);
    lObject->add(lOPair);
    aStack.push_back(lOPair);

    return;
  }

  JSONObjectPair* lOPair = dynamic_cast<JSONObjectPair*>(lLast.getp());
  if (lOPair)
  {
    lOPair->setValue(aValue);
    aStack.pop_back();

    return;
  }

  JSONArray* lArray  = dynamic_cast<JSONArray*>(lLast.getp());
  assert(lArray);

  JSONArrayPair_t lArrayPair(
      new SimpleJSONArrayPair(
        aValue,
        lArray
      )
    );
  lArray->push_back(lArrayPair);

}

template<typename T> T*
JSONLoader::cast(const JSONItem_t& j)
{
#ifndef NDEBUG
  T* t = dynamic_cast<T*>(j.getp());
  assert(t);
#else
  T* t = static_cast<T*>(j.getp());
#endif
  return t;
}

} /* namespace json */

} /* namespace simplestore */

} /* namespace zorba */

/*
 * Local variables:
 * mode: c++
 * End:
 */
/* vim:set et sw=2 ts=2: */

<commit_msg>fix for parsing json sequences<commit_after>/*
 * Copyright 2006-2011 The FLWOR Foundation.
 *
 * 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 "json_loader.h"
#include "util/json_parser.h"
#include "json_items.h"
#include "simple_item_factory.h"
#include "store_defs.h"
#include "simple_store.h"
#include <cassert>
#include <vector>

namespace zorba
{

namespace simplestore
{

namespace json
{

/******************************************************************************

*******************************************************************************/
JSONLoader::JSONLoader(std::istream& s)
  : in(s)
{
}

/******************************************************************************

*******************************************************************************/
JSONLoader::~JSONLoader()
{
}

/******************************************************************************

*******************************************************************************/
store::Item_t
JSONLoader::next( )
{
  using namespace zorba::json;
  using namespace zorba::simplestore;
  using namespace zorba::simplestore::json;

  in.peek();
  if (in.eof())
  {
    return NULL;
  }

  try
  {
    BasicItemFactory& lFactory = GET_FACTORY();

    JSONItem_t lRootItem;

    // stack of objects, arrays, and object pairs
    std::vector<JSONItem_t> lStack;

    parser lParser(in);

    token lToken;

    while (lParser.next(&lToken))
    {
      switch (lToken.get_type())
      {
        case token::begin_array:
          lStack.push_back(new SimpleJSONArray());
          break;

        case token::begin_object:
          lStack.push_back(new SimpleJSONObject());
          break;

        case token::end_array:
        case token::end_object:
          {
            JSONItem_t lItem = lStack.back();

            lStack.pop_back();

            if (lStack.empty())
            {
              lRootItem = lItem;
            }
            else
            {
              JSONObjectPair* lOPair = cast<JSONObjectPair>(lStack.back());
              lOPair->setValue(lItem);
              lStack.pop_back();
            }

            break;
          }
        case token::name_separator:
        case token::value_separator:
            break;
        case token::string:
          {
            store::Item_t lValue;
            zstring s = lToken.get_value();
            lFactory.createString(lValue, s);

            addValue(lStack, lValue);
            break;
          }
        case token::number:
          {
            store::Item_t lValue;
            zstring s = lToken.get_value();
            lFactory.createJSONNumber(lValue, s);
            // todo check return type
            addValue(lStack, lValue);
            break;
          }
        case token::json_false:
          {
            store::Item_t lValue;
            lFactory.createBoolean(lValue, false);
            addValue(lStack, lValue);
            break;
          }
        case token::json_true:
          {
            store::Item_t lValue;
            lFactory.createBoolean(lValue, true);
            addValue(lStack, lValue);
            break;
          }
        case token::json_null:
          {
            store::Item_t lValue;
            lFactory.createJSONNull(lValue);
            addValue(lStack, lValue);
            break;
          }
        default:
          assert(false);
      }
    }
    return lRootItem;
  }
  catch (zorba::json::exception& e)
  {
    std::cerr << e.what() << " at " << e.get_loc() << std::endl;
  }
  return NULL;
}

void
JSONLoader::addValue(
  std::vector<JSONItem_t>& aStack,
  const store::Item_t& aValue)
{
  JSONItem_t lLast = aStack.back();

  JSONObject* lObject = dynamic_cast<JSONObject*>(lLast.getp());

  if (lObject)
  {
    // if the top of the stack is an object, then
    // the value must be a string which is the name
    // of the object's name value pair
    JSONObjectPair_t lOPair = new SimpleJSONObjectPair();
    lOPair->setName(aValue);
    lObject->add(lOPair);
    aStack.push_back(lOPair);

    return;
  }

  JSONObjectPair* lOPair = dynamic_cast<JSONObjectPair*>(lLast.getp());
  if (lOPair)
  {
    lOPair->setValue(aValue);
    aStack.pop_back();

    return;
  }

  JSONArray* lArray  = dynamic_cast<JSONArray*>(lLast.getp());
  assert(lArray);

  JSONArrayPair_t lArrayPair(
      new SimpleJSONArrayPair(
        aValue,
        lArray
      )
    );
  lArray->push_back(lArrayPair);

}

template<typename T> T*
JSONLoader::cast(const JSONItem_t& j)
{
#ifndef NDEBUG
  T* t = dynamic_cast<T*>(j.getp());
  assert(t);
#else
  T* t = static_cast<T*>(j.getp());
#endif
  return t;
}

} /* namespace json */

} /* namespace simplestore */

} /* namespace zorba */

/*
 * Local variables:
 * mode: c++
 * End:
 */
/* vim:set et sw=2 ts=2: */

<|endoftext|>


<commit_before>/*
    Определить функцию для вычисления по формуле Ньютона приблежённого значения
    арифметического квадратного корня. В формуле Ньютона итерации определяются
    по формуле r_[n+1] = (r_[n] + x / r_[n]) / 2

    Версия для C++
*/
#include <iostream>
#include <cmath>
#include <clocale>

const double PRECISION = 0.000000001;

/*
    Объявление функции с именем newton_root.
    Она принимает один аргумент типа double и возращает значение типа double.
    Объявление без описания тела функции (блок кода в фигурных скобках) - позволяет
    делать вызов этой функции в любом месте, до определения самой функции.
*/
double newton_root(double );

int main()
{
    std::setlocale(LC_ALL, "RUS");

    double x, result;

    std::cout << "Введите x: ";
    std::cin >> x;

    // вызываем функцию, передавая ей в качестве аргумента переменную x и сохраняя возращённый ею результат в переменной result
    result = newton_root(x);
    std::cout << "Корень из x: " << result;

    return 0;
}

/*
    Ниже производится определение функции. В отличие от объявления, здесь обязательно указание имени передаваемых аргументов.
    Имя аргумента используется только в теле функции.

    Стоит заметить, что отделение объявления и определения функции не является обязательным при записи всего в одном файле.
*/
double newton_root(double num)
{
    double r_cur, r_next = num;

    /*
        Действительные числа (float, double) лучше сравнивать с некоторой заранее определённой
        точностью по числу знаков после запятой.
        num == 0.0 - не гарантирует, что сравнение будет истино даже если num = 0;
    */
    if (num < PRECISION)
        return 0.0;

    do {
        r_cur = r_next;
        r_next = (r_cur + num / r_cur) / 2;
    } while (fabs(r_cur - r_next) > PRECISION);

    return r_next;
}
<commit_msg>minor fix to from_study_guide/5_1.cpp<commit_after>/*
    Определить функцию для вычисления по формуле Ньютона приблежённого значения
    арифметического квадратного корня. В формуле Ньютона итерации определяются
    по формуле r_[n+1] = (r_[n] + x / r_[n]) / 2

    Версия для C++
*/
#include <iostream>
#include <cmath>
#include <clocale>

const double PRECISION = 0.000000001;

/*
    Объявление функции с именем newton_root.
    Она принимает один аргумент типа double и возращает значение типа double.
    Объявление без описания тела функции (блок кода в фигурных скобках) - позволяет
    делать вызов этой функции в любом месте, до определения самой функции.
*/
double newton_root(double );

int main()
{
    std::setlocale(LC_ALL, "RUS");

    double x, result;

    std::cout << "Введите x: ";
    std::cin >> x;

    // вызываем функцию, передавая ей в качестве аргумента переменную x и сохраняя возращённый ею результат в переменной result
    result = newton_root(x);
    std::cout << "Корень из x: " << result;

    return 0;
}

/*
    Ниже производится определение функции. В отличие от объявления, здесь обязательно указание имени передаваемых аргументов.
    Имя аргумента используется только в теле функции.

    Стоит заметить, что отделение объявления и определения функции не является обязательным при записи всего в одном файле.
*/
double newton_root(double num)
{
    double r_cur, r_next = num;

    /*
        Действительные числа (float, double) лучше сравнивать с некоторой заранее определённой
        точностью по числу знаков после запятой.
        num == 0.0 - не гарантирует, что сравнение будет истино даже если num = 0;
    */
    if (num < PRECISION)
        return 0.0;

    do {
        r_cur = r_next;
        r_next = (r_cur + num / r_cur) / 2;
    } while ( abs(r_cur - r_next) > PRECISION );

    return r_next;
}
<|endoftext|>


<commit_before>// This file is part of SWGANH which is released under GPL v2.
// See file LICENSE or go to http://swganh.com/LICENSE

#include "config_reader.h"

#include <array>
#include <fstream>
#include <stdexcept>

#ifdef WIN32
#include <regex>
#else
#include <boost/regex.hpp>
#endif

#include <boost/filesystem.hpp>

#include <anh/logger.h>

using namespace swganh::tre;

using std::ifstream;
using std::ios_base;
using std::move;
using std::invalid_argument;
using std::string;
using std::vector;

#ifdef WIN32
using std::regex;
using std::smatch;
using std::regex_match;
#else
using boost::regex;
using boost::smatch;
using boost::regex_match;
#endif

ConfigReader::ConfigReader(std::string filename)
    : config_filename_(move(filename))
{
    ParseConfig();
}

const std::vector<std::string>& ConfigReader::GetTreFilenames()
{
    return tre_filenames_;
}

void ConfigReader::ParseConfig()
{
    ifstream input_stream(config_filename_.c_str());

    if (!input_stream.is_open())
    {
        LOG(fatal) << "Invalid tre configuration file: " << config_filename_;
        throw invalid_argument("Invalid tre configuration file: " + config_filename_);
    }

    boost::filesystem::path p(config_filename_);
    boost::filesystem::path dir = p.parent_path();

#ifdef WIN32
    regex rx("searchTree_([0-9]{2})_([0-9]{1,2})=(\")?(.*)\\3");
#else
    regex rx("searchTree_([0-9]{2})_([0-9]{1,2})=(\")?(.*)(\")?");
#endif

    smatch match;
    string line;

    while(!input_stream.eof())
    {
        Getline(input_stream, line);

        if (regex_search(line, match, rx))
        {
            boost::filesystem::path tmp = dir;
            boost::filesystem::path filename = match[4].str();

            if (!boost::filesystem::is_regular_file(filename))
            {
                tmp /= filename;
                filename = tmp;
            }

            auto native_path = boost::filesystem::system_complete(filename).native();
            tre_filenames_.emplace_back(string(begin(native_path), end(native_path)));
        }
    }
}

std::istream& ConfigReader::Getline(std::istream& input, std::string& output)
{
    char c;

    output.clear();

    while(input.get(c) && c != '\n' && c != '\r')
    {
        output += c;
    }

    return input;
}<commit_msg>Reverted back to the single regex syntax now that line endings are working proper.<commit_after>// This file is part of SWGANH which is released under GPL v2.
// See file LICENSE or go to http://swganh.com/LICENSE

#include "config_reader.h"

#include <array>
#include <fstream>
#include <stdexcept>

#ifdef WIN32
#include <regex>
#else
#include <boost/regex.hpp>
#endif

#include <boost/filesystem.hpp>

#include <anh/logger.h>

using namespace swganh::tre;

using std::ifstream;
using std::ios_base;
using std::move;
using std::invalid_argument;
using std::string;
using std::vector;

#ifdef WIN32
using std::regex;
using std::smatch;
using std::regex_match;
#else
using boost::regex;
using boost::smatch;
using boost::regex_match;
#endif

ConfigReader::ConfigReader(std::string filename)
    : config_filename_(move(filename))
{
    ParseConfig();
}

const std::vector<std::string>& ConfigReader::GetTreFilenames()
{
    return tre_filenames_;
}

void ConfigReader::ParseConfig()
{
    ifstream input_stream(config_filename_.c_str());

    if (!input_stream.is_open())
    {
        LOG(fatal) << "Invalid tre configuration file: " << config_filename_;
        throw invalid_argument("Invalid tre configuration file: " + config_filename_);
    }

    boost::filesystem::path p(config_filename_);
    boost::filesystem::path dir = p.parent_path();

    regex rx("searchTree_([0-9]{2})_([0-9]{1,2})=(\")?(.*)\\3");
    smatch match;
    string line;

    while(!input_stream.eof())
    {
        Getline(input_stream, line);

        if (regex_search(line, match, rx))
        {
            boost::filesystem::path tmp = dir;
            boost::filesystem::path filename = match[4].str();

            if (!boost::filesystem::is_regular_file(filename))
            {
                tmp /= filename;
                filename = tmp;
            }

            auto native_path = boost::filesystem::system_complete(filename).native();
            tre_filenames_.emplace_back(string(begin(native_path), end(native_path)));
        }
    }
}

std::istream& ConfigReader::Getline(std::istream& input, std::string& output)
{
    char c;

    output.clear();

    while(input.get(c) && c != '\n' && c != '\r')
    {
        output += c;
    }

    return input;
}<|endoftext|>


<commit_before>/*
 *  _____             ___ ___   |
 * |  _  |___ ___ _ _|_  |_  |  |  C/C++ framework for 32-bit AVRs
 * |     | -_|  _| | |_  |  _|  |
 * |__|__|___|_| |_  |___|___|  |  https://github.com/aery32
 *               |___|          |
 *
 * Copyright (c) 2012, Muiku Oy
 * All rights reserved.
 *
 * LICENSE
 *
 * New BSD License, see the LICENSE.txt bundled with this package. If you did
 * not receive a copy of the license and are unable to obtain it through the
 * world-wide-web, please send an email to contact@muiku.com so we can send
 * you a copy.
 */

#include "aery32/pwm.h"

volatile avr32_pwm_t *aery::pwm = &AVR32_PWM;

int aery::pwm_init_divab(enum Pwm_channel_clk prea, uint8_t diva,
		enum Pwm_channel_clk preb, uint8_t divb)
{
	if (prea == PWM_CLKA || prea == PWM_CLKB)
		return -1;
	if (preb == PWM_CLKA || preb == PWM_CLKB)
		return -1;

	AVR32_PWM.MR.prea = prea;
	AVR32_PWM.MR.diva = diva;

	AVR32_PWM.MR.preb = preb;
	AVR32_PWM.MR.divb = divb;

	return 0;
}

int aery::pwm_init_channel(uint8_t chanum, enum Pwm_channel_clk clk,
		uint32_t duration, uint32_t period)
{
	/* Writing in CDTYn and CPRDn is possible while the chan is disabled */
	if (aery::pwm_isenabled(chanum))
		return -1;
	if (duration > period)
		return -1;

	volatile avr32_pwm_channel_t *pwm = &AVR32_PWM.channel[chanum];
	pwm->CMR.cpre = clk;
	pwm->cdty = duration;
	pwm->cprd = period;

	return 0;
}

int aery::pwm_setup_chamode(uint8_t chanum, enum Pwm_alignment align,
		enum Pwm_polarity polar)
{
	/* Mode can be modified only when the channel is disabled. */
	if (aery::pwm_isenabled(chanum))
		return -1;

	AVR32_PWM.channel[chanum].CMR.calg = align;
	AVR32_PWM.channel[chanum].CMR.cpol = polar;
	return 0;
}

int aery::pwm_update_duration(uint8_t chanum, uint32_t newval)
{
	if (newval > AVR32_PWM.channel[chanum].cprd)
		return -1;
	AVR32_PWM.channel[chanum].CMR.cpd = 0;
	AVR32_PWM.channel[chanum].cupd = newval;
	return 0;
}

int aery::pwm_update_period(uint8_t chanum, uint32_t newval)
{
	if (newval < AVR32_PWM.channel[chanum].cdty)
		return -1;
	AVR32_PWM.channel[chanum].CMR.cpd = 1;
	AVR32_PWM.channel[chanum].cupd = newval;
	return 0;
}

void aery::pwm_wait_periods(uint8_t chanum, uint32_t periods)
{
	volatile uint32_t status = AVR32_PWM.isr;

	AVR32_PWM.ier |= (1 << chanum);
	while (periods--)
		while ((status = AVR32_PWM.isr) & (1 << chanum));
	AVR32_PWM.idr |= (1 << chanum);
}

int aery::pwm_update_dutycl(uint8_t chanum, double D)
{
	volatile avr32_pwm_channel_t *pwm = &AVR32_PWM.channel[chanum];

	if (D > 1.0)
		return -1;
	if (D < 0.0)
		return -1;
	if (pwm->CMR.cpd == 0)
		return pwm_update_duration(chanum, (uint32_t) (D * pwm->cprd));
	else
		return pwm_update_period(chanum, (uint32_t) (pwm->cdty / D));
}

void aery::pwm_enable(uint8_t chamask)
{
	AVR32_PWM.ena = chamask;
}

void aery::pwm_disable(uint8_t chamask)
{
	AVR32_PWM.dis = chamask;
}

bool aery::pwm_isenabled(uint8_t chanum)
{
	return AVR32_PWM.sr & (1 << chanum);
}<commit_msg>Fine tuning the if statement<commit_after>/*
 *  _____             ___ ___   |
 * |  _  |___ ___ _ _|_  |_  |  |  C/C++ framework for 32-bit AVRs
 * |     | -_|  _| | |_  |  _|  |
 * |__|__|___|_| |_  |___|___|  |  https://github.com/aery32
 *               |___|          |
 *
 * Copyright (c) 2012, Muiku Oy
 * All rights reserved.
 *
 * LICENSE
 *
 * New BSD License, see the LICENSE.txt bundled with this package. If you did
 * not receive a copy of the license and are unable to obtain it through the
 * world-wide-web, please send an email to contact@muiku.com so we can send
 * you a copy.
 */

#include "aery32/pwm.h"

volatile avr32_pwm_t *aery::pwm = &AVR32_PWM;

int aery::pwm_init_divab(enum Pwm_channel_clk prea, uint8_t diva,
		enum Pwm_channel_clk preb, uint8_t divb)
{
	if (prea == PWM_CLKA || prea == PWM_CLKB)
		return -1;
	if (preb == PWM_CLKA || preb == PWM_CLKB)
		return -1;

	AVR32_PWM.MR.prea = prea;
	AVR32_PWM.MR.diva = diva;

	AVR32_PWM.MR.preb = preb;
	AVR32_PWM.MR.divb = divb;

	return 0;
}

int aery::pwm_init_channel(uint8_t chanum, enum Pwm_channel_clk clk,
		uint32_t duration, uint32_t period)
{
	/* Writing in CDTYn and CPRDn is possible while the chan is disabled */
	if (aery::pwm_isenabled(chanum))
		return -1;
	if (duration > period)
		return -1;

	volatile avr32_pwm_channel_t *pwm = &AVR32_PWM.channel[chanum];
	pwm->CMR.cpre = clk;
	pwm->cdty = duration;
	pwm->cprd = period;

	return 0;
}

int aery::pwm_setup_chamode(uint8_t chanum, enum Pwm_alignment align,
		enum Pwm_polarity polar)
{
	/* Mode can be modified only when the channel is disabled. */
	if (aery::pwm_isenabled(chanum))
		return -1;

	AVR32_PWM.channel[chanum].CMR.calg = align;
	AVR32_PWM.channel[chanum].CMR.cpol = polar;
	return 0;
}

int aery::pwm_update_duration(uint8_t chanum, uint32_t newval)
{
	if (newval > AVR32_PWM.channel[chanum].cprd)
		return -1;
	AVR32_PWM.channel[chanum].CMR.cpd = 0;
	AVR32_PWM.channel[chanum].cupd = newval;
	return 0;
}

int aery::pwm_update_period(uint8_t chanum, uint32_t newval)
{
	if (newval < AVR32_PWM.channel[chanum].cdty)
		return -1;
	AVR32_PWM.channel[chanum].CMR.cpd = 1;
	AVR32_PWM.channel[chanum].cupd = newval;
	return 0;
}

void aery::pwm_wait_periods(uint8_t chanum, uint32_t periods)
{
	volatile uint32_t status = AVR32_PWM.isr;

	AVR32_PWM.ier |= (1 << chanum);
	while (periods--)
		while ((status = AVR32_PWM.isr) & (1 << chanum));
	AVR32_PWM.idr |= (1 << chanum);
}

int aery::pwm_update_dutycl(uint8_t chanum, double D)
{
	volatile avr32_pwm_channel_t *pwm = &AVR32_PWM.channel[chanum];

	if (D < 0.0 || D > 1.0)
		return -1;
	if (pwm->CMR.cpd == 0)
		return pwm_update_duration(chanum, (uint32_t) (D * pwm->cprd));
	else
		return pwm_update_period(chanum, (uint32_t) (pwm->cdty / D));
}

void aery::pwm_enable(uint8_t chamask)
{
	AVR32_PWM.ena = chamask;
}

void aery::pwm_disable(uint8_t chamask)
{
	AVR32_PWM.dis = chamask;
}

bool aery::pwm_isenabled(uint8_t chanum)
{
	return AVR32_PWM.sr & (1 << chanum);
}<|endoftext|>