code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
namespace Infrastructure.DataAccess.Migrations { using System; using System.Data.Entity.Migrations; public partial class usersupervisioninfoaddedtosysusage : DbMigration { public override void Up() { AddColumn("dbo.ItSystemUsage", "UserSupervisionDate", c => c.DateTime(nullable: false, precision: 7, storeType: "datetime2")); AddColumn("dbo.ItSystemUsage", "UserSupervision", c => c.Int(nullable: false)); } public override void Down() { DropColumn("dbo.ItSystemUsage", "UserSupervision"); DropColumn("dbo.ItSystemUsage", "UserSupervisionDate"); } } }
miracle-as/kitos
Infrastructure.DataAccess/Migrations/201802161536558_user supervision info added to sysusage.cs
C#
mpl-2.0
683
/* * Copyright © 2013-2020, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.i18n.rest.internal.infrastructure.csv; import com.google.common.collect.Sets; import org.seedstack.i18n.rest.internal.locale.LocaleFinder; import org.seedstack.i18n.rest.internal.locale.LocaleRepresentation; import org.seedstack.io.spi.Template; import org.seedstack.io.spi.TemplateLoader; import org.seedstack.io.supercsv.Column; import org.seedstack.io.supercsv.SuperCsvTemplate; import org.seedstack.jpa.JpaUnit; import org.seedstack.seed.transaction.Transactional; import org.supercsv.cellprocessor.Optional; import javax.inject.Inject; import java.util.List; import java.util.Set; /** * @author pierre.thirouin@ext.mpsa.com */ public class I18nCSVTemplateLoader implements TemplateLoader { public static final String I18N_CSV_TEMPLATE = "i18nTranslations"; public static final String KEY = "key"; @Inject private LocaleFinder localeFinder; @JpaUnit("seed-i18n-domain") @Transactional @Override public Template load(String name) { List<LocaleRepresentation> availableLocales = localeFinder.findAvailableLocales(); SuperCsvTemplate superCsvTemplate = new SuperCsvTemplate(name); superCsvTemplate.addColumn(new Column(KEY, KEY, new Optional(), new Optional())); for (LocaleRepresentation availableLocale : availableLocales) { superCsvTemplate.addColumn(new Column(availableLocale.getCode(), availableLocale.getCode(), new Optional(), new Optional())); } return superCsvTemplate; } @Override public Set<String> names() { return Sets.newHashSet(I18N_CSV_TEMPLATE); } @Override public boolean contains(String name) { return names().contains(name); } @Override public String templateRenderer() { return I18nCSVRenderer.I18N_RENDERER; } @Override public String templateParser() { return CSVParser.I18N_PARSER; } }
seedstack/i18n-function
rest/src/main/java/org/seedstack/i18n/rest/internal/infrastructure/csv/I18nCSVTemplateLoader.java
Java
mpl-2.0
2,205
<?php declare(strict_types=1); /* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ namespace ParkManager\Application\Command\User; use Rollerworks\Component\SplitToken\SplitToken; final class ConfirmPasswordReset { /** * @param string $password The password in hashed format */ public function __construct(public SplitToken $token, public string $password) { } }
park-manager/park-manager
src/Application/Command/User/ConfirmPasswordReset.php
PHP
mpl-2.0
551
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MovingPlatform : MonoBehaviour { public float moveSpeed; private float moveForce; public float limit; public bool vertical; public bool movingPlus; public Vector3 startPos; Rigidbody2D rb; // Use this for initialization void Start () { rb = GetComponent<Rigidbody2D> (); startPos = transform.position; } // Update is called once per frame void Update () { if (vertical == false) { rb.velocity = new Vector2 (moveForce, rb.velocity.y); } else { rb.velocity = new Vector2 (rb.velocity.x, moveForce); } if (vertical == false) { if (transform.localPosition.x >= startPos.x + limit) { movingPlus = false; } if (transform.localPosition.x <= startPos.x - limit) { movingPlus = true; } } else { if (transform.localPosition.y >= startPos.y + limit) { movingPlus = false; } if (transform.localPosition.y <= startPos.y - limit) { movingPlus = true; } } if (movingPlus == true) { moveForce = moveSpeed; } if (movingPlus == false) { moveForce = moveSpeed * -1; } } }
apetersell/RPSX
RPSXUnity/Assets/Scripts/Level Stuff/MovingPlatform.cs
C#
mpl-2.0
1,165
// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // 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 "bvh4_factory.h" #include "../bvh/bvh.h" #include "../geometry/bezier1v.h" #include "../geometry/bezier1i.h" #include "../geometry/linei.h" #include "../geometry/triangle.h" #include "../geometry/trianglev.h" #include "../geometry/trianglev_mb.h" #include "../geometry/trianglei.h" #include "../geometry/quadv.h" #include "../geometry/quadi.h" #include "../geometry/quadi_mb.h" #include "../geometry/subdivpatch1cached.h" #include "../geometry/object.h" #include "../../common/accelinstance.h" namespace embree { DECLARE_SYMBOL2(Accel::Intersector1,BVH4Line4iIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Line4iMBIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1vIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1iIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1vIntersector1_OBB); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1iIntersector1_OBB); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1iMBIntersector1_OBB); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4Intersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4XfmTriangle4Intersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle8Intersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4vIntersector1Pluecker); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4iIntersector1Pluecker); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4vMBIntersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Subdivpatch1CachedIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4GridAOSIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4VirtualIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4VirtualMBIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Quad4vIntersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Quad4iIntersector1Pluecker); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Quad4iMBIntersector1Pluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Line4iIntersector4); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Line4iMBIntersector4); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1vIntersector4Single); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1iIntersector4Single); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1vIntersector4Single_OBB); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1iIntersector4Single_OBB); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1iMBIntersector4Single_OBB); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4Intersector4HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4Intersector4HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle8Intersector4HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle8Intersector4HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4vIntersector4HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4iIntersector4HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4vMBIntersector4HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4vIntersector4HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4vIntersector4HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4iIntersector4HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4iMBIntersector4HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Subdivpatch1CachedIntersector4); DECLARE_SYMBOL2(Accel::Intersector4,BVH4GridAOSIntersector4); DECLARE_SYMBOL2(Accel::Intersector4,BVH4VirtualIntersector4Chunk); DECLARE_SYMBOL2(Accel::Intersector4,BVH4VirtualMBIntersector4Chunk); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Line4iIntersector8); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Line4iMBIntersector8); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1vIntersector8Single); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1iIntersector8Single); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1vIntersector8Single_OBB); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1iIntersector8Single_OBB); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1iMBIntersector8Single_OBB); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4Intersector8HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4Intersector8HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle8Intersector8HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle8Intersector8HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4vIntersector8HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4iIntersector8HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4vMBIntersector8HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4vIntersector8HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4vIntersector8HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4iIntersector8HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4iMBIntersector8HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Subdivpatch1CachedIntersector8); DECLARE_SYMBOL2(Accel::Intersector8,BVH4GridAOSIntersector8); DECLARE_SYMBOL2(Accel::Intersector8,BVH4VirtualIntersector8Chunk); DECLARE_SYMBOL2(Accel::Intersector8,BVH4VirtualMBIntersector8Chunk); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Line4iIntersector16); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Line4iMBIntersector16); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1vIntersector16Single); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1iIntersector16Single); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1vIntersector16Single_OBB); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1iIntersector16Single_OBB); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1iMBIntersector16Single_OBB); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4Intersector16HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4Intersector16HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle8Intersector16HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle8Intersector16HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4vIntersector16HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4iIntersector16HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4vMBIntersector16HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4vIntersector16HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4vIntersector16HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4iIntersector16HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4iMBIntersector16HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Subdivpatch1CachedIntersector16); DECLARE_SYMBOL2(Accel::Intersector16,BVH4GridAOSIntersector16); DECLARE_SYMBOL2(Accel::Intersector16,BVH4VirtualIntersector16Chunk); DECLARE_SYMBOL2(Accel::Intersector16,BVH4VirtualMBIntersector16Chunk); DECLARE_BUILDER2(void,Scene,const createLineSegmentsAccelTy,BVH4BuilderTwoLevelLineSegmentsSAH); DECLARE_BUILDER2(void,Scene,const createTriangleMeshAccelTy,BVH4BuilderTwoLevelTriangleMeshSAH); DECLARE_BUILDER2(void,Scene,const createTriangleMeshAccelTy,BVH4BuilderInstancingTriangleMeshSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1vBuilder_OBB_New); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1iBuilder_OBB_New); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1iMBBuilder_OBB_New); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4SceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle8SceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4vSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4iSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4vMBSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Quad4vSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Quad4iSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Quad4iMBSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4SceneBuilderSpatialSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle8SceneBuilderSpatialSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4vSceneBuilderSpatialSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4iSceneBuilderSpatialSAH); DECLARE_BUILDER2(void,LineSegments,size_t,BVH4Line4iMeshBuilderSAH); DECLARE_BUILDER2(void,LineSegments,size_t,BVH4Line4iMBMeshBuilderSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4MeshBuilderSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle8MeshBuilderSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4vMeshBuilderSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4iMeshBuilderSAH); DECLARE_BUILDER2(void,QuadMesh,size_t,BVH4Quad4vMeshBuilderSAH); DECLARE_BUILDER2(void,QuadMesh,size_t,BVH4Quad4iMeshBuilderSAH); DECLARE_BUILDER2(void,QuadMesh,size_t,BVH4Quad4iMBMeshBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1vSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1iSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Line4iSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Line4iMBSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4VirtualSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4VirtualMBSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4SubdivPatch1CachedBuilderBinnedSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4SubdivGridEagerBuilderBinnedSAH); DECLARE_BUILDER2(void,LineSegments,size_t,BVH4Line4iMeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4MeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle8MeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4vMeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4iMeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4MeshBuilderMortonGeneral); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle8MeshBuilderMortonGeneral); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4vMeshBuilderMortonGeneral); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4iMeshBuilderMortonGeneral); BVH4Factory::BVH4Factory (int features) { /* select builders */ SELECT_SYMBOL_DEFAULT_AVX(features,BVH4BuilderTwoLevelLineSegmentsSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4BuilderTwoLevelTriangleMeshSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4BuilderInstancingTriangleMeshSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1vBuilder_OBB_New); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iBuilder_OBB_New); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iMBBuilder_OBB_New); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4SceneBuilderSAH); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8SceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMBSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX_AVX512KNL(features,BVH4Quad4vSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX_AVX512KNL(features,BVH4Quad4iSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4iMBSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4SceneBuilderSpatialSAH); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8SceneBuilderSpatialSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vSceneBuilderSpatialSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iSceneBuilderSpatialSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshBuilderSAH); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8MeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4vMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4iMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4iMBMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iMBSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1vSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4VirtualSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4VirtualMBSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX_AVX512KNL(features,BVH4SubdivPatch1CachedBuilderBinnedSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4SubdivGridEagerBuilderBinnedSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iMeshRefitSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshRefitSAH); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8MeshRefitSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshRefitSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshRefitSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshBuilderMortonGeneral); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8MeshBuilderMortonGeneral); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshBuilderMortonGeneral); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshBuilderMortonGeneral); /* select intersectors1 */ SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Line4iIntersector1); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Line4iMBIntersector1); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1vIntersector1); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iIntersector1); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1vIntersector1_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iIntersector1_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iMBIntersector1_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512KNL(features,BVH4Triangle4Intersector1Moeller); SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512KNL(features,BVH4XfmTriangle4Intersector1Moeller); SELECT_SYMBOL_INIT_AVX_AVX2 (features,BVH4Triangle8Intersector1Moeller); SELECT_SYMBOL_DEFAULT_SSE42_AVX (features,BVH4Triangle4vIntersector1Pluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX (features,BVH4Triangle4iIntersector1Pluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4vMBIntersector1Moeller); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector1); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4GridAOSIntersector1); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualIntersector1); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualMBIntersector1); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4vIntersector1Moeller); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4iIntersector1Pluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4iMBIntersector1Pluecker); #if defined (RTCORE_RAY_PACKETS) /* select intersectors4 */ SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Line4iIntersector4); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Line4iMBIntersector4); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1vIntersector4Single); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1iIntersector4Single); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1vIntersector4Single_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1iIntersector4Single_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1iMBIntersector4Single_OBB); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4Intersector4HybridMoeller); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4Intersector4HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector4HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector4HybridMoellerNoFilter); SELECT_SYMBOL_DEFAULT_SSE42_AVX(features,BVH4Triangle4vIntersector4HybridPluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX(features,BVH4Triangle4iIntersector4HybridPluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4vMBIntersector4HybridMoeller); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Quad4vIntersector4HybridMoeller); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Quad4vIntersector4HybridMoellerNoFilter); SELECT_SYMBOL_DEFAULT_AVX (features,BVH4Quad4iIntersector4HybridPluecker); SELECT_SYMBOL_DEFAULT_AVX (features,BVH4Quad4iMBIntersector4HybridPluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector4); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4GridAOSIntersector4); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualIntersector4Chunk); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualMBIntersector4Chunk); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4vIntersector4HybridMoeller); /* select intersectors8 */ SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Line4iIntersector8); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Line4iMBIntersector8); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1vIntersector8Single); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1iIntersector8Single); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1vIntersector8Single_OBB); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1iIntersector8Single_OBB); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1iMBIntersector8Single_OBB); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle4Intersector8HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle4Intersector8HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector8HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector8HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle4vIntersector8HybridPluecker); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle4iIntersector8HybridPluecker); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle4vMBIntersector8HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Quad4vIntersector8HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Quad4vIntersector8HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX (features,BVH4Quad4iIntersector8HybridPluecker); SELECT_SYMBOL_INIT_AVX (features,BVH4Quad4iMBIntersector8HybridPluecker); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector8); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4GridAOSIntersector8); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4VirtualIntersector8Chunk); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4VirtualMBIntersector8Chunk); /* select intersectors16 */ SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Line4iIntersector16); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Line4iMBIntersector16); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1vIntersector16Single); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1iIntersector16Single); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1vIntersector16Single_OBB); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1iIntersector16Single_OBB); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1iMBIntersector16Single_OBB); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4Intersector16HybridMoeller); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4Intersector16HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle8Intersector16HybridMoeller); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle8Intersector16HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4vIntersector16HybridPluecker); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4iIntersector16HybridPluecker); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4vMBIntersector16HybridMoeller); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4vIntersector16HybridMoeller); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4vIntersector16HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4iIntersector16HybridPluecker); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4iMBIntersector16HybridPluecker); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Subdivpatch1CachedIntersector16); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4GridAOSIntersector16); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4VirtualIntersector16Chunk); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4VirtualMBIntersector16Chunk); #endif } Accel::Intersectors BVH4Factory::BVH4Bezier1vIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1vIntersector1; intersectors.intersector4 = BVH4Bezier1vIntersector4Single; intersectors.intersector8 = BVH4Bezier1vIntersector8Single; intersectors.intersector16 = BVH4Bezier1vIntersector16Single; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Bezier1iIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1iIntersector1; intersectors.intersector4 = BVH4Bezier1iIntersector4Single; intersectors.intersector8 = BVH4Bezier1iIntersector8Single; intersectors.intersector16 = BVH4Bezier1iIntersector16Single; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Line4iIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Line4iIntersector1; intersectors.intersector4 = BVH4Line4iIntersector4; intersectors.intersector8 = BVH4Line4iIntersector8; intersectors.intersector16 = BVH4Line4iIntersector16; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Line4iMBIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Line4iMBIntersector1; intersectors.intersector4 = BVH4Line4iMBIntersector4; intersectors.intersector8 = BVH4Line4iMBIntersector8; intersectors.intersector16 = BVH4Line4iMBIntersector16; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Bezier1vIntersectors_OBB(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1vIntersector1_OBB; intersectors.intersector4 = BVH4Bezier1vIntersector4Single_OBB; intersectors.intersector8 = BVH4Bezier1vIntersector8Single_OBB; intersectors.intersector16 = BVH4Bezier1vIntersector16Single_OBB; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Bezier1iIntersectors_OBB(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1iIntersector1_OBB; intersectors.intersector4 = BVH4Bezier1iIntersector4Single_OBB; intersectors.intersector8 = BVH4Bezier1iIntersector8Single_OBB; intersectors.intersector16 = BVH4Bezier1iIntersector16Single_OBB; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Bezier1iMBIntersectors_OBB(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1iMBIntersector1_OBB; intersectors.intersector4 = BVH4Bezier1iMBIntersector4Single_OBB; intersectors.intersector8 = BVH4Bezier1iMBIntersector8Single_OBB; intersectors.intersector16 = BVH4Bezier1iMBIntersector16Single_OBB; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4IntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle4Intersector1Moeller; intersectors.intersector4_filter = BVH4Triangle4Intersector4HybridMoeller; intersectors.intersector4_nofilter = BVH4Triangle4Intersector4HybridMoellerNoFilter; intersectors.intersector8_filter = BVH4Triangle4Intersector8HybridMoeller; intersectors.intersector8_nofilter = BVH4Triangle4Intersector8HybridMoellerNoFilter; intersectors.intersector16_filter = BVH4Triangle4Intersector16HybridMoeller; intersectors.intersector16_nofilter = BVH4Triangle4Intersector16HybridMoellerNoFilter; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4IntersectorsInstancing(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4XfmTriangle4Intersector1Moeller; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle8IntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle8Intersector1Moeller; intersectors.intersector4_filter = BVH4Triangle8Intersector4HybridMoeller; intersectors.intersector4_nofilter = BVH4Triangle8Intersector4HybridMoellerNoFilter; intersectors.intersector8_filter = BVH4Triangle8Intersector8HybridMoeller; intersectors.intersector8_nofilter = BVH4Triangle8Intersector8HybridMoellerNoFilter; intersectors.intersector16_filter = BVH4Triangle8Intersector16HybridMoeller; intersectors.intersector16_nofilter = BVH4Triangle8Intersector16HybridMoellerNoFilter; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4vIntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle4vIntersector1Pluecker; intersectors.intersector4 = BVH4Triangle4vIntersector4HybridPluecker; intersectors.intersector8 = BVH4Triangle4vIntersector8HybridPluecker; intersectors.intersector16 = BVH4Triangle4vIntersector16HybridPluecker; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4iIntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle4iIntersector1Pluecker; intersectors.intersector4 = BVH4Triangle4iIntersector4HybridPluecker; intersectors.intersector8 = BVH4Triangle4iIntersector8HybridPluecker; intersectors.intersector16 = BVH4Triangle4iIntersector16HybridPluecker; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4vMBIntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle4vMBIntersector1Moeller; intersectors.intersector4 = BVH4Triangle4vMBIntersector4HybridMoeller; intersectors.intersector8 = BVH4Triangle4vMBIntersector8HybridMoeller; intersectors.intersector16 = BVH4Triangle4vMBIntersector16HybridMoeller; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Quad4vIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Quad4vIntersector1Moeller; intersectors.intersector4_filter = BVH4Quad4vIntersector4HybridMoeller; intersectors.intersector4_nofilter = BVH4Quad4vIntersector4HybridMoellerNoFilter; intersectors.intersector8_filter = BVH4Quad4vIntersector8HybridMoeller; intersectors.intersector8_nofilter = BVH4Quad4vIntersector8HybridMoellerNoFilter; intersectors.intersector16_filter = BVH4Quad4vIntersector16HybridMoeller; intersectors.intersector16_nofilter = BVH4Quad4vIntersector16HybridMoellerNoFilter; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Quad4iIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Quad4iIntersector1Pluecker; intersectors.intersector4 = BVH4Quad4iIntersector4HybridPluecker; intersectors.intersector8 = BVH4Quad4iIntersector8HybridPluecker; intersectors.intersector16= BVH4Quad4iIntersector16HybridPluecker; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Quad4iMBIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Quad4iMBIntersector1Pluecker; intersectors.intersector4 = BVH4Quad4iMBIntersector4HybridPluecker; intersectors.intersector8 = BVH4Quad4iMBIntersector8HybridPluecker; intersectors.intersector16= BVH4Quad4iMBIntersector16HybridPluecker; return intersectors; } void BVH4Factory::createLineSegmentsLine4i(LineSegments* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Line4i::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Line4iMeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Line4iMeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Line4iMeshBuilderSAH(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } void BVH4Factory::createTriangleMeshTriangle4Morton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4::type,mesh->parent); builder = mesh->parent->device->bvh4_factory->BVH4Triangle4MeshBuilderMortonGeneral(accel,mesh,0); } #if defined (__TARGET_AVX__) void BVH4Factory::createTriangleMeshTriangle8Morton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { accel = new BVH4(Triangle8::type,mesh->parent); builder = mesh->parent->device->bvh4_factory->BVH4Triangle8MeshBuilderMortonGeneral(accel,mesh,0); } #endif void BVH4Factory::createTriangleMeshTriangle4vMorton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4v::type,mesh->parent); builder = mesh->parent->device->bvh4_factory->BVH4Triangle4vMeshBuilderMortonGeneral(accel,mesh,0); } void BVH4Factory::createTriangleMeshTriangle4iMorton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4i::type,mesh->parent); builder = mesh->parent->device->bvh4_factory->BVH4Triangle4iMeshBuilderMortonGeneral(accel,mesh,0); } void BVH4Factory::createTriangleMeshTriangle4(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle4MeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle4MeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle4MeshBuilderMortonGeneral(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } #if defined (__TARGET_AVX__) void BVH4Factory::createTriangleMeshTriangle8(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle8::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle8MeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle8MeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle8MeshBuilderMortonGeneral(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } #endif void BVH4Factory::createTriangleMeshTriangle4v(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4v::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle4vMeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle4vMeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle4vMeshBuilderMortonGeneral(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } void BVH4Factory::createTriangleMeshTriangle4i(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4i::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle4iMeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle4iMeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle4iMeshBuilderMortonGeneral(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } Accel* BVH4Factory::BVH4Bezier1v(Scene* scene) { BVH4* accel = new BVH4(Bezier1v::type,scene); Accel::Intersectors intersectors = BVH4Bezier1vIntersectors(accel); Builder* builder = BVH4Bezier1vSceneBuilderSAH(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Bezier1i(Scene* scene) { BVH4* accel = new BVH4(Bezier1i::type,scene); Accel::Intersectors intersectors = BVH4Bezier1iIntersectors(accel); Builder* builder = BVH4Bezier1iSceneBuilderSAH(accel,scene,0); scene->needBezierVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Line4i(Scene* scene) { BVH4* accel = new BVH4(Line4i::type,scene); Accel::Intersectors intersectors = BVH4Line4iIntersectors(accel); Builder* builder = nullptr; if (scene->device->line_builder == "default" ) builder = BVH4Line4iSceneBuilderSAH(accel,scene,0); else if (scene->device->line_builder == "sah" ) builder = BVH4Line4iSceneBuilderSAH(accel,scene,0); else if (scene->device->line_builder == "dynamic" ) builder = BVH4BuilderTwoLevelLineSegmentsSAH(accel,scene,&createLineSegmentsLine4i); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->line_builder+" for BVH4<Line4i>"); scene->needLineVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Line4iMB(Scene* scene) { BVH4* accel = new BVH4(Line4i::type,scene); Accel::Intersectors intersectors = BVH4Line4iMBIntersectors(accel); Builder* builder = BVH4Line4iMBSceneBuilderSAH(accel,scene,0); scene->needLineVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Line4iTwolevel(Scene* scene) { BVH4* accel = new BVH4(Line4i::type,scene); Accel::Intersectors intersectors = BVH4Line4iIntersectors(accel); Builder* builder = BVH4BuilderTwoLevelLineSegmentsSAH(accel,scene,&createLineSegmentsLine4i); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4OBBBezier1v(Scene* scene, bool highQuality) { BVH4* accel = new BVH4(Bezier1v::type,scene); Accel::Intersectors intersectors = BVH4Bezier1vIntersectors_OBB(accel); Builder* builder = BVH4Bezier1vBuilder_OBB_New(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4OBBBezier1i(Scene* scene, bool highQuality) { BVH4* accel = new BVH4(Bezier1i::type,scene); Accel::Intersectors intersectors = BVH4Bezier1iIntersectors_OBB(accel); Builder* builder = BVH4Bezier1iBuilder_OBB_New(accel,scene,0); scene->needBezierVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4OBBBezier1iMB(Scene* scene, bool highQuality) { BVH4* accel = new BVH4(Bezier1i::type,scene); Accel::Intersectors intersectors = BVH4Bezier1iMBIntersectors_OBB(accel); Builder* builder = BVH4Bezier1iMBBuilder_OBB_New(accel,scene,0); scene->needBezierVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4IntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4IntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4>"); Builder* builder = nullptr; if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4SceneBuilderSpatialSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4SceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY); else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4); else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4Morton); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4>"); return new AccelInstance(accel,builder,intersectors); } #if defined (__TARGET_AVX__) Accel* BVH4Factory::BVH4Triangle8(Scene* scene) { BVH4* accel = new BVH4(Triangle8::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle8IntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle8IntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle8>"); Builder* builder = nullptr; if (scene->device->tri_builder == "default" ) builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle8SceneBuilderSpatialSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle8SceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY); else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle8); else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle8Morton); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle8>"); return new AccelInstance(accel,builder,intersectors); } #endif Accel* BVH4Factory::BVH4Triangle4v(Scene* scene) { BVH4* accel = new BVH4(Triangle4v::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4vIntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4vIntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4>"); Builder* builder = nullptr; if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4vSceneBuilderSpatialSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY); else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4v); else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4vMorton); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4v>"); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4i(Scene* scene) { BVH4* accel = new BVH4(Triangle4i::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4iIntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4iIntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4i>"); Builder* builder = nullptr; if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4iSceneBuilderSpatialSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY); else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4i); else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4iMorton); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4i>"); scene->needTriangleVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4vMB(Scene* scene) { BVH4* accel = new BVH4(Triangle4vMB::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4vMBIntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4vMBIntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4vMB>"); Builder* builder = nullptr; if (scene->device->tri_builder_mb == "default" ) builder = BVH4Triangle4vMBSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder_mb == "sah") builder = BVH4Triangle4vMBSceneBuilderSAH(accel,scene,0); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder_mb+" for BVH4<Triangle4vMB>"); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4InstancedBVH4Triangle4ObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsInstancing(accel); Builder* builder = BVH4BuilderInstancingTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4Twolevel(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4); return new AccelInstance(accel,builder,intersectors); } #if defined (__TARGET_AVX__) Accel* BVH4Factory::BVH4Triangle8Twolevel(Scene* scene) { BVH4* accel = new BVH4(Triangle8::type,scene); Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel); Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle8); return new AccelInstance(accel,builder,intersectors); } #endif Accel* BVH4Factory::BVH4Triangle4vTwolevel(Scene* scene) { BVH4* accel = new BVH4(Triangle4v::type,scene); Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel); Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4v); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4iTwolevel(Scene* scene) { BVH4* accel = new BVH4(Triangle4i::type,scene); Accel::Intersectors intersectors = BVH4Triangle4iIntersectorsHybrid(accel); Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4i); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4SpatialSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Builder* builder = BVH4Triangle4SceneBuilderSpatialSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } #if defined (__TARGET_AVX__) Accel* BVH4Factory::BVH4Triangle8SpatialSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle8::type,scene); Builder* builder = BVH4Triangle8SceneBuilderSpatialSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } #endif Accel* BVH4Factory::BVH4Triangle4ObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Builder* builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } #if defined (__TARGET_AVX__) Accel* BVH4Factory::BVH4Triangle8ObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle8::type,scene); Builder* builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } #endif Accel* BVH4Factory::BVH4Triangle4vObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4v::type,scene); Builder* builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4iObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4i::type,scene); Builder* builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle4iIntersectorsHybrid(accel); scene->needTriangleVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4SubdivPatch1Cached(Scene* scene) { BVH4* accel = new BVH4(SubdivPatch1Cached::type,scene); Accel::Intersectors intersectors; intersectors.ptr = accel; intersectors.intersector1 = BVH4Subdivpatch1CachedIntersector1; intersectors.intersector4 = BVH4Subdivpatch1CachedIntersector4; intersectors.intersector8 = BVH4Subdivpatch1CachedIntersector8; intersectors.intersector16 = BVH4Subdivpatch1CachedIntersector16; Builder* builder = BVH4SubdivPatch1CachedBuilderBinnedSAH(accel,scene,0); scene->needSubdivIndices = false; scene->needSubdivVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4SubdivGridEager(Scene* scene) { BVH4* accel = new BVH4(SubdivPatch1Eager::type,scene); Accel::Intersectors intersectors; intersectors.ptr = accel; intersectors.intersector1 = BVH4GridAOSIntersector1; intersectors.intersector4 = BVH4GridAOSIntersector4; intersectors.intersector8 = BVH4GridAOSIntersector8; intersectors.intersector16 = BVH4GridAOSIntersector16; Builder* builder = BVH4SubdivGridEagerBuilderBinnedSAH(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4UserGeometry(Scene* scene) { BVH4* accel = new BVH4(Object::type,scene); Accel::Intersectors intersectors; intersectors.ptr = accel; intersectors.intersector1 = BVH4VirtualIntersector1; intersectors.intersector4 = BVH4VirtualIntersector4Chunk; intersectors.intersector8 = BVH4VirtualIntersector8Chunk; intersectors.intersector16 = BVH4VirtualIntersector16Chunk; Builder* builder = BVH4VirtualSceneBuilderSAH(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4UserGeometryMB(Scene* scene) { BVH4* accel = new BVH4(Object::type,scene); Accel::Intersectors intersectors; intersectors.ptr = accel; intersectors.intersector1 = BVH4VirtualMBIntersector1; intersectors.intersector4 = BVH4VirtualMBIntersector4Chunk; intersectors.intersector8 = BVH4VirtualMBIntersector8Chunk; intersectors.intersector16 = BVH4VirtualMBIntersector16Chunk; Builder* builder = BVH4VirtualMBSceneBuilderSAH(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4ObjectSplit(TriangleMesh* mesh) { BVH4* accel = new BVH4(Triangle4::type,mesh->parent); Builder* builder = BVH4Triangle4MeshBuilderSAH(accel,mesh,0); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4vObjectSplit(TriangleMesh* mesh) { BVH4* accel = new BVH4(Triangle4v::type,mesh->parent); Builder* builder = BVH4Triangle4vMeshBuilderSAH(accel,mesh,0); Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4Refit(TriangleMesh* mesh) { BVH4* accel = new BVH4(Triangle4::type,mesh->parent); Builder* builder = BVH4Triangle4MeshRefitSAH(accel,mesh,0); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Quad4v(Scene* scene) { BVH4* accel = new BVH4(Quad4v::type,scene); Builder* builder = BVH4Quad4vSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Quad4vIntersectors(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Quad4i(Scene* scene) { BVH4* accel = new BVH4(Quad4i::type,scene); Builder* builder = BVH4Quad4iSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Quad4iIntersectors(accel); scene->needQuadVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Quad4iMB(Scene* scene) { BVH4* accel = new BVH4(Quad4iMB::type,scene); Builder* builder = BVH4Quad4iMBSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Quad4iMBIntersectors(accel); scene->needQuadVertices = true; return new AccelInstance(accel,builder,intersectors); } }
KIKI007/ReusedPrinter
external/embree/kernels/xeon/bvh/bvh4_factory.cpp
C++
mpl-2.0
52,759
/** * Nooku Platform - http://www.nooku.org/platform * * @copyright Copyright (C) 2011 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link https://github.com/nooku/nooku-platform for the canonical source repository */ if(!Attachments) var Attachments = {}; Attachments.List = new Class({ element : null, initialize: function(options) { this.element = document.id(options.container); this.url = options.action; this.token = options.token; this.coordinates = ''; this.trueSize = ''; if(!this.element) { return; } this.addCrop(); var that = this; this.element.getElements('a[data-action]').each(function(a) { if(a.get('data-action')) { a.addEvent('click', function(e) { e.stop(); that.execute(this.get('data-action'), this.get('data-id'), this.get('data-row')); }); } }); }, addCrop: function() { var target = jQuery('#target'); var img = new Image(), self = this; img.onload = function() { self.trueSize = [this.width, this.height]; if (target.length) { target.Jcrop({ boxWidth: 600, boxHeight: 600, trueSize: self.trueSize, aspectRatio: 4 / 3, minSize: [200, 150], setSelect: [0, 0, 200, 150], onSelect: self.setCoordinates.bind(self), onChange: self.setCoordinates.bind(self) }); } }; var source = target.attr("src"); if (source) { img.src = source; } }, setCoordinates: function(c) { this.coordinates = c; }, execute: function(action, id, row) { var method = '_action' + action.capitalize(); if($type(this[method]) == 'function') { this.action = action; var uri = new URI(this.url); uri.setData('id', id); this[method].call(this, uri); } }, _actionDelete: function(uri) { var form = new Kodekit.Form({ method: 'post', url: uri.toString(), params: { _action: 'delete', csrf_token: this.token } }); form.submit(); }, _actionCrop: function(uri) { jQuery.ajax({ url: uri.toString(), dataType: 'json', method: 'post', data: { _action: 'edit', csrf_token: this.token, x1: this.coordinates.x, y1: this.coordinates.y, x2: this.coordinates.x2, y2: this.coordinates.y2 } }).then(function(data, textStatus, xhr) { if (xhr.status === 204) { jQuery.ajax({ url: uri.toString(), dataType: 'json', method: 'get' }).then(function(data, textStatus, xhr) { if (xhr.status === 200 && typeof data.item === 'object') { var thumbnail = data.item.thumbnail, element = window.parent.jQuery('.thumbnail[data-id="'+data.item.id+'"] img'), source = element.attr('src'); thumbnail = source.substring(0, source.lastIndexOf('/'))+'/'+thumbnail; element.attr('src', thumbnail); if (window.parent.SqueezeBox) { window.parent.SqueezeBox.close(); } } }); } else { alert('Unable to crop thumbnail'); } }); } });
nooku/nooku-platform
component/attachments/resources/assets/js/attachments.list.js
JavaScript
mpl-2.0
4,062
/*! JointJS v3.4.1 (2021-08-18) - JavaScript diagramming library This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ this.joint = this.joint || {}; this.joint.shapes = this.joint.shapes || {}; (function (exports, basic_mjs, Element_mjs, Link_mjs) { 'use strict'; var State = basic_mjs.Circle.define('fsa.State', { attrs: { circle: { 'stroke-width': 3 }, text: { 'font-weight': '800' } } }); var StartState = Element_mjs.Element.define('fsa.StartState', { size: { width: 20, height: 20 }, attrs: { circle: { transform: 'translate(10, 10)', r: 10, fill: '#000000' } } }, { markup: '<g class="rotatable"><g class="scalable"><circle/></g></g>', }); var EndState = Element_mjs.Element.define('fsa.EndState', { size: { width: 20, height: 20 }, attrs: { '.outer': { transform: 'translate(10, 10)', r: 10, fill: '#ffffff', stroke: '#000000' }, '.inner': { transform: 'translate(10, 10)', r: 6, fill: '#000000' } } }, { markup: '<g class="rotatable"><g class="scalable"><circle class="outer"/><circle class="inner"/></g></g>', }); var Arrow = Link_mjs.Link.define('fsa.Arrow', { attrs: { '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z' }}, smooth: true }); exports.Arrow = Arrow; exports.EndState = EndState; exports.StartState = StartState; exports.State = State; }(this.joint.shapes.fsa = this.joint.shapes.fsa || {}, joint.shapes.basic, joint.dia, joint.dia));
DavidDurman/joint
dist/joint.shapes.fsa.js
JavaScript
mpl-2.0
1,920
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import { createStore, applyMiddleware } from 'redux'; import threadDispatcher from '../../common/thread-middleware'; import handleMessages from '../../common/message-handler'; import messages from './messages-worker'; import reducers from './reducers'; import thunk from 'redux-thunk'; const store = createStore( // Reducers: reducers, // Initial State: {}, // Enhancers: applyMiddleware( ...[ thunk, threadDispatcher(self, 'toContent'), ].filter(fn => fn) ) ); handleMessages(self, store, messages);
squarewave/bhr.html
src/workers/summary/index.js
JavaScript
mpl-2.0
743
package org.hl7.v3; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ResponseMode. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="ResponseMode"> * &lt;restriction base="{urn:hl7-org:v3}cs"> * &lt;enumeration value="D"/> * &lt;enumeration value="I"/> * &lt;enumeration value="Q"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "ResponseMode") @XmlEnum public enum ResponseMode { D, I, Q; public String value() { return name(); } public static ResponseMode fromValue(String v) { return valueOf(v); } }
jembi/openhim-encounter-orchestrator
src/main/java/org/hl7/v3/ResponseMode.java
Java
mpl-2.0
754
#if BUILD_UNIT_TESTS #include "augs/misc/enum/enum_map.h" #include <Catch/single_include/catch2/catch.hpp> TEST_CASE("EnumMap") { enum class tenum { _0, _1, _2, _3, _4, COUNT }; augs::enum_map<tenum, int> mm; mm[tenum::_0] = 0; mm[tenum::_1] = 1; mm[tenum::_2] = 2; int cnt = 0; for (const auto&& m : mm) { REQUIRE(m.first == tenum(m.second)); REQUIRE(m.second == cnt++); } REQUIRE(3 == cnt); for (const auto&& m : reverse(mm)) { REQUIRE(m.first == tenum(m.second)); REQUIRE(m.second == --cnt); } REQUIRE(0 == cnt); { augs::enum_map<tenum, int> emp; for (const auto&& abc : emp) { REQUIRE(false); (void)abc; } for (const auto&& abc : reverse(emp)) { REQUIRE(false); (void)abc; } REQUIRE(emp.size() == 0); emp[tenum::_0] = 48; REQUIRE(emp.size() == 1); for (const auto&& m : reverse(emp)) { REQUIRE(48 == m.second); } emp.clear(); REQUIRE(emp.size() == 0); emp[tenum::_1] = 84; REQUIRE(emp.size() == 1); for (const auto&& m : reverse(emp)) { REQUIRE(84 == m.second); } emp[tenum::_0] = 0; emp[tenum::_1] = 1; emp[tenum::_2] = 2; REQUIRE(emp.size() == 3); for (const auto&& m : emp) { REQUIRE(m.first == tenum(m.second)); REQUIRE(m.second == cnt++); } REQUIRE(3 == cnt); for (const auto&& m : reverse(emp)) { REQUIRE(m.first == tenum(m.second)); REQUIRE(m.second == --cnt); } emp.clear(); REQUIRE(emp.size() == 0); emp[tenum::_4] = 4; emp[tenum::_3] = 3; emp[tenum::_1] = 1; emp[tenum::_0] = 0; auto it = emp.rbegin(); REQUIRE((*it).second == 4); REQUIRE((*++it).second == 3); REQUIRE((*++it).second == 1); REQUIRE((*++it).second == 0); REQUIRE(++it == emp.rend()); } } #endif
TeamHypersomnia/Augmentations
src/augs/misc/enum/enum_map.cpp
C++
agpl-3.0
1,737
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated: 12/10/2015, 13:28 * */ package ims.core.clinical.domain.objects; /** * * @author John MacEnri * Generated. */ public class NonUniqueTaxonomyMap extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable { public static final int CLASSID = 1003100071; private static final long serialVersionUID = 1003100071L; public static final String CLASSVERSION = "${ClassVersion}"; @Override public boolean shouldCapQuery() { return true; } private ims.domain.lookups.LookupInstance taxonomyName; private String taxonomyCode; private java.util.Date effectiveFrom; private java.util.Date effectiveTo; /** SystemInformation */ private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation(); public NonUniqueTaxonomyMap (Integer id, int ver) { super(id, ver); isComponentClass=true; } public NonUniqueTaxonomyMap () { super(); isComponentClass=true; } public NonUniqueTaxonomyMap (Integer id, int ver, Boolean includeRecord) { super(id, ver, includeRecord); isComponentClass=true; } public Class getRealDomainClass() { return ims.core.clinical.domain.objects.NonUniqueTaxonomyMap.class; } public ims.domain.lookups.LookupInstance getTaxonomyName() { return taxonomyName; } public void setTaxonomyName(ims.domain.lookups.LookupInstance taxonomyName) { this.taxonomyName = taxonomyName; } public String getTaxonomyCode() { return taxonomyCode; } public void setTaxonomyCode(String taxonomyCode) { if ( null != taxonomyCode && taxonomyCode.length() > 30 ) { throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for taxonomyCode. Tried to set value: "+ taxonomyCode); } this.taxonomyCode = taxonomyCode; } public java.util.Date getEffectiveFrom() { return effectiveFrom; } public void setEffectiveFrom(java.util.Date effectiveFrom) { this.effectiveFrom = effectiveFrom; } public java.util.Date getEffectiveTo() { return effectiveTo; } public void setEffectiveTo(java.util.Date effectiveTo) { this.effectiveTo = effectiveTo; } public ims.domain.SystemInformation getSystemInformation() { if (systemInformation == null) systemInformation = new ims.domain.SystemInformation(); return systemInformation; } /** * isConfigurationObject * Taken from the Usage property of the business object, this method will return * a boolean indicating whether this is a configuration object or not * Configuration = true, Instantiation = false */ public static boolean isConfigurationObject() { if ( "Instantiation".equals("Configuration") ) return true; else return false; } public int getClassId() { return CLASSID; } public String getClassVersion() { return CLASSVERSION; } public String toAuditString() { StringBuffer auditStr = new StringBuffer(); auditStr.append("\r\n*taxonomyName* :"); if (taxonomyName != null) auditStr.append(taxonomyName.getText()); auditStr.append("; "); auditStr.append("\r\n*taxonomyCode* :"); auditStr.append(taxonomyCode); auditStr.append("; "); auditStr.append("\r\n*effectiveFrom* :"); auditStr.append(effectiveFrom); auditStr.append("; "); auditStr.append("\r\n*effectiveTo* :"); auditStr.append(effectiveTo); auditStr.append("; "); return auditStr.toString(); } public String toXMLString() { return toXMLString(new java.util.HashMap()); } public String toXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); sb.append("<class type=\"" + this.getClass().getName() + "\" "); sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" "); sb.append(" classVersion=\"" + this.getClassVersion() + "\" "); sb.append(" component=\"" + this.getIsComponentClass() + "\" >"); if (domMap.get(this) == null) { domMap.put(this, this); sb.append(this.fieldsToXMLString(domMap)); } sb.append("</class>"); return sb.toString(); } public String fieldsToXMLString(java.util.HashMap domMap) { StringBuffer sb = new StringBuffer(); if (this.getTaxonomyName() != null) { sb.append("<taxonomyName>"); sb.append(this.getTaxonomyName().toXMLString()); sb.append("</taxonomyName>"); } if (this.getTaxonomyCode() != null) { sb.append("<taxonomyCode>"); sb.append(ims.framework.utils.StringUtils.encodeXML(this.getTaxonomyCode().toString())); sb.append("</taxonomyCode>"); } if (this.getEffectiveFrom() != null) { sb.append("<effectiveFrom>"); sb.append(new ims.framework.utils.DateTime(this.getEffectiveFrom()).toString(ims.framework.utils.DateTimeFormat.MILLI)); sb.append("</effectiveFrom>"); } if (this.getEffectiveTo() != null) { sb.append("<effectiveTo>"); sb.append(new ims.framework.utils.DateTime(this.getEffectiveTo()).toString(ims.framework.utils.DateTimeFormat.MILLI)); sb.append("</effectiveTo>"); } return sb.toString(); } public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception { if (list == null) list = new java.util.ArrayList(); fillListFromXMLString(list, el, factory, domMap); return list; } public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception { if (set == null) set = new java.util.HashSet(); fillSetFromXMLString(set, el, factory, domMap); return set; } private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); NonUniqueTaxonomyMap domainObject = getNonUniqueTaxonomyMapfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!set.contains(domainObject)) set.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = set.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { set.remove(iter.next()); } } private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return; java.util.List cl = el.elements("class"); int size = cl.size(); for(int i=0; i<size; i++) { org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i); NonUniqueTaxonomyMap domainObject = getNonUniqueTaxonomyMapfromXML(itemEl, factory, domMap); if (domainObject == null) { continue; } int domIdx = list.indexOf(domainObject); if (domIdx == -1) { list.add(i, domainObject); } else if (i != domIdx && i < list.size()) { Object tmp = list.get(i); list.set(i, list.get(domIdx)); list.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=list.size(); while (i1 > size) { list.remove(i1-1); i1=list.size(); } } public static NonUniqueTaxonomyMap getNonUniqueTaxonomyMapfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml)); return getNonUniqueTaxonomyMapfromXML(doc.getRootElement(), factory, domMap); } public static NonUniqueTaxonomyMap getNonUniqueTaxonomyMapfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception { if (el == null) return null; String className = el.attributeValue("type"); if (!NonUniqueTaxonomyMap.class.getName().equals(className)) { Class clz = Class.forName(className); if (!NonUniqueTaxonomyMap.class.isAssignableFrom(clz)) throw new Exception("Element of type = " + className + " cannot be imported using the NonUniqueTaxonomyMap class"); String shortClassName = className.substring(className.lastIndexOf(".")+1); String methodName = "get" + shortClassName + "fromXML"; java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class}); return (NonUniqueTaxonomyMap)m.invoke(null, new Object[]{el, factory, domMap}); } String impVersion = el.attributeValue("classVersion"); if(!impVersion.equals(NonUniqueTaxonomyMap.CLASSVERSION)) { throw new Exception("Incompatible class structure found. Cannot import instance."); } NonUniqueTaxonomyMap ret = null; if (ret == null) { ret = new NonUniqueTaxonomyMap(); } fillFieldsfromXML(el, factory, ret, domMap); return ret; } public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, NonUniqueTaxonomyMap obj, java.util.HashMap domMap) throws Exception { org.dom4j.Element fldEl; fldEl = el.element("taxonomyName"); if(fldEl != null) { fldEl = fldEl.element("lki"); obj.setTaxonomyName(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory)); } fldEl = el.element("taxonomyCode"); if(fldEl != null) { obj.setTaxonomyCode(new String(fldEl.getTextTrim())); } fldEl = el.element("effectiveFrom"); if(fldEl != null) { obj.setEffectiveFrom(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim())); } fldEl = el.element("effectiveTo"); if(fldEl != null) { obj.setEffectiveTo(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim())); } } public static String[] getCollectionFields() { return new String[]{ }; } /** equals */ public boolean equals(Object obj) { if (null == obj) { return false; } if(!(obj instanceof NonUniqueTaxonomyMap)) { return false; } NonUniqueTaxonomyMap compareObj=(NonUniqueTaxonomyMap)obj; if((taxonomyCode==null ? compareObj.taxonomyCode == null : taxonomyCode.equals(compareObj.taxonomyCode))&& (taxonomyName==null ? compareObj.taxonomyName==null : taxonomyName.equals(compareObj.taxonomyName))&& (effectiveFrom==null? compareObj.effectiveFrom==null : effectiveFrom.equals(compareObj.effectiveFrom))&& (effectiveTo==null? compareObj.effectiveTo==null : effectiveTo.equals(compareObj.effectiveTo))) return true; return super.equals(obj); } /** toString */ public String toString() { StringBuffer objStr = new StringBuffer(); if (taxonomyName != null) objStr.append(taxonomyName.getText() + "-"); objStr.append(taxonomyCode); return objStr.toString(); } /** hashcode */ public int hashCode() { int hash = 0; if (taxonomyName!= null) hash += taxonomyName.hashCode()* 10011; if (taxonomyCode!= null) hash += taxonomyCode.hashCode(); if (effectiveFrom!= null) hash += effectiveFrom.hashCode(); if (effectiveTo!= null) hash += effectiveTo.hashCode(); return hash; } public static class FieldNames { public static final String ID = "id"; public static final String TaxonomyName = "taxonomyName"; public static final String TaxonomyCode = "taxonomyCode"; public static final String EffectiveFrom = "effectiveFrom"; public static final String EffectiveTo = "effectiveTo"; } }
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/DomainObjects/src/ims/core/clinical/domain/objects/NonUniqueTaxonomyMap.java
Java
agpl-3.0
14,623
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.analysis; import com.google.common.collect.ImmutableMap; import org.apache.lucene.analysis.Analyzer; import org.elasticsearch.ElasticSearchIllegalArgumentException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.component.CloseableComponent; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.AbstractIndexComponent; import org.elasticsearch.index.Index; import org.elasticsearch.index.settings.IndexSettings; import org.elasticsearch.indices.analysis.IndicesAnalysisService; import java.util.Map; import static com.google.common.collect.Maps.newHashMap; /** * */ public class AnalysisService extends AbstractIndexComponent implements CloseableComponent { private final ImmutableMap<String, NamedAnalyzer> analyzers; private final ImmutableMap<String, TokenizerFactory> tokenizers; private final ImmutableMap<String, CharFilterFactory> charFilters; private final ImmutableMap<String, TokenFilterFactory> tokenFilters; private final NamedAnalyzer defaultAnalyzer; private final NamedAnalyzer defaultIndexAnalyzer; private final NamedAnalyzer defaultSearchAnalyzer; private final NamedAnalyzer defaultSearchQuoteAnalyzer; public AnalysisService(Index index) { this(index, ImmutableSettings.Builder.EMPTY_SETTINGS, null, null, null, null, null); } @Inject public AnalysisService(Index index, @IndexSettings Settings indexSettings, @Nullable IndicesAnalysisService indicesAnalysisService, @Nullable Map<String, AnalyzerProviderFactory> analyzerFactoryFactories, @Nullable Map<String, TokenizerFactoryFactory> tokenizerFactoryFactories, @Nullable Map<String, CharFilterFactoryFactory> charFilterFactoryFactories, @Nullable Map<String, TokenFilterFactoryFactory> tokenFilterFactoryFactories) { super(index, indexSettings); Map<String, TokenizerFactory> tokenizers = newHashMap(); if (tokenizerFactoryFactories != null) { Map<String, Settings> tokenizersSettings = indexSettings.getGroups("index.analysis.tokenizer"); for (Map.Entry<String, TokenizerFactoryFactory> entry : tokenizerFactoryFactories.entrySet()) { String tokenizerName = entry.getKey(); TokenizerFactoryFactory tokenizerFactoryFactory = entry.getValue(); Settings tokenizerSettings = tokenizersSettings.get(tokenizerName); if (tokenizerSettings == null) { tokenizerSettings = ImmutableSettings.Builder.EMPTY_SETTINGS; } TokenizerFactory tokenizerFactory = tokenizerFactoryFactory.create(tokenizerName, tokenizerSettings); tokenizers.put(tokenizerName, tokenizerFactory); tokenizers.put(Strings.toCamelCase(tokenizerName), tokenizerFactory); } } if (indicesAnalysisService != null) { for (Map.Entry<String, PreBuiltTokenizerFactoryFactory> entry : indicesAnalysisService.tokenizerFactories().entrySet()) { String name = entry.getKey(); if (!tokenizers.containsKey(name)) { tokenizers.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } name = Strings.toCamelCase(entry.getKey()); if (!name.equals(entry.getKey())) { if (!tokenizers.containsKey(name)) { tokenizers.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } } } } this.tokenizers = ImmutableMap.copyOf(tokenizers); Map<String, CharFilterFactory> charFilters = newHashMap(); if (charFilterFactoryFactories != null) { Map<String, Settings> charFiltersSettings = indexSettings.getGroups("index.analysis.char_filter"); for (Map.Entry<String, CharFilterFactoryFactory> entry : charFilterFactoryFactories.entrySet()) { String charFilterName = entry.getKey(); CharFilterFactoryFactory charFilterFactoryFactory = entry.getValue(); Settings charFilterSettings = charFiltersSettings.get(charFilterName); if (charFilterSettings == null) { charFilterSettings = ImmutableSettings.Builder.EMPTY_SETTINGS; } CharFilterFactory tokenFilterFactory = charFilterFactoryFactory.create(charFilterName, charFilterSettings); charFilters.put(charFilterName, tokenFilterFactory); charFilters.put(Strings.toCamelCase(charFilterName), tokenFilterFactory); } } if (indicesAnalysisService != null) { for (Map.Entry<String, PreBuiltCharFilterFactoryFactory> entry : indicesAnalysisService.charFilterFactories().entrySet()) { String name = entry.getKey(); if (!charFilters.containsKey(name)) { charFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } name = Strings.toCamelCase(entry.getKey()); if (!name.equals(entry.getKey())) { if (!charFilters.containsKey(name)) { charFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } } } } this.charFilters = ImmutableMap.copyOf(charFilters); Map<String, TokenFilterFactory> tokenFilters = newHashMap(); if (tokenFilterFactoryFactories != null) { Map<String, Settings> tokenFiltersSettings = indexSettings.getGroups("index.analysis.filter"); for (Map.Entry<String, TokenFilterFactoryFactory> entry : tokenFilterFactoryFactories.entrySet()) { String tokenFilterName = entry.getKey(); TokenFilterFactoryFactory tokenFilterFactoryFactory = entry.getValue(); Settings tokenFilterSettings = tokenFiltersSettings.get(tokenFilterName); if (tokenFilterSettings == null) { tokenFilterSettings = ImmutableSettings.Builder.EMPTY_SETTINGS; } TokenFilterFactory tokenFilterFactory = tokenFilterFactoryFactory.create(tokenFilterName, tokenFilterSettings); tokenFilters.put(tokenFilterName, tokenFilterFactory); tokenFilters.put(Strings.toCamelCase(tokenFilterName), tokenFilterFactory); } } // pre initialize the globally registered ones into the map if (indicesAnalysisService != null) { for (Map.Entry<String, PreBuiltTokenFilterFactoryFactory> entry : indicesAnalysisService.tokenFilterFactories().entrySet()) { String name = entry.getKey(); if (!tokenFilters.containsKey(name)) { tokenFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } name = Strings.toCamelCase(entry.getKey()); if (!name.equals(entry.getKey())) { if (!tokenFilters.containsKey(name)) { tokenFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } } } } this.tokenFilters = ImmutableMap.copyOf(tokenFilters); Map<String, AnalyzerProvider> analyzerProviders = newHashMap(); if (analyzerFactoryFactories != null) { Map<String, Settings> analyzersSettings = indexSettings.getGroups("index.analysis.analyzer"); for (Map.Entry<String, AnalyzerProviderFactory> entry : analyzerFactoryFactories.entrySet()) { String analyzerName = entry.getKey(); AnalyzerProviderFactory analyzerFactoryFactory = entry.getValue(); Settings analyzerSettings = analyzersSettings.get(analyzerName); if (analyzerSettings == null) { analyzerSettings = ImmutableSettings.Builder.EMPTY_SETTINGS; } AnalyzerProvider analyzerFactory = analyzerFactoryFactory.create(analyzerName, analyzerSettings); analyzerProviders.put(analyzerName, analyzerFactory); } } if (indicesAnalysisService != null) { for (Map.Entry<String, PreBuiltAnalyzerProviderFactory> entry : indicesAnalysisService.analyzerProviderFactories().entrySet()) { String name = entry.getKey(); if (!analyzerProviders.containsKey(name)) { analyzerProviders.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } name = Strings.toCamelCase(entry.getKey()); if (!name.equals(entry.getKey())) { if (!analyzerProviders.containsKey(name)) { analyzerProviders.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS)); } } } } if (!analyzerProviders.containsKey("default")) { analyzerProviders.put("default", new StandardAnalyzerProvider(index, indexSettings, null, "default", ImmutableSettings.Builder.EMPTY_SETTINGS)); } if (!analyzerProviders.containsKey("default_index")) { analyzerProviders.put("default_index", analyzerProviders.get("default")); } if (!analyzerProviders.containsKey("default_search")) { analyzerProviders.put("default_search", analyzerProviders.get("default")); } if (!analyzerProviders.containsKey("default_search_quoted")) { analyzerProviders.put("default_search_quoted", analyzerProviders.get("default_search")); } Map<String, NamedAnalyzer> analyzers = newHashMap(); for (AnalyzerProvider analyzerFactory : analyzerProviders.values()) { if (analyzerFactory instanceof CustomAnalyzerProvider) { ((CustomAnalyzerProvider) analyzerFactory).build(this); } Analyzer analyzerF = analyzerFactory.get(); if (analyzerF == null) { throw new ElasticSearchIllegalArgumentException("analyzer [" + analyzerFactory.name() + "] created null analyzer"); } NamedAnalyzer analyzer; // if we got a named analyzer back, use it... if (analyzerF instanceof NamedAnalyzer) { analyzer = (NamedAnalyzer) analyzerF; } else { analyzer = new NamedAnalyzer(analyzerFactory.name(), analyzerFactory.scope(), analyzerF); } analyzers.put(analyzerFactory.name(), analyzer); analyzers.put(Strings.toCamelCase(analyzerFactory.name()), analyzer); String strAliases = indexSettings.get("index.analysis.analyzer." + analyzerFactory.name() + ".alias"); if (strAliases != null) { for (String alias : Strings.commaDelimitedListToStringArray(strAliases)) { analyzers.put(alias, analyzer); } } String[] aliases = indexSettings.getAsArray("index.analysis.analyzer." + analyzerFactory.name() + ".alias"); for (String alias : aliases) { analyzers.put(alias, analyzer); } } defaultAnalyzer = analyzers.get("default"); if (defaultAnalyzer == null) { throw new ElasticSearchIllegalArgumentException("no default analyzer configured"); } defaultIndexAnalyzer = analyzers.containsKey("default_index") ? analyzers.get("default_index") : analyzers.get("default"); defaultSearchAnalyzer = analyzers.containsKey("default_search") ? analyzers.get("default_search") : analyzers.get("default"); defaultSearchQuoteAnalyzer = analyzers.containsKey("default_search_quote") ? analyzers.get("default_search_quote") : defaultSearchAnalyzer; this.analyzers = ImmutableMap.copyOf(analyzers); } public void close() { for (NamedAnalyzer analyzer : analyzers.values()) { if (analyzer.scope() == AnalyzerScope.INDEX) { try { analyzer.close(); } catch (NullPointerException e) { // because analyzers are aliased, they might be closed several times // an NPE is thrown in this case, so ignore.... } catch (Exception e) { logger.debug("failed to close analyzer " + analyzer); } } } } public NamedAnalyzer analyzer(String name) { return analyzers.get(name); } public NamedAnalyzer defaultAnalyzer() { return defaultAnalyzer; } public NamedAnalyzer defaultIndexAnalyzer() { return defaultIndexAnalyzer; } public NamedAnalyzer defaultSearchAnalyzer() { return defaultSearchAnalyzer; } public NamedAnalyzer defaultSearchQuoteAnalyzer() { return defaultSearchQuoteAnalyzer; } public TokenizerFactory tokenizer(String name) { return tokenizers.get(name); } public CharFilterFactory charFilter(String name) { return charFilters.get(name); } public TokenFilterFactory tokenFilter(String name) { return tokenFilters.get(name); } }
exercitussolus/yolo
src/main/java/org/elasticsearch/index/analysis/AnalysisService.java
Java
agpl-3.0
14,624
<?php /** * Smarty Internal Plugin Compile Make_Nocache * Compiles the {make_nocache} tag * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Make_Nocache Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Make_Nocache extends Smarty_Internal_CompileBase { /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $option_flags = []; /** * Array of names of required attribute required by tag * * @var array */ public $required_attributes = ['var']; /** * Shorttag attribute order defined by its names * * @var array */ public $shorttag_order = ['var']; /** * Compiles code for the {make_nocache} tag * * @param array $args array with attributes from parser * @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object * @param array $parameter array with compilation parameter * * @return string compiled code * @throws \SmartyCompilerException */ public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler, $parameter) { // check and get attributes $_attr = $this->getAttributes($compiler, $args); if ($compiler->template->caching) { $output = "<?php \$_smarty_tpl->smarty->ext->_make_nocache->save(\$_smarty_tpl, {$_attr[ 'var' ]});\n?>\n"; $compiler->has_code = true; $compiler->suppressNocacheProcessing = true; return $output; } else { return true; } } }
WWXD/WorldWeb-XD
lib/smarty/sysplugins/smarty_internal_compile_make_nocache.php
PHP
agpl-3.0
1,773
<?php /* * Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io> * This file is part of Pydio. * * Pydio is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pydio 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Pydio. If not, see <http://www.gnu.org/licenses/>. * * The latest code can be found at <https://pydio.com>. */ // spanish translation: Salva Gómez <salva.gomez at gmail.com>, 2015 $mess=array( "Generic Conf Features" => "Configuraciones genéricas", "Let user create repositories" => "Permitir al usuario crear repositorios", "Remember guest preferences" => "Recordar preferencias de invitado", "If the 'guest' user is enabled, remember her preferences accross sessions." => "Si el usuario 'Invitado' está habilitado, recordar sus preferencias a través de sesiones.", "Configurations Management" => "Gestión de configuraciones", "Sets how the application core data (users,roles,etc) is stored." => "Establece cómo se almacenan los datos básicos de aplicación (usuarios, roles, etc.)", "Default start repository" => "Repositorio de inicio por defecto", "Default repository" => "Repositorio por defecto", "Maximum number of shared users per user" => "Número máximo de usuarios compartidos por usuario", "Shared users limit" => "Límite de usuarios compartidos", "Core SQL Connexion" => "Conexión SQL Principal", "SQL Connexion" => "Conexión SQL", "Simple SQL Connexion definition that can be used by other sql-based plugins" => "Definición de conexión SQL simple que puede ser utilizada por otros plugins basados en SQL", "Preferences Saving" => "Preferencias de guardado", "Skip user history" => "Omitir preferencias de interfaz", "Use this option to avoid automatic reloading of the interface state (last folder, opened tabs, etc)" => "Utilice esta opción para evitar la carga automática del estado de la interfaz (última carpeta, pestañas abiertas, etc)", "Internal / External Users" => "Usuarios internos / externos", "Maximum number of users displayed in the users autocompleter" => "Número máximo de usuarios mostrados en la lista autocompletada de usuarios", "Users completer limit" => "Límite del completador de usuarios", "Minimum number of characters to trigger the auto completion feature" => "Número mínimo de caracteres para activar la función de autocompletado", "Users completer min chars" => "Número mínimo de caracteres del completador de usuarios", "Do not display real login in parenthesis" => "No mostrar el nombre de inicio de sesión real entre paréntesis", "Hide real login" => "Ocultar nombre de inicio de sesión real", "See existing users" => "Ver usuarios existentes", "Allow the users to pick an existing user when sharing a folder" => "Permitir a los usuarios elegir un usuario existente al compartir una carpeta", "Create external users" => "Crear usuarios externos", "Allow the users to create a new user when sharing a folder" => "Permitir a los usuarios crear un nuevo usuario al compartir una carpeta", "External users parameters" => "Parámetros de usuarios externos", "List of parameters to be edited when creating a new shared user." => "Lista de parámetros a editar al crear un nuevo usuario compartido.", "Configuration Store Instance" => "Instancia de almacenamiento de la configuración", "Instance" => "Instancia", "Choose the configuration plugin" => "Seleccionar el plugin de configuración", "Name" => "Nombre", "Full name displayed to others" => "Mostrar el nombre completo a los demás", "Avatar" => "Avatar", "Image displayed next to the user name" => "Imágen mostrada junto al nombre de usuario", "Email" => "Correo electrónico", "Address used for notifications" => "Dirección utilizada para las notificaciones", "Country" => "País", "Language" => "Idioma", "User Language" => "Idioma del usuario", "Role Label" => "Etiqueta de rol", "Users Lock Action" => "Acción de bloqueo de usuarios", "If set, this action will be triggered automatically at users login. Can be logout (to lock out the users), pass_change (to force password change), or anything else" => "Si se establece, esta acción se activará automáticamente en el inicio de sesión de los usuarios. Puede ser cerrar la sesión (para bloquear a los usuarios), cambiar contraseña (para forzar el cambio de contraseña), o cualquier otra cosa", "Worskpace creation delegation" => "Delegación de la creación de repositorios", "Let user create repositories from templates" => "Permitir al usuario crear repositorios usando plantillas", "Whether users can create their own repositories, based on predefined templates." => "Si los usuarios pueden crear sus propios repositorios, hacerlo basándose en plantillas predefinidas.", "Users Directory Listing" => "Listado del directorio de usuarios", "Share with existing users from all groups" => "Compartir con los usuarios existentes de todos los grupos", "Allow to search users from other groups through auto completer (can be handy if previous option is set to false) and share workspaces with them" => "Permitir de buscar usuarios de otros grupos a través de autocompletar (puede ser útil si la opción anterior se establece en False) y compartir repositorios con ellos", "List existing from all groups" => "Listar existentes de todos los grupos", "If previous option is set to True, directly display a full list of users from all groups" => "Si la opción anterior se establece en True, mostrar directamente una lista completa de los usuarios de todos los grupos", "Roles / Groups Directory Listing" => "Listado de roles / directorio de grupos", "Display roles and/or groups" => "Mostrar roles y/o grupos", "Users only (do not list groups nor roles)" => "Sólo usuarios (no listar grupos ni roles)", "Allow Group Listing" => "Permitir el listado de grupos", "Allow Role Listing" => "Permitir el listado de roles", "Role/Group Listing" => "Listado de roles/grupos", "List Roles By" => "Listar roles por", "All roles" => "Todos los roles", "User roles only" => "Sólo roles de usuario", "role prefix" => "Prefijo del rol", "Excluded Roles" => "Roles excluidos", "Included Roles" => "Roles incluidos", "Some roles should be disappered in the list. list separated by ',' or start with 'preg:' for regex." => "Roles ocultos en la lista. Lista separada por ',' o empezar con 'preg: ' para expresiones regulares regex.", "Some roles should be shown in the list. list separated by ',' or start with 'preg:' for regex." => "Roles que deben mostrarse en la lista. Lista separada por ',' o empezar con 'preg: ' para expresiones regulares regex.", "External Users Creation" => "Creación de usuarios externos", "Always override other roles, included group roles." => "Ignorar siempre otros roles, incluido los roles de grupo.", "Always Override" => "Ignorar Siempre", "Do not load groups and users list if no regexp is entered. Avoid sending large search on LDAP." => "No cargar la lista de grupos y usuarios si no se introduce una regexp. Evita enviar búsquedas largas a LDAP.", "Make regexp mandatory" => "Regexp obligatorio", );
pydio/pydio-core
core/src/plugins/core.conf/i18n/conf/es.php
PHP
agpl-3.0
7,509
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\Profiler; use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface; /** * Profile. * * @author Fabien Potencier <fabien@symfony.com> */ class Profile { private $token; /** * @var DataCollectorInterface[] */ private $collectors = array(); private $ip; private $method; private $url; private $time; /** * @var Profile */ private $parent; /** * @var Profile[] */ private $children = array(); /** * Constructor. * * @param string $token The token */ public function __construct($token) { $this->token = $token; } /** * Returns the parent profile. * * @return Profile The parent profile */ public function getParent() { return $this->parent; } /** * Sets the parent token * * @param Profile $parent The parent Profile */ public function setParent( Profile $parent ) { $this->parent = $parent; } /** * Returns the parent token. * * @return null|string The parent token */ public function getParentToken() { return $this->parent ? $this->parent->getToken() : null; } /** * Gets the token. * * @return string The token */ public function getToken() { return $this->token; } /** * Sets the token. * * @param string $token The token */ public function setToken( $token ) { $this->token = $token; } /** * Returns the IP. * * @return string The IP */ public function getIp() { return $this->ip; } /** * Sets the IP. * * @param string $ip */ public function setIp($ip) { $this->ip = $ip; } /** * Returns the request method. * * @return string The request method */ public function getMethod() { return $this->method; } public function setMethod($method) { $this->method = $method; } /** * Returns the URL. * * @return string The URL */ public function getUrl() { return $this->url; } public function setUrl($url) { $this->url = $url; } /** * Returns the time. * * @return string The time */ public function getTime() { if (null === $this->time) { return 0; } return $this->time; } public function setTime($time) { $this->time = $time; } /** * Finds children profilers. * * @return Profile[] An array of Profile */ public function getChildren() { return $this->children; } /** * Sets children profiler. * * @param Profile[] $children An array of Profile */ public function setChildren(array $children) { $this->children = array(); foreach ($children as $child) { $this->addChild($child); } } /** * Adds the child token * * @param Profile $child The child Profile */ public function addChild(Profile $child) { $this->children[] = $child; $child->setParent($this); } /** * Gets a Collector by name. * * @param string $name A collector name * * @return DataCollectorInterface A DataCollectorInterface instance * * @throws \InvalidArgumentException if the collector does not exist */ public function getCollector($name) { if (!isset($this->collectors[$name])) { throw new \InvalidArgumentException(sprintf('Collector "%s" does not exist.', $name)); } return $this->collectors[$name]; } /** * Gets the Collectors associated with this profile. * * @return DataCollectorInterface[] */ public function getCollectors() { return $this->collectors; } /** * Sets the Collectors associated with this profile. * * @param DataCollectorInterface[] $collectors */ public function setCollectors(array $collectors) { $this->collectors = array(); foreach ($collectors as $collector) { $this->addCollector($collector); } } /** * Adds a Collector. * * @param DataCollectorInterface $collector A DataCollectorInterface instance */ public function addCollector(DataCollectorInterface $collector) { $this->collectors[$collector->getName()] = $collector; } /** * Returns true if a Collector for the given name exists. * * @param string $name A collector name * * @return bool */ public function hasCollector($name) { return isset($this->collectors[$name]); } public function __sleep() { return array('token', 'parent', 'children', 'collectors', 'ip', 'method', 'url', 'time'); } }
KWZwickau/KREDA-Sphere
Library/MOC-V/Component/Router/Vendor/Symfony/Component/HttpKernel/Profiler/Profile.php
PHP
agpl-3.0
5,311
# session module tests # # Copyright (C) 2012-2013 Mohammed Morsi <mo@morsi.org> # Licensed under the AGPLv3 http://www.gnu.org/licenses/agpl.txt require 'spec_helper' require 'timecop' require 'users/session' module Users describe Session do after(:all) do Timecop.return end describe "#initialize" do it "sets attributes" do id = Motel.gen_uuid u = User.new :id => 'user1' s = Session.new :id => id, :user => u, :endpoint_id => 'node1' s.id.should == id s.user.id.should == 'user1' s.refreshed_time.should_not be_nil s.endpoint_id.should == 'node1' end end describe "#timed_out" do before(:each) do Timecop.freeze @u = User.new :id => 'user1' @s = Session.new :id => 'id', :user => @u end after(:each) do Timecop.travel end context "timeout has passed" do it "returns true" do Timecop.freeze Session::SESSION_EXPIRATION + 1 @s.timed_out?.should be_true end end context "timeout has not passed" do it "returns false" do @s.timed_out?.should be_false @s.instance_variable_get(:@refreshed_time).should == Time.now end end context "user is permenant" do it "always returns false" do @u.permenant = true Timecop.freeze Session::SESSION_EXPIRATION + 1 @s.timed_out?.should be_false end end end describe "#to_json" do it "returns json representation of session" do u = User.new :id => 'user1' s = Session.new :id => '1234', :user => u, :endpoint_id => 'node1' j = s.to_json j.should include('"json_class":"Users::Session"') j.should include('"id":"1234"') j.should include('"json_class":"Users::User"') j.should include('"id":"user1"') j.should include('"refreshed_time":') j.should include('"endpoint_id":"node1"') end end describe "#json_create" do it "returns session from json format" do j = '{"json_class":"Users::Session","data":{"user":{"json_class":"Users::User","data":{"id":"user1","email":null,"roles":null,"permenant":false,"npc":false,"attributes":null,"password":null,"registration_code":null}},"id":"1234","refreshed_time":"2013-05-30 00:43:54 -0400"}}' s = ::RJR::JSONParser.parse(j) s.class.should == Users::Session s.id.should == "1234" s.user.id.should == 'user1' s.refreshed_time.should_not be_nil end end end # describe Session end # module Users
movitto/omega
spec/users/session_spec.rb
Ruby
agpl-3.0
2,513
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import IconButton from './icon_button'; import DropdownMenu from './dropdown_menu'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ delete: { id: 'status.delete', defaultMessage: 'Delete' }, mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' }, mute: { id: 'account.mute', defaultMessage: 'Mute @{name}' }, block: { id: 'account.block', defaultMessage: 'Block @{name}' }, reply: { id: 'status.reply', defaultMessage: 'Reply' }, replyAll: { id: 'status.replyAll', defaultMessage: 'Reply to thread' }, reblog: { id: 'status.reblog', defaultMessage: 'Boost' }, cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' }, favourite: { id: 'status.favourite', defaultMessage: 'Favourite' }, open: { id: 'status.open', defaultMessage: 'Expand this status' }, report: { id: 'status.report', defaultMessage: 'Report @{name}' }, muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' }, unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' }, }); @injectIntl export default class StatusActionBar extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, onReply: PropTypes.func, onFavourite: PropTypes.func, onReblog: PropTypes.func, onDelete: PropTypes.func, onMention: PropTypes.func, onMute: PropTypes.func, onBlock: PropTypes.func, onReport: PropTypes.func, onMuteConversation: PropTypes.func, me: PropTypes.number.isRequired, withDismiss: PropTypes.bool, intl: PropTypes.object.isRequired, }; // Avoid checking props that are functions (and whose equality will always // evaluate to false. See react-immutable-pure-component for usage. updateOnProps = [ 'status', 'me', 'withDismiss', ] handleReplyClick = () => { this.props.onReply(this.props.status, this.context.router.history); } handleFavouriteClick = () => { this.props.onFavourite(this.props.status); } handleReblogClick = (e) => { this.props.onReblog(this.props.status, e); } handleDeleteClick = () => { this.props.onDelete(this.props.status); } handleMentionClick = () => { this.props.onMention(this.props.status.get('account'), this.context.router.history); } handleMuteClick = () => { this.props.onMute(this.props.status.get('account')); } handleBlockClick = () => { this.props.onBlock(this.props.status.get('account')); } handleOpen = () => { this.context.router.history.push(`/statuses/${this.props.status.get('id')}`); } handleReport = () => { this.props.onReport(this.props.status); } handleConversationMuteClick = () => { this.props.onMuteConversation(this.props.status); } render () { const { status, me, intl, withDismiss } = this.props; const reblogDisabled = status.get('visibility') === 'private' || status.get('visibility') === 'direct'; const mutingConversation = status.get('muted'); let menu = []; let reblogIcon = 'retweet'; let replyIcon; let replyTitle; menu.push({ text: intl.formatMessage(messages.open), action: this.handleOpen }); menu.push(null); if (withDismiss) { menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick }); menu.push(null); } if (status.getIn(['account', 'id']) === me) { menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick }); } else { menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick }); menu.push(null); menu.push({ text: intl.formatMessage(messages.mute, { name: status.getIn(['account', 'username']) }), action: this.handleMuteClick }); menu.push({ text: intl.formatMessage(messages.block, { name: status.getIn(['account', 'username']) }), action: this.handleBlockClick }); menu.push({ text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), action: this.handleReport }); } if (status.get('visibility') === 'direct') { reblogIcon = 'envelope'; } else if (status.get('visibility') === 'private') { reblogIcon = 'lock'; } if (status.get('in_reply_to_id', null) === null) { replyIcon = 'reply'; replyTitle = intl.formatMessage(messages.reply); } else { replyIcon = 'reply-all'; replyTitle = intl.formatMessage(messages.replyAll); } return ( <div className='status__action-bar'> <IconButton className='status__action-bar-button' title={replyTitle} icon={replyIcon} onClick={this.handleReplyClick} /> <IconButton className='status__action-bar-button' disabled={reblogDisabled} active={status.get('reblogged')} title={reblogDisabled ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)} icon={reblogIcon} onClick={this.handleReblogClick} /> <IconButton className='status__action-bar-button star-icon' animate active={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} /> <div className='status__action-bar-dropdown'> <DropdownMenu items={menu} icon='ellipsis-h' size={18} direction='right' ariaLabel='More' /> </div> </div> ); } }
Toootim/mastodon
app/javascript/mastodon/components/status_action_bar.js
JavaScript
agpl-3.0
5,791
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django import forms from django.utils.translation import ugettext_lazy as _ from shoop.admin.form_part import FormPart, TemplatedFormDef from shoop.core.models import Shop from shoop.discount_pricing.models import DiscountedProductPrice class DiscountPricingForm(forms.Form): def __init__(self, **kwargs): self.product = kwargs.pop("product") super(DiscountPricingForm, self).__init__(**kwargs) self.shops = [] if self.product: self._build_fields() def _build_fields(self): self.shops = list(Shop.objects.all()) prices_by_shop_and_group = dict( (shop_id, price) for (shop_id, price) in DiscountedProductPrice.objects.filter(product=self.product) .values_list("shop_id", "price_value") ) for shop in self.shops: name = self._get_field_name(shop) price = prices_by_shop_and_group.get(shop.id) price_field = forms.DecimalField( min_value=0, initial=price, label=_("Price (%s)") % shop, required=False ) self.fields[name] = price_field def _get_field_name(self, shop): return "s_%d" % shop.id def _process_single_save(self, shop): name = self._get_field_name(shop) value = self.cleaned_data.get(name) clear = (value is None or value < 0) if clear: DiscountedProductPrice.objects.filter(product=self.product, shop=shop).delete() else: (spp, created) = DiscountedProductPrice.objects.get_or_create( product=self.product, shop=shop, defaults={'price_value': value}) if not created: spp.price_value = value spp.save() def save(self): if not self.has_changed(): # No changes, so no need to do anything. return for shop in self.shops: self._process_single_save(shop) def get_shop_field(self, shop): name = self._get_field_name(shop) return self[name] class DiscountPricingFormPart(FormPart): priority = 10 def get_form_defs(self): yield TemplatedFormDef( name="discount_pricing", form_class=DiscountPricingForm, template_name="shoop/admin/discount_pricing/form_part.jinja", required=False, kwargs={"product": self.object} ) def form_valid(self, form): form["discount_pricing"].save()
jorge-marques/shoop
shoop/discount_pricing/admin_form_part.py
Python
agpl-3.0
2,820
/******************************************************************************* * HELIUM V, Open Source ERP software for sustained success * at small and medium-sized enterprises. * Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of theLicense, or * (at your option) any later version. * * According to sec. 7 of the GNU Affero General Public License, version 3, * the terms of the AGPL are supplemented with the following terms: * * "HELIUM V" and "HELIUM 5" are registered trademarks of * HELIUM V IT-Solutions GmbH. The licensing of the program under the * AGPL does not imply a trademark license. Therefore any rights, title and * interest in our trademarks remain entirely with us. If you want to propagate * modified versions of the Program under the name "HELIUM V" or "HELIUM 5", * you may only do so if you have a written permission by HELIUM V IT-Solutions * GmbH (to acquire a permission please contact HELIUM V IT-Solutions * at trademark@heliumv.com). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact: developers@heliumv.com ******************************************************************************/ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.12.03 at 10:12:07 AM MEZ // package com.lp.server.schema.opentrans.cc.orderresponse; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for _XML_XML_COST_CATEGORY_ID complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="_XML_XML_COST_CATEGORY_ID"> * &lt;simpleContent> * &lt;extension base="&lt;http://www.opentrans.org/XMLSchema/1.0>typeCOST_CATEGORY_ID"> * &lt;attGroup ref="{http://www.opentrans.org/XMLSchema/1.0}ComIbmMrmNamespaceInfo154"/> * &lt;attribute name="type"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"> * &lt;minLength value="1"/> * &lt;maxLength value="32"/> * &lt;enumeration value="cost_center"/> * &lt;enumeration value="project"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "_XML_XML_COST_CATEGORY_ID", propOrder = { "value" }) public class XMLXMLCOSTCATEGORYID { @XmlValue protected String value; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String type; @XmlAttribute(name = "xsi_schemaLocation") protected String xsiSchemaLocation; @XmlAttribute(name = "xmlns_xsd") protected String xmlnsXsd; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the xsiSchemaLocation property. * * @return * possible object is * {@link String } * */ public String getXsiSchemaLocation() { if (xsiSchemaLocation == null) { return "openbase_1_0.mxsd"; } else { return xsiSchemaLocation; } } /** * Sets the value of the xsiSchemaLocation property. * * @param value * allowed object is * {@link String } * */ public void setXsiSchemaLocation(String value) { this.xsiSchemaLocation = value; } /** * Gets the value of the xmlnsXsd property. * * @return * possible object is * {@link String } * */ public String getXmlnsXsd() { if (xmlnsXsd == null) { return "http://www.w3.org/2001/XMLSchema"; } else { return xmlnsXsd; } } /** * Sets the value of the xmlnsXsd property. * * @param value * allowed object is * {@link String } * */ public void setXmlnsXsd(String value) { this.xmlnsXsd = value; } }
erdincay/ejb
src/com/lp/server/schema/opentrans/cc/orderresponse/XMLXMLCOSTCATEGORYID.java
Java
agpl-3.0
5,991
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2019. (c) 2019. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * <http://www.gnu.org/licenses/>. * * ************************************************************************ */ package org.opencadc.proxy; import ca.nrc.cadc.auth.AuthMethod; import ca.nrc.cadc.reg.client.RegistryClient; import java.net.URI; import java.net.URL; import org.junit.Test; import org.junit.Assert; import static org.mockito.Mockito.*; public class ProxyServletTest { @Test public void lookupServiceURL() throws Exception { final RegistryClient mockRegistryClient = mock(RegistryClient.class); final ProxyServlet testSubject = new ProxyServlet() { /** * Useful for overriding in tests. * * @return RegistryClient instance. Never null. */ @Override RegistryClient getRegistryClient() { return mockRegistryClient; } }; final URL lookedUpServiceURL = new URL("https://www.services.com/myservice"); final ServiceParameterMap serviceParameterMap = new ServiceParameterMap(); serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource"); serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard"); serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https"); serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "cookie"); when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"), URI.create("ivo://cadc.nrc.ca/mystandard"), AuthMethod.COOKIE, URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn( lookedUpServiceURL); final URL result = testSubject.lookupServiceURL(serviceParameterMap); Assert.assertEquals("URLs do not match.", lookedUpServiceURL, result); } @Test public void lookupServiceURLWithPath() throws Exception { final RegistryClient mockRegistryClient = mock(RegistryClient.class); final ProxyServlet testSubject = new ProxyServlet() { /** * Useful for overriding in tests. * * @return RegistryClient instance. Never null. */ @Override RegistryClient getRegistryClient() { return mockRegistryClient; } }; final URL lookedUpServiceURL = new URL("https://www.services.com/myservice"); final ServiceParameterMap serviceParameterMap = new ServiceParameterMap(); serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource"); serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard"); serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https"); serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "anon"); serviceParameterMap.put(ServiceParameterName.EXTRA_PATH, "alt-site"); when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"), URI.create("ivo://cadc.nrc.ca/mystandard"), AuthMethod.ANON, URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn( lookedUpServiceURL); final URL result = testSubject.lookupServiceURL(serviceParameterMap); final URL expected = new URL("https://www.services.com/myservice/alt-site"); Assert.assertEquals("URLs do not match.", expected, result); } @Test public void lookupServiceURLWithPathQuery() throws Exception { final RegistryClient mockRegistryClient = mock(RegistryClient.class); final ProxyServlet testSubject = new ProxyServlet() { /** * Useful for overriding in tests. * * @return RegistryClient instance. Never null. */ @Override RegistryClient getRegistryClient() { return mockRegistryClient; } }; final URL lookedUpServiceURL = new URL("https://www.services.com/myservice"); final ServiceParameterMap serviceParameterMap = new ServiceParameterMap(); serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource"); serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard"); serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https"); serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "anon"); serviceParameterMap.put(ServiceParameterName.EXTRA_PATH, "alt-site"); serviceParameterMap.put(ServiceParameterName.EXTRA_QUERY, "myquery=a&g=j"); when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"), URI.create("ivo://cadc.nrc.ca/mystandard"), AuthMethod.ANON, URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn( lookedUpServiceURL); final URL result = testSubject.lookupServiceURL(serviceParameterMap); final URL expected = new URL("https://www.services.com/myservice/alt-site?myquery=a&g=j"); Assert.assertEquals("URLs do not match.", expected, result); } }
at88mph/web
cadc-web-util/src/test/java/org/opencadc/proxy/ProxyServletTest.java
Java
agpl-3.0
9,512
import ITEM_QUALITIES from '../ITEM_QUALITIES'; export default { // Shared legendaries SOUL_OF_THE_SHADOWBLADE: { id: 150936, name: 'Soul of the Shadowblade', icon: 'inv_jewelry_ring_56', quality: ITEM_QUALITIES.LEGENDARY, }, MANTLE_OF_THE_MASTER_ASSASSIN: { id: 144236, name: 'Mantle of the Master Assassin', icon: 'inv_shoulder_leather_raidrogue_k_01', quality: ITEM_QUALITIES.LEGENDARY, }, INSIGNIA_OF_RAVENHOLDT: { id: 137049, name: 'Insignia of Ravenholdt', icon: 'inv_misc_epicring_a2', quality: ITEM_QUALITIES.LEGENDARY, }, WILL_OF_VALEERA: { id: 137069, name: 'Will of Valeera', icon: 'inv_pants_cloth_02', quality: ITEM_QUALITIES.LEGENDARY, }, THE_DREADLORDS_DECEIT: { id: 137021, name: 'The Dreadlord\'s Deceit', icon: 'inv_cape_pandaria_d_03', quality: ITEM_QUALITIES.LEGENDARY, }, // Assassination legendaries DUSKWALKERS_FOOTPADS: { id: 137030, name: 'Duskwalker\'s Footpads', icon: 'inv_boots_leather_8', quality: ITEM_QUALITIES.LEGENDARY, }, ZOLDYCK_FAMILY_TRAINING_SHACKLES: { id: 137098, name: 'Zoldyck Family Training Shackles', icon: 'inv_bracer_leather_raiddruid_i_01', quality: ITEM_QUALITIES.LEGENDARY, }, THE_EMPTY_CROWN: { id: 151815, name: 'The Empty Crown', icon: 'inv_crown_02', quality: ITEM_QUALITIES.LEGENDARY, }, // Outlaw legendaries THRAXIS_TRICKSY_TREADS: { id: 137031, name: 'Thraxi\'s Tricksy Treads', icon: 'inv_boots_leather_03a', quality: ITEM_QUALITIES.LEGENDARY, }, GREENSKINS_WATERLOGGED_WRISTCUFFS: { id: 137099, name: 'Greenskin\'s Waterlogged Wristcuffs', icon: 'inv_bracer_leather_raidrogue_k_01', quality: ITEM_QUALITIES.LEGENDARY, }, SHIVARRAN_SYMMETRY: { id: 141321, name: 'Shivarran Symmetry', icon: 'inv_gauntlets_83', quality: ITEM_QUALITIES.LEGENDARY, }, THE_CURSE_OF_RESTLESSNESS: { id: 151817, name: 'The Curse of Restlessness', icon: 'inv_qiraj_draperegal', quality: ITEM_QUALITIES.LEGENDARY, }, // Subtlety legendaries SHADOW_SATYRS_WALK: { id: 137032, name: 'Shadow Satyr\'s Walk', icon: 'inv_boots_mail_dungeonmail_c_04', quality: ITEM_QUALITIES.LEGENDARY, }, DENIAL_OF_THE_HALF_GIANTS: { id: 137100, name: 'Denial of the Half-Giants', icon: 'inv_bracer_leather_panda_b_02_crimson', quality: ITEM_QUALITIES.LEGENDARY, }, THE_FIRST_OF_THE_DEAD: { id: 151818, name: 'The First of the Dead', icon: 'inv_glove_cloth_raidwarlockmythic_q_01', quality: ITEM_QUALITIES.LEGENDARY, }, };
enragednuke/WoWAnalyzer
src/common/ITEMS/ROGUE.js
JavaScript
agpl-3.0
2,649
module Merb::Maintainer::BillingHelper def get_stats(metric, dom) today = Date.today date_this_month = Date.new(today.year, today.month, dom) data = [] data_length = 30 data << get_stat(metric, date_this_month) if dom < today.mday (1..(data_length-data.length)).each do |i| date = date_this_month << i data << get_stat(metric, date) end data end # to add a new metric to the billing section, add a case below def get_stat(metric, date) case metric when "active_loans" count = repository.adapter.query(%Q{ SELECT COUNT(date) FROM loan_history lh, (SELECT max(date) AS mdt, loan_id FROM loan_history lh2 WHERE date <= '#{date.strftime}' GROUP BY loan_id) AS md WHERE lh.date = md.mdt AND lh.loan_id = md.loan_id AND lh.status IN (2,4,5,6); }).first when "total_loans" count = Loan.count(:applied_on.lte => date) when "total_clients" count = Client.count(:date_joined.lte => date) end { :date => date.strftime(DATE_FORMAT_READABLE), :count => count } end end
Mostfit/mostfit
slices/maintainer/app/helpers/billing_helper.rb
Ruby
agpl-3.0
1,102
/*************************************************************************** constraintteachersmaxgapsperdayform.cpp - description ------------------- begin : Jan 21, 2008 copyright : (C) 2008 by Lalescu Liviu email : Please see http://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address) ***************************************************************************/ /*************************************************************************** * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * ***************************************************************************/ #include <QMessageBox> #include "longtextmessagebox.h" #include "constraintteachersmaxgapsperdayform.h" #include "addconstraintteachersmaxgapsperdayform.h" #include "modifyconstraintteachersmaxgapsperdayform.h" #include <QListWidget> #include <QScrollBar> #include <QAbstractItemView> ConstraintTeachersMaxGapsPerDayForm::ConstraintTeachersMaxGapsPerDayForm(QWidget* parent): QDialog(parent) { setupUi(this); currentConstraintTextEdit->setReadOnly(true); modifyConstraintPushButton->setDefault(true); constraintsListWidget->setSelectionMode(QAbstractItemView::SingleSelection); connect(constraintsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(constraintChanged(int))); connect(addConstraintPushButton, SIGNAL(clicked()), this, SLOT(addConstraint())); connect(closePushButton, SIGNAL(clicked()), this, SLOT(close())); connect(removeConstraintPushButton, SIGNAL(clicked()), this, SLOT(removeConstraint())); connect(modifyConstraintPushButton, SIGNAL(clicked()), this, SLOT(modifyConstraint())); connect(constraintsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(modifyConstraint())); centerWidgetOnScreen(this); restoreFETDialogGeometry(this); this->filterChanged(); } ConstraintTeachersMaxGapsPerDayForm::~ConstraintTeachersMaxGapsPerDayForm() { saveFETDialogGeometry(this); } bool ConstraintTeachersMaxGapsPerDayForm::filterOk(TimeConstraint* ctr) { if(ctr->type==CONSTRAINT_TEACHERS_MAX_GAPS_PER_DAY) return true; else return false; } void ConstraintTeachersMaxGapsPerDayForm::filterChanged() { this->visibleConstraintsList.clear(); constraintsListWidget->clear(); for(int i=0; i<gt.rules.timeConstraintsList.size(); i++){ TimeConstraint* ctr=gt.rules.timeConstraintsList[i]; if(filterOk(ctr)){ visibleConstraintsList.append(ctr); constraintsListWidget->addItem(ctr->getDescription(gt.rules)); } } if(constraintsListWidget->count()>0) constraintsListWidget->setCurrentRow(0); else constraintChanged(-1); } void ConstraintTeachersMaxGapsPerDayForm::constraintChanged(int index) { if(index<0){ currentConstraintTextEdit->setPlainText(""); return; } assert(index<this->visibleConstraintsList.size()); TimeConstraint* ctr=this->visibleConstraintsList.at(index); assert(ctr!=NULL); currentConstraintTextEdit->setPlainText(ctr->getDetailedDescription(gt.rules)); } void ConstraintTeachersMaxGapsPerDayForm::addConstraint() { AddConstraintTeachersMaxGapsPerDayForm form(this); setParentAndOtherThings(&form, this); form.exec(); filterChanged(); constraintsListWidget->setCurrentRow(constraintsListWidget->count()-1); } void ConstraintTeachersMaxGapsPerDayForm::modifyConstraint() { int valv=constraintsListWidget->verticalScrollBar()->value(); int valh=constraintsListWidget->horizontalScrollBar()->value(); int i=constraintsListWidget->currentRow(); if(i<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected constraint")); return; } TimeConstraint* ctr=this->visibleConstraintsList.at(i); ModifyConstraintTeachersMaxGapsPerDayForm form(this, (ConstraintTeachersMaxGapsPerDay*)ctr); setParentAndOtherThings(&form, this); form.exec(); filterChanged(); constraintsListWidget->verticalScrollBar()->setValue(valv); constraintsListWidget->horizontalScrollBar()->setValue(valh); if(i>=constraintsListWidget->count()) i=constraintsListWidget->count()-1; if(i>=0) constraintsListWidget->setCurrentRow(i); else this->constraintChanged(-1); } void ConstraintTeachersMaxGapsPerDayForm::removeConstraint() { int i=constraintsListWidget->currentRow(); if(i<0){ QMessageBox::information(this, tr("FET information"), tr("Invalid selected constraint")); return; } TimeConstraint* ctr=this->visibleConstraintsList.at(i); QString s; s=tr("Remove constraint?"); s+="\n\n"; s+=ctr->getDetailedDescription(gt.rules); QListWidgetItem* item; switch( LongTextMessageBox::confirmation( this, tr("FET confirmation"), s, tr("Yes"), tr("No"), 0, 0, 1 ) ){ case 0: // The user clicked the OK button or pressed Enter gt.rules.removeTimeConstraint(ctr); visibleConstraintsList.removeAt(i); constraintsListWidget->setCurrentRow(-1); item=constraintsListWidget->takeItem(i); delete item; break; case 1: // The user clicked the Cancel button or pressed Escape break; } if(i>=constraintsListWidget->count()) i=constraintsListWidget->count()-1; if(i>=0) constraintsListWidget->setCurrentRow(i); else this->constraintChanged(-1); }
fet-project/fet
src/interface/constraintteachersmaxgapsperdayform.cpp
C++
agpl-3.0
5,667
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ############################################################################## import base64 import netsvc from osv import osv from osv import fields from tools.translate import _ import tools def _reopen(self, wizard_id, res_model, res_id): return {'type': 'ir.actions.act_window', 'view_mode': 'form', 'view_type': 'form', 'res_id': wizard_id, 'res_model': self._name, 'target': 'new', # save original model in context, otherwise # it will be lost on the action's context switch 'context': {'mail.compose.target.model': res_model, 'mail.compose.target.id': res_id,} } class mail_compose_message(osv.osv_memory): _inherit = 'mail.compose.message' def _get_templates(self, cr, uid, context=None): """ Return Email Template of particular Model. """ if context is None: context = {} record_ids = [] email_template= self.pool.get('email.template') model = False if context.get('message_id'): mail_message = self.pool.get('mail.message') message_data = mail_message.browse(cr, uid, int(context.get('message_id')), context) model = message_data.model elif context.get('mail.compose.target.model') or context.get('active_model'): model = context.get('mail.compose.target.model', context.get('active_model')) if model: record_ids = email_template.search(cr, uid, [('model', '=', model)]) return email_template.name_get(cr, uid, record_ids, context) + [(False,'')] return [] _columns = { 'use_template': fields.boolean('Use Template'), 'template_id': fields.selection(_get_templates, 'Template', size=-1 # means we want an int db column ), } _defaults = { 'template_id' : lambda self, cr, uid, context={} : context.get('mail.compose.template_id', False) } def on_change_template(self, cr, uid, ids, use_template, template_id, email_from=None, email_to=None, context=None): if context is None: context = {} values = {} if template_id: res_id = context.get('mail.compose.target.id') or context.get('active_id') or False if context.get('mail.compose.message.mode') == 'mass_mail': # use the original template values - to be rendered when actually sent # by super.send_mail() values = self.pool.get('email.template').read(cr, uid, template_id, self.fields_get_keys(cr, uid), context) report_xml_pool = self.pool.get('ir.actions.report.xml') template = self.pool.get('email.template').get_email_template(cr, uid, template_id, res_id, context) values['attachments'] = False attachments = {} if template.report_template: report_name = self.render_template(cr, uid, template.report_name, template.model, res_id, context=context) report_service = 'report.' + report_xml_pool.browse(cr, uid, template.report_template.id, context).report_name # Ensure report is rendered using template's language ctx = context.copy() if template.lang: ctx['lang'] = self.render_template(cr, uid, template.lang, template.model, res_id, context) service = netsvc.LocalService(report_service) (result, format) = service.create(cr, uid, [res_id], {'model': template.model}, ctx) result = base64.b64encode(result) if not report_name: report_name = report_service ext = "." + format if not report_name.endswith(ext): report_name += ext attachments[report_name] = result # Add document attachments for attach in template.attachment_ids: # keep the bytes as fetched from the db, base64 encoded attachments[attach.datas_fname] = attach.datas values['attachments'] = attachments if values['attachments']: attachment = values.pop('attachments') attachment_obj = self.pool.get('ir.attachment') att_ids = [] for fname, fcontent in attachment.iteritems(): data_attach = { 'name': fname, 'datas': fcontent, 'datas_fname': fname, 'description': fname, 'res_model' : self._name, 'res_id' : ids[0] if ids else False } att_ids.append(attachment_obj.create(cr, uid, data_attach)) values['attachment_ids'] = att_ids else: # render the mail as one-shot values = self.pool.get('email.template').generate_email(cr, uid, template_id, res_id, context=context) # retrofit generated attachments in the expected field format if values['attachments']: attachment = values.pop('attachments') attachment_obj = self.pool.get('ir.attachment') att_ids = [] for fname, fcontent in attachment.iteritems(): data_attach = { 'name': fname, 'datas': fcontent, 'datas_fname': fname, 'description': fname, 'res_model' : self._name, 'res_id' : ids[0] if ids else False } att_ids.append(attachment_obj.create(cr, uid, data_attach)) values['attachment_ids'] = att_ids else: # restore defaults values = self.default_get(cr, uid, self.fields_get_keys(cr, uid), context) values.update(use_template=use_template, template_id=template_id) return {'value': values} def template_toggle(self, cr, uid, ids, context=None): for record in self.browse(cr, uid, ids, context=context): had_template = record.use_template record.write({'use_template': not(had_template)}) if had_template: # equivalent to choosing an empty template onchange_defaults = self.on_change_template(cr, uid, record.id, not(had_template), False, email_from=record.email_from, email_to=record.email_to, context=context) record.write(onchange_defaults['value']) return _reopen(self, record.id, record.model, record.res_id) def save_as_template(self, cr, uid, ids, context=None): if context is None: context = {} email_template = self.pool.get('email.template') model_pool = self.pool.get('ir.model') for record in self.browse(cr, uid, ids, context=context): model = record.model or context.get('active_model') model_ids = model_pool.search(cr, uid, [('model', '=', model)]) model_id = model_ids and model_ids[0] or False model_name = '' if model_id: model_name = model_pool.browse(cr, uid, model_id, context=context).name template_name = "%s: %s" % (model_name, tools.ustr(record.subject)) values = { 'name': template_name, 'email_from': record.email_from or False, 'subject': record.subject or False, 'body_text': record.body_text or False, 'email_to': record.email_to or False, 'email_cc': record.email_cc or False, 'email_bcc': record.email_bcc or False, 'reply_to': record.reply_to or False, 'model_id': model_id or False, 'attachment_ids': [(6, 0, [att.id for att in record.attachment_ids])] } template_id = email_template.create(cr, uid, values, context=context) record.write({'template_id': template_id, 'use_template': True}) # _reopen same wizard screen with new template preselected return _reopen(self, record.id, model, record.res_id) # override the basic implementation def render_template(self, cr, uid, template, model, res_id, context=None): return self.pool.get('email.template').render_template(cr, uid, template, model, res_id, context=context) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
ksrajkumar/openerp-6.1
openerp/addons/email_template/wizard/mail_compose_message.py
Python
agpl-3.0
10,036
package org.osforce.connect.service.system; import org.osforce.connect.entity.system.ProjectFeature; /** * * @author gavin * @since 1.0.0 * @create Feb 12, 2011 - 9:23:35 PM * <a href="http://www.opensourceforce.org">开源力量</a> */ public interface ProjectFeatureService { ProjectFeature getProjectFeature(Long featureId); ProjectFeature getProjectFeature(String code, Long projectId); void createProjectFeature(ProjectFeature feature); void updateProjectFeature(ProjectFeature feature); void deleteProjectFeature(Long featureId); }
shook2012/focus-sns
connect-service/src/main/java/org/osforce/connect/service/system/ProjectFeatureService.java
Java
agpl-3.0
562
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "rocksdb/sst_file_writer.h" #include <vector> #include "db/dbformat.h" #include "rocksdb/table.h" #include "table/block_based_table_builder.h" #include "table/sst_file_writer_collectors.h" #include "util/file_reader_writer.h" #include "util/sync_point.h" namespace rocksdb { const std::string ExternalSstFilePropertyNames::kVersion = "rocksdb.external_sst_file.version"; const std::string ExternalSstFilePropertyNames::kGlobalSeqno = "rocksdb.external_sst_file.global_seqno"; #ifndef ROCKSDB_LITE const size_t kFadviseTrigger = 1024 * 1024; // 1MB struct SstFileWriter::Rep { Rep(const EnvOptions& _env_options, const Options& options, const Comparator* _user_comparator, ColumnFamilyHandle* _cfh, bool _invalidate_page_cache) : env_options(_env_options), ioptions(options), mutable_cf_options(options), internal_comparator(_user_comparator), cfh(_cfh), invalidate_page_cache(_invalidate_page_cache), last_fadvise_size(0) {} std::unique_ptr<WritableFileWriter> file_writer; std::unique_ptr<TableBuilder> builder; EnvOptions env_options; ImmutableCFOptions ioptions; MutableCFOptions mutable_cf_options; InternalKeyComparator internal_comparator; ExternalSstFileInfo file_info; InternalKey ikey; std::string column_family_name; ColumnFamilyHandle* cfh; // If true, We will give the OS a hint that this file pages is not needed // everytime we write 1MB to the file bool invalidate_page_cache; // the size of the file during the last time we called Fadvise to remove // cached pages from page cache. uint64_t last_fadvise_size; }; SstFileWriter::SstFileWriter(const EnvOptions& env_options, const Options& options, const Comparator* user_comparator, ColumnFamilyHandle* column_family, bool invalidate_page_cache) : rep_(new Rep(env_options, options, user_comparator, column_family, invalidate_page_cache)) { rep_->file_info.file_size = 0; } SstFileWriter::~SstFileWriter() { if (rep_->builder) { // User did not call Finish() or Finish() failed, we need to // abandon the builder. rep_->builder->Abandon(); } delete rep_; } Status SstFileWriter::Open(const std::string& file_path) { Rep* r = rep_; Status s; std::unique_ptr<WritableFile> sst_file; s = r->ioptions.env->NewWritableFile(file_path, &sst_file, r->env_options); if (!s.ok()) { return s; } CompressionType compression_type; if (r->ioptions.bottommost_compression != kDisableCompressionOption) { compression_type = r->ioptions.bottommost_compression; } else if (!r->ioptions.compression_per_level.empty()) { // Use the compression of the last level if we have per level compression compression_type = *(r->ioptions.compression_per_level.rbegin()); } else { compression_type = r->mutable_cf_options.compression; } std::vector<std::unique_ptr<IntTblPropCollectorFactory>> int_tbl_prop_collector_factories; // SstFileWriter properties collector to add SstFileWriter version. int_tbl_prop_collector_factories.emplace_back( new SstFileWriterPropertiesCollectorFactory(2 /* version */, 0 /* global_seqno*/)); // User collector factories auto user_collector_factories = r->ioptions.table_properties_collector_factories; for (size_t i = 0; i < user_collector_factories.size(); i++) { int_tbl_prop_collector_factories.emplace_back( new UserKeyTablePropertiesCollectorFactory( user_collector_factories[i])); } int unknown_level = -1; uint32_t cf_id; if (r->cfh != nullptr) { // user explicitly specified that this file will be ingested into cfh, // we can persist this information in the file. cf_id = r->cfh->GetID(); r->column_family_name = r->cfh->GetName(); } else { r->column_family_name = ""; cf_id = TablePropertiesCollectorFactory::Context::kUnknownColumnFamily; } TableBuilderOptions table_builder_options( r->ioptions, r->internal_comparator, &int_tbl_prop_collector_factories, compression_type, r->ioptions.compression_opts, nullptr /* compression_dict */, false /* skip_filters */, r->column_family_name, unknown_level); r->file_writer.reset( new WritableFileWriter(std::move(sst_file), r->env_options)); // TODO(tec) : If table_factory is using compressed block cache, we will // be adding the external sst file blocks into it, which is wasteful. r->builder.reset(r->ioptions.table_factory->NewTableBuilder( table_builder_options, cf_id, r->file_writer.get())); r->file_info.file_path = file_path; r->file_info.file_size = 0; r->file_info.num_entries = 0; r->file_info.sequence_number = 0; r->file_info.version = 2; return s; } Status SstFileWriter::Add(const Slice& user_key, const Slice& value) { Rep* r = rep_; if (!r->builder) { return Status::InvalidArgument("File is not opened"); } if (r->file_info.num_entries == 0) { r->file_info.smallest_key.assign(user_key.data(), user_key.size()); } else { if (r->internal_comparator.user_comparator()->Compare( user_key, r->file_info.largest_key) <= 0) { // Make sure that keys are added in order return Status::InvalidArgument("Keys must be added in order"); } } // TODO(tec) : For external SST files we could omit the seqno and type. r->ikey.Set(user_key, 0 /* Sequence Number */, ValueType::kTypeValue /* Put */); r->builder->Add(r->ikey.Encode(), value); // update file info r->file_info.num_entries++; r->file_info.largest_key.assign(user_key.data(), user_key.size()); r->file_info.file_size = r->builder->FileSize(); InvalidatePageCache(false /* closing */); return Status::OK(); } Status SstFileWriter::Finish(ExternalSstFileInfo* file_info) { Rep* r = rep_; if (!r->builder) { return Status::InvalidArgument("File is not opened"); } if (r->file_info.num_entries == 0) { return Status::InvalidArgument("Cannot create sst file with no entries"); } Status s = r->builder->Finish(); r->file_info.file_size = r->builder->FileSize(); if (s.ok()) { s = r->file_writer->Sync(r->ioptions.use_fsync); InvalidatePageCache(true /* closing */); if (s.ok()) { s = r->file_writer->Close(); } } if (!s.ok()) { r->ioptions.env->DeleteFile(r->file_info.file_path); } if (file_info != nullptr) { *file_info = r->file_info; } r->builder.reset(); return s; } void SstFileWriter::InvalidatePageCache(bool closing) { Rep* r = rep_; if (r->invalidate_page_cache == false) { // Fadvise disabled return; } uint64_t bytes_since_last_fadvise = r->builder->FileSize() - r->last_fadvise_size; if (bytes_since_last_fadvise > kFadviseTrigger || closing) { TEST_SYNC_POINT_CALLBACK("SstFileWriter::InvalidatePageCache", &(bytes_since_last_fadvise)); // Tell the OS that we dont need this file in page cache r->file_writer->InvalidateCache(0, 0); r->last_fadvise_size = r->builder->FileSize(); } } uint64_t SstFileWriter::FileSize() { return rep_->file_info.file_size; } #endif // !ROCKSDB_LITE } // namespace rocksdb
chain/chain
vendor/github.com/facebook/rocksdb/table/sst_file_writer.cc
C++
agpl-3.0
7,678
const LdapStrategy = require('./LdapStrategy'); const MoodleStrategy = require('./MoodleStrategy'); const IservStrategy = require('./IservStrategy'); const TSPStrategy = require('./TSPStrategy'); const ApiKeyStrategy = require('./ApiKeyStrategy'); module.exports = { LdapStrategy, MoodleStrategy, IservStrategy, TSPStrategy, ApiKeyStrategy, };
schul-cloud/schulcloud-server
src/services/authentication/strategies/index.js
JavaScript
agpl-3.0
350
/* Copyright (C) 2014-2016 Leosac This file is part of Leosac. Leosac is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leosac 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "AccessOverview.hpp" #include "core/auth/Door.hpp" #include "core/auth/Door_odb.h" #include "core/auth/User_odb.h" #include "tools/JSONUtils.hpp" #include "tools/db/DBService.hpp" using namespace Leosac; using namespace Leosac::Module; using namespace Leosac::Module::WebSockAPI; AccessOverview::AccessOverview(RequestContext ctx) : MethodHandler(ctx) { } MethodHandlerUPtr AccessOverview::create(RequestContext ctx) { return std::make_unique<AccessOverview>(ctx); } json AccessOverview::process_impl(const json &) { json rep; DBPtr db = ctx_.dbsrv->db(); odb::transaction t(db->begin()); // todo: This probably doesn't scale very well... auto doors = db->query<Auth::Door>(); // Since we'll be looping over users multiple time, we cannot use // an odb::result object. auto users_odb = db->query<Auth::User>(); // So we'll have to convert this to a vector of User, instead of // odb::result::iterator. std::vector<Auth::UserPtr> users; for (auto itr_odb(users_odb.begin()); itr_odb != users_odb.end(); ++itr_odb) users.push_back(itr_odb.load()); for (const auto &door : doors) { std::set<Auth::UserId> unique_user_ids; json door_info = {{"door_id", door.id()}, {"user_ids", json::array()}}; for (const auto &lazy_mapping : door.lazy_mapping()) { auto mapping = lazy_mapping.load(); for (const auto &user_ptr : users) { // Check the std::set in case the user is already authorized to // access the door. if (unique_user_ids.count(user_ptr->id())) { continue; } if (mapping->has_user_indirect(user_ptr)) { unique_user_ids.insert(user_ptr->id()); } } } for (const auto &id : unique_user_ids) door_info["user_ids"].push_back(id); rep.push_back(door_info); } return rep; } std::vector<ActionActionParam> AccessOverview::required_permission(const json &) const { std::vector<ActionActionParam> perm_; SecurityContext::ActionParam ap; perm_.push_back({SecurityContext::Action::ACCESS_OVERVIEW, ap}); return perm_; }
islog/leosac
src/modules/websock-api/api/AccessOverview.cpp
C++
agpl-3.0
3,045
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('schedules', '0005_auto_20171010_1722'), ] operations = [ migrations.CreateModel( name='ScheduleExperience', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('experience_type', models.PositiveSmallIntegerField(default=0, choices=[(0, b'Recurring Nudge and Upgrade Reminder'), (1, b'Course Updates')])), ('schedule', models.OneToOneField(related_name='experience', to='schedules.Schedule', on_delete=models.CASCADE)), ], ), ]
ESOedX/edx-platform
openedx/core/djangoapps/schedules/migrations/0006_scheduleexperience.py
Python
agpl-3.0
793
# -*- coding: utf-8 -*- # Copyright 2017 KMEE # Hendrix Costa <hendrix.costa@kmee.com.br> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp.addons.financial.tests.financial_test_classes import \ FinancialTestCase class ManualFinancialProcess(FinancialTestCase): def setUp(self): self.financial_model = self.env['financial.move'] super(ManualFinancialProcess, self).setUp() def test_01_check_return_views(self): """Check if view is correctly called for python code""" # test for len(financial.move) == 1 financial_move_id = self.financial_model.search([], limit=1) action = financial_move_id.action_view_financial('2receive') self.assertEqual( action.get('display_name'), 'financial.move.debt.2receive.form (in financial)') self.assertEqual( action.get('res_id'), financial_move_id.id) action = financial_move_id.action_view_financial('2pay') self.assertEqual( action.get('display_name'), 'financial.move.debt.2pay.form (in financial)') self.assertEqual( action.get('res_id'), financial_move_id.id) # test for len(financial.move) > 1 financial_move_id = self.financial_model.search([], limit=2) action = financial_move_id.action_view_financial('2pay') self.assertEqual(action.get('domain')[0][2], financial_move_id.ids) # test for len(financial.move) < 1 action = self.financial_model.action_view_financial('2pay') self.assertEqual(action.get('type'), 'ir.actions.act_window_close')
thinkopensolutions/l10n-brazil
financial/tests/test_financial_move.py
Python
agpl-3.0
1,651
# Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application RailsFrance::Application.initialize!
nicolasleger/railsfrance.org
config/environment.rb
Ruby
agpl-3.0
155
package functionaltests.job; import java.io.Serializable; import org.ow2.proactive.scheduler.common.Scheduler; import org.ow2.proactive.scheduler.common.job.JobId; import org.ow2.proactive.scheduler.common.job.JobState; import org.ow2.proactive.scheduler.common.job.TaskFlowJob; import org.ow2.proactive.scheduler.common.task.JavaTask; import org.ow2.proactive.scheduler.common.task.TaskResult; import org.ow2.proactive.scheduler.common.task.TaskStatus; import org.ow2.proactive.scheduler.common.task.executable.JavaExecutable; import org.junit.Test; import functionaltests.utils.SchedulerFunctionalTest; import static org.junit.Assert.*; /** * Test provokes scenario when task gets 'NOT_RESTARTED' status: * - task is submitted and starts execution * - user requests to restart task with some delay * - before task was restarted job is killed * */ public class TestTaskNotRestarted extends SchedulerFunctionalTest { public static class TestJavaTask extends JavaExecutable { @Override public Serializable execute(TaskResult... results) throws Throwable { Thread.sleep(Long.MAX_VALUE); return "OK"; } } @Test public void test() throws Exception { Scheduler scheduler = schedulerHelper.getSchedulerInterface(); JobId jobId = scheduler.submit(createJob()); JobState jobState; schedulerHelper.waitForEventTaskRunning(jobId, "task1"); jobState = scheduler.getJobState(jobId); assertEquals(1, jobState.getTasks().size()); assertEquals(TaskStatus.RUNNING, jobState.getTasks().get(0).getStatus()); scheduler.restartTask(jobId, "task1", Integer.MAX_VALUE); jobState = scheduler.getJobState(jobId); assertEquals(1, jobState.getTasks().size()); assertEquals(TaskStatus.WAITING_ON_ERROR, jobState.getTasks().get(0).getStatus()); scheduler.killJob(jobId); jobState = scheduler.getJobState(jobId); assertEquals(1, jobState.getTasks().size()); assertEquals(TaskStatus.NOT_RESTARTED, jobState.getTasks().get(0).getStatus()); } private TaskFlowJob createJob() throws Exception { TaskFlowJob job = new TaskFlowJob(); job.setName(this.getClass().getSimpleName()); JavaTask javaTask = new JavaTask(); javaTask.setExecutableClassName(TestJavaTask.class.getName()); javaTask.setName("task1"); javaTask.setMaxNumberOfExecution(10); job.addTask(javaTask); return job; } }
sandrineBeauche/scheduling
scheduler/scheduler-server/src/test/java/functionaltests/job/TestTaskNotRestarted.java
Java
agpl-3.0
2,532
/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.io.File; /** * This file isn't long for this world. It's just something I've been using * to debug multi-process rejoin stuff. * */ public class VLog { static File m_logfile = new File("vlog.txt"); public synchronized static void setPortNo(int portNo) { m_logfile = new File(String.format("vlog-%d.txt", portNo)); } public synchronized static void log(String str) { // turn off this stupid thing for now /*try { FileWriter log = new FileWriter(m_logfile, true); log.write(str + "\n"); log.flush(); log.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } public static void log(String format, Object... args) { log(String.format(format, args)); } }
migue/voltdb
src/frontend/org/voltdb/VLog.java
Java
agpl-3.0
1,623
// Generated by CoffeeScript 1.10.0 var api, baseOVHKonnector, connector, name, slug; baseOVHKonnector = require('../lib/base_ovh_konnector'); name = 'Kimsufi EU'; slug = 'kimsufi_eu'; api = { endpoint: 'kimsufi-eu', appKey: '', appSecret: '' }; connector = module.exports = baseOVHKonnector.createNew(api, name, slug);
frankrousseau/konnectors
build/server/konnectors/kimsufi_eu.js
JavaScript
agpl-3.0
331
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // // Copyright (C) 2006-2022 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== package com.kaltura.client.enums; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ public enum BeaconIndexType implements EnumAsString { LOG("Log"), STATE("State"); private String value; BeaconIndexType(String value) { this.value = value; } @Override public String getValue() { return this.value; } public void setValue(String value) { this.value = value; } public static BeaconIndexType get(String value) { if(value == null) { return null; } // goes over BeaconIndexType defined values and compare the inner value with the given one: for(BeaconIndexType item: values()) { if(item.getValue().equals(value)) { return item; } } // in case the requested value was not found in the enum values, we return the first item as default. return BeaconIndexType.values().length > 0 ? BeaconIndexType.values()[0]: null; } }
kaltura/KalturaGeneratedAPIClientsJava
src/main/java/com/kaltura/client/enums/BeaconIndexType.java
Java
agpl-3.0
2,312
/* Taken from a very informative blogpost by Eldar Djafarov: * http://eldar.djafarov.com/2013/11/reactjs-mixing-with-backbone/ */ (function() { 'use strict'; module.exports = { /* Forces an update when the underlying Backbone model instance has * changed. Users will have to implement getBackboneModels(). * Also requires that React is loaded with addons. */ __syncedModels: [], componentDidMount: function() { // Whenever there may be a change in the Backbone data, trigger a reconcile. this.getBackboneModels().forEach(this.injectModel, this); }, componentWillUnmount: function() { // Ensure that we clean up any dangling references when the component is // destroyed. this.__syncedModels.forEach(function(model) { model.off(null, model.__updater, this); }, this); }, injectModel: function(model){ if(!~this.__syncedModels.indexOf(model)){ var updater = function() { try { this.forceUpdate(); } catch(e) { // This means the component is already being updated somewhere // else, so we just silently go on with our business. // This is most likely due to some AJAX callback that already // updated the model at the same time or slightly earlier. } }.bind(this, null); model.__updater = updater; model.on('add change remove', updater, this); } }, bindTo: function(model, key){ /* Allows for two-way databinding for Backbone models. * Use by passing it as a 'valueLink' property, e.g.: * valueLink={this.bindTo(model, attribute)} */ return { value: model.get(key), requestChange: function(value){ model.set(key, value); }.bind(this) }; } }; })();
jbaiter/spreads
spreadsplug/web/client/lib/backbonemixin.js
JavaScript
agpl-3.0
1,858
<? // The source code packaged with this file is Free Software, Copyright (C) 2005 by // Ricardo Galli <gallir at uib dot es>. // It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise. // You can get copies of the licenses here: // http://www.affero.org/oagpl.html // AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING". function send_recover_mail ($user) { global $site_key, $globals; require_once(mnminclude.'user.php'); $now = time(); $key = md5($user->id.$user->pass.$now.$site_key.get_server_name()); $url = 'http://'.get_server_name().$globals['base_url'].'profile.php?login='.$user->username.'&t='.$now.'&k='.$key; //echo "$user->username, $user->email, $url<br />"; $to = $user->email; $subject = _('Recuperación o verificación de la contraseña de '). get_server_name(); $message = $to . _(': para poder acceder sin la clave, conéctate a la siguiente dirección en menos de dos horas:') . "\n\n$url\n\n"; $message .= _('Pasado este tiempo puedes volver a solicitar acceso en: ') . "\nhttp://".get_server_name().$globals['base_url']."login.php?op=recover\n\n"; $message .= _('Una vez en tu perfil, puedes cambiar la clave de acceso.') . "\n" . "\n"; $message .= "\n\n". _('Este mensaje ha sido enviado a solicitud de la dirección: ') . $globals['user_ip'] . "\n\n"; $message .= "-- \n " . _('el equipo de menéame'); $message = wordwrap($message, 70); $headers = 'Content-Type: text/plain; charset="utf-8"'."\n" . 'X-Mailer: meneame.net/PHP/' . phpversion(). "\n". 'From: meneame.net <web@'.get_server_name().">\n"; //$pars = '-fweb@'.get_server_name(); mail($to, $subject, $message, $headers); echo '<p><strong>' ._ ('Correo enviado, mira tu buzón, allí están las instrucciones. Mira también en la carpeta de spam.') . '</strong></p>'; return true; } ?>
brainsqueezer/fffff
branches/version2/www/libs/mail.php
PHP
agpl-3.0
1,852
<?php class BAInitiativeParser extends RISParser { private static $MAX_OFFSET = 5500; private static $MAX_OFFSET_UPDATE = 200; public function parse($antrag_id) { $antrag_id = IntVal($antrag_id); if (SITE_CALL_MODE != "cron") echo "- Initiative $antrag_id\n"; if ($antrag_id == 0) { RISTools::report_ris_parser_error("Fehler BAInitiativeParser", "Initiative-ID 0\n" . print_r(debug_backtrace(), true)); return; } $html_details = RISTools::load_file(RIS_BA_BASE_URL . "ba_initiativen_details.jsp?Id=$antrag_id"); $html_dokumente = RISTools::load_file(RIS_BA_BASE_URL . "ba_initiativen_dokumente.jsp?Id=$antrag_id"); //$html_ergebnisse = load_file(RIS_BA_BASE_URL . "/RII/RII/ris_antrag_ergebnisse.jsp?risid=" . $antrag_id); $daten = new Antrag(); $daten->id = $antrag_id; $daten->datum_letzte_aenderung = new CDbExpression('NOW()'); $daten->typ = Antrag::$TYP_BA_INITIATIVE; $dokumente = []; //$ergebnisse = array(); preg_match("/<h3.*>.* +(.*)<\/h3/siU", $html_details, $matches); if (count($matches) == 2) $daten->antrags_nr = Antrag::cleanAntragNr($matches[1]);; $dat_details = explode("<h3 class=\"introheadline\">BA-Initiativen-Nummer", $html_details); $dat_details = explode("<div class=\"formularcontainer\">", $dat_details[1]); preg_match_all("/class=\"detail_row\">.*detail_label\">(.*)<\/d.*detail_div\">(.*)<\/div/siU", $dat_details[0], $matches); $betreff_gefunden = false; for ($i = 0; $i < count($matches[1]); $i++) switch (trim($matches[1][$i])) { case "Betreff:": $betreff_gefunden = true; $daten->betreff = html_entity_decode($this->text_simple_clean($matches[2][$i]), ENT_COMPAT, "UTF-8"); break; case "Status:": $daten->status = $this->text_simple_clean($matches[2][$i]); break; case "Bearbeitung:": $daten->bearbeitung = trim(strip_tags($matches[2][$i])); break; } if (!$betreff_gefunden) { RISTools::report_ris_parser_error("Fehler BAInitiativeParser", "Kein Betreff\n" . $html_details); throw new Exception("Betreff nicht gefunden"); } $dat_details = explode("<div class=\"detailborder\">", $html_details); $dat_details = explode("<!-- seitenfuss -->", $dat_details[1]); preg_match_all("/<span class=\"itext\">(.*)<\/span.*detail_div_(left|right|left_long)\">(.*)<\/div/siU", $dat_details[0], $matches); for ($i = 0; $i < count($matches[1]); $i++) if ($matches[3][$i] != "&nbsp;") switch ($matches[1][$i]) { case "Zust&auml;ndiges Referat:": $daten->referat = $matches[3][$i]; break; case "Gestellt am:": $daten->gestellt_am = $this->date_de2mysql($matches[3][$i]); break; case "Wahlperiode:": $daten->wahlperiode = $matches[3][$i]; break; case "Bearbeitungsfrist:": $daten->bearbeitungsfrist = $this->date_de2mysql($matches[3][$i]); break; case "Registriert am:": $daten->registriert_am = $this->date_de2mysql($matches[3][$i]); break; case "Bezirksausschuss:": $daten->ba_nr = IntVal($matches[3][$i]); break; case "Typ:": $daten->antrag_typ = strip_tags($matches[3][$i]); break; case "TO aufgenommen am:": $daten->initiative_to_aufgenommen = $this->date_de2mysql($matches[3][$i]); break; } if ($daten->wahlperiode == "") $daten->wahlperiode = "?"; preg_match_all("/<li><span class=\"iconcontainer\">.*title=\"([^\"]+)\"[^>]+href=\"(.*)\".*>(.*)<\/a>/siU", $html_dokumente, $matches); for ($i = 0; $i < count($matches[1]); $i++) { $dokumente[] = [ "url" => $matches[2][$i], "name" => $matches[3][$i], "name_title" => $matches[1][$i], ]; } /* $dat_ergebnisse = explode("<!-- tabellenkopf -->", $html_ergebnisse); $dat_ergebnisse = explode("<!-- tabellenfuss -->", $dat_ergebnisse[1]); preg_match_all("<tr>.*bghell tdborder\"><a.*\">(.*)<\/a>.* */ if ($daten->ba_nr == 0) { echo "BA-Initiative $antrag_id: " . "Keine BA-Angabe"; $GLOBALS["RIS_PARSE_ERROR_LOG"][] = "Keine BA-Angabe (Initiative): $antrag_id"; return; } $aenderungen = ""; /** @var Antrag $alter_eintrag */ $alter_eintrag = Antrag::model()->findByPk($antrag_id); $changed = true; if ($alter_eintrag) { $changed = false; if ($alter_eintrag->betreff != $daten->betreff) $aenderungen .= "Betreff: " . $alter_eintrag->betreff . " => " . $daten->betreff . "\n"; if ($alter_eintrag->bearbeitungsfrist != $daten->bearbeitungsfrist) $aenderungen .= "Bearbeitungsfrist: " . $alter_eintrag->bearbeitungsfrist . " => " . $daten->bearbeitungsfrist . "\n"; if ($alter_eintrag->status != $daten->status) $aenderungen .= "Status: " . $alter_eintrag->status . " => " . $daten->status . "\n"; if ($alter_eintrag->fristverlaengerung != $daten->fristverlaengerung) $aenderungen .= "Fristverlängerung: " . $alter_eintrag->fristverlaengerung . " => " . $daten->fristverlaengerung . "\n"; if ($alter_eintrag->initiative_to_aufgenommen != $daten->initiative_to_aufgenommen) $aenderungen .= "In TO Aufgenommen: " . $alter_eintrag->initiative_to_aufgenommen . " => " . $daten->initiative_to_aufgenommen . "\n"; if ($aenderungen != "") $changed = true; if ($alter_eintrag->wahlperiode == "") $alter_eintrag->wahlperiode = "?"; } if ($changed) { if ($aenderungen == "") $aenderungen = "Neu angelegt\n"; echo "BA-Initiative $antrag_id: Verändert: " . $aenderungen . "\n"; if ($alter_eintrag) { $alter_eintrag->copyToHistory(); $alter_eintrag->setAttributes($daten->getAttributes()); if (!$alter_eintrag->save()) { var_dump($alter_eintrag->getErrors()); die("Fehler"); } $daten = $alter_eintrag; } else { if (!$daten->save()) { var_dump($daten->getErrors()); die("Fehler"); } } $daten->resetPersonen(); } foreach ($dokumente as $dok) { $aenderungen .= Dokument::create_if_necessary(Dokument::$TYP_BA_INITIATIVE, $daten, $dok); } if ($aenderungen != "") { $aend = new RISAenderung(); $aend->ris_id = $daten->id; $aend->ba_nr = $daten->ba_nr; $aend->typ = RISAenderung::$TYP_BA_INITIATIVE; $aend->datum = new CDbExpression("NOW()"); $aend->aenderungen = $aenderungen; $aend->save(); /** @var Antrag $antrag */ $antrag = Antrag::model()->findByPk($antrag_id); $antrag->datum_letzte_aenderung = new CDbExpression('NOW()'); // Auch bei neuen Dokumenten $antrag->save(); $antrag->rebuildVorgaenge(); } } public function parseSeite($seite, $first) { if (SITE_CALL_MODE != "cron") echo "BA-Initiativen Seite $seite\n"; $text = RISTools::load_file(RIS_BA_BASE_URL . "ba_initiativen.jsp?Trf=n&Start=$seite"); $txt = explode("<!-- tabellenkopf -->", $text); $txt = explode("<div class=\"ergebnisfuss\">", $txt[1]); preg_match_all("/ba_initiativen_details\.jsp\?Id=([0-9]+)[\"'& ]/siU", $txt[0], $matches); if ($first && count($matches[1]) > 0) RISTools::report_ris_parser_error("BA-Initiativen VOLL", "Erste Seite voll: $seite"); for ($i = count($matches[1]) - 1; $i >= 0; $i--) try { $this->parse($matches[1][$i]); } catch (Exception $e) { echo " EXCEPTION! " . $e . "\n"; } return $matches[1]; } public function parseAlle() { $anz = static::$MAX_OFFSET; $first = true; for ($i = $anz; $i >= 0; $i -= 10) { if (SITE_CALL_MODE != "cron") echo ($anz - $i) . " / $anz\n"; $this->parseSeite($i, $first); $first = false; } } public function parseUpdate() { echo "Updates: BA-Initiativen\n"; $loaded_ids = []; $anz = static::$MAX_OFFSET_UPDATE; for ($i = $anz; $i >= 0; $i -= 10) { $ids = $this->parseSeite($i, false); $loaded_ids = array_merge($loaded_ids, array_map("IntVal", $ids)); } } public function parseQuickUpdate() { } }
codeformunich/Muenchen-Transparent
protected/RISParser/BAInitiativeParser.php
PHP
agpl-3.0
9,264
# # Copyright (C) 2019 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas 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 Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. # require "spec_helper" describe Messages::AssignmentSubmitted::TwitterPresenter do let(:course) { course_model(name: "MATH-101") } let(:assignment) { course.assignments.create!(name: "Introductions", due_at: 1.day.ago) } let(:teacher) { course_with_teacher(course: course, active_all: true).user } let(:student) do course_with_user("StudentEnrollment", course: course, name: "Adam Jones", active_all: true).user end let(:submission) do @submission = assignment.submit_homework(student) assignment.grade_student(student, grade: 5, grader: teacher) @submission.reload end before :once do PostPolicy.enable_feature! end describe "Presenter instance" do let(:message) { Message.new(context: submission, user: teacher) } let(:presenter) { Messages::AssignmentSubmitted::TwitterPresenter.new(message) } context "when the assignment is not anonymously graded" do it "#body includes the name of the student" do expect(presenter.body).to include("Adam Jones") end it "#link is a url for the submission" do expect(presenter.link).to eql( message.course_assignment_submission_url(course, assignment, submission.user_id) ) end end context "when the assignment is anonymously graded" do before(:each) do assignment.update!(anonymous_grading: true) end context "when grades have not been posted" do it "#body excludes the name of the student" do expect(presenter.body).not_to include("Adam Jones") end it "#link is a url to SpeedGrader" do expect(presenter.link).to eq( message.speed_grader_course_gradebook_url(course, assignment_id: assignment.id, anonymous_id: submission.anonymous_id) ) end end context "when grades have been posted" do before(:each) do submission assignment.unmute! end it "#body includes the name of the student" do expect(presenter.body).to include("Adam Jones") end it "#link is a url for the submission" do expect(presenter.link).to eql( message.course_assignment_submission_url(course, assignment, submission.user_id) ) end end end end describe "generated message" do let(:message) { generate_message(:assignment_submitted, :twitter, submission, {}) } let(:presenter) do msg = Message.new(context: submission, user: teacher) Messages::AssignmentSubmitted::TwitterPresenter.new(msg) end context "when the assignment is not anonymously graded" do it "#body includes the name of the student" do expect(message.body).to include("Adam Jones") end it "#url is a url for the submission" do expect(message.url).to include(presenter.link) end end context "when the assignment is anonymously graded" do before(:each) do assignment.update!(anonymous_grading: true) end context "when grades have not been posted" do it "#body excludes the name of the student" do expect(message.body).not_to include("Adam Jones") end it "#url is a url to SpeedGrader" do expect(message.url).to include(presenter.link) end end context "when grades have been posted" do before(:each) do submission assignment.unmute! end it "#body includes the name of the student" do expect(message.body).to include("Adam Jones") end it "#url is a url for the submission" do expect(message.url).to include(presenter.link) end end end end end
djbender/canvas-lms
spec/models/messages/assignment_submitted/twitter_presenter_spec.rb
Ruby
agpl-3.0
4,430
# # Copyright (C) 2015 - present Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas 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 Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. require 'spec_helper' require_dependency "users/creation_notify_policy" module Users describe CreationNotifyPolicy do describe "#is_self_registration?" do it "is true when forced" do policy = CreationNotifyPolicy.new(false, {force_self_registration: '1'}) expect(policy.is_self_registration?).to be(true) end it "is opposite the management ability provide" do policy = CreationNotifyPolicy.new(false, {}) expect(policy.is_self_registration?).to be(true) policy = CreationNotifyPolicy.new(true, {}) expect(policy.is_self_registration?).to be(false) end end describe "#dispatch!" do let(:user){ double() } let(:pseudonym) { double() } let(:channel){ double() } context "for self_registration" do let(:policy){ CreationNotifyPolicy.new(true, {force_self_registration: true}) } before{ allow(channel).to receive_messages(has_merge_candidates?: false) } it "sends confirmation notification" do allow(user).to receive_messages(pre_registered?: true) expect(pseudonym).to receive(:send_confirmation!) result = policy.dispatch!(user, pseudonym, channel) expect(result).to be(true) end it "sends the registration notification if the user is pending or registered" do allow(user).to receive_messages(pre_registered?: false, registered?: false) expect(pseudonym).to receive(:send_registration_notification!) result = policy.dispatch!(user, pseudonym, channel) expect(result).to be(true) end end context "when the user isn't yet registered" do before do allow(user).to receive_messages(registered?: false) allow(channel).to receive_messages(has_merge_candidates?: false) end it "sends the registration notification if should notify" do policy = CreationNotifyPolicy.new(true, {send_confirmation: '1'}) expect(pseudonym).to receive(:send_registration_notification!) result = policy.dispatch!(user, pseudonym, channel) expect(result).to be(true) end it "doesnt send the registration notification if shouldnt notify" do policy = CreationNotifyPolicy.new(true, {send_confirmation: '0'}) expect(pseudonym).to receive(:send_registration_notification!).never result = policy.dispatch!(user, pseudonym, channel) expect(result).to be(false) end end context "when the user is registered" do before{ allow(user).to receive_messages(registered?: true) } let(:policy){ CreationNotifyPolicy.new(true, {}) } it "sends the merge notification if there are merge candidates" do allow(channel).to receive_messages(has_merge_candidates?: true) expect(channel).to receive(:send_merge_notification!) result = policy.dispatch!(user, pseudonym, channel) expect(result).to be(false) end it "does nothing without merge candidates" do allow(channel).to receive_messages(has_merge_candidates?: false) expect(channel).to receive(:send_merge_notification!).never result = policy.dispatch!(user, pseudonym, channel) expect(result).to be(false) end end end end end
venturehive/canvas-lms
spec/models/users/creation_notify_policy_spec.rb
Ruby
agpl-3.0
4,064
<? session_start(); // Modificado Junio 2009 /** * Original en la SSPD en el año 2003 * * Se añadio compatibilidad con variables globales en Off * @autor Jairo Losada 2009-05 * @licencia GNU/GPL */ foreach ($_GET as $key => $valor) ${$key} = $valor; foreach ($_POST as $key => $valor) ${$key} = $valor; define('ADODB_ASSOC_CASE', 1); $krd = $_SESSION["krd"]; $dependencia = $_SESSION["dependencia"]; $usua_doc = $_SESSION["usua_doc"]; $codusuario = $_SESSION["codusuario"]; $tip3Nombre=$_SESSION["tip3Nombre"]; $tip3desc = $_SESSION["tip3desc"]; $tip3img =$_SESSION["tip3img"]; $verrad = ""; $ruta_raiz = ".."; /*************************************************************************************/ /* ORFEO GPL:Sistema de Gestion Documental http://www.orfeogpl.org */ /* Idea Original de la SUPERINTENDENCIA DE SERVICIOS PUBLICOS DOMICILIARIOS */ /* COLOMBIA TEL. (57) (1) 6913005 orfeogpl@gmail.com */ /* =========================== */ /* */ /* Este programa es software libre. usted puede redistribuirlo y/o modificarlo */ /* bajo los terminos de la licencia GNU General Public publicada por */ /* la "Free Software Foundation"; Licencia version 2. */ /* */ /* Copyright (c) 2005 por : */ /* SSPS "Superintendencia de Servicios Publicos Domiciliarios" */ /* Jairo Hernan Losada jlosada@gmail.com Desarrollador */ /* Sixto Angel Pinz�n L�pez --- angel.pinzon@gmail.com Desarrollador */ /* C.R.A. "COMISION DE REGULACION DE AGUAS Y SANEAMIENTO AMBIENTAL" */ /* Liliana Gomez lgomezv@gmail.com Desarrolladora */ /* Lucia Ojeda lojedaster@gmail.com Desarrolladora */ /* D.N.P. "Departamento Nacional de Planeaci�n" */ /* Hollman Ladino hladino@gmail.com Desarrollador */ /* */ /* Colocar desde esta lInea las Modificaciones Realizadas Luego de la Version 3.5 */ /* Nombre Desarrollador Correo Fecha Modificacion */ /*************************************************************************************/ $ruta_raiz = ".."; $verrad = ""; include_once "$ruta_raiz/include/db/ConnectionHandler.php"; $db = new ConnectionHandler($ruta_raiz); if(!$tipo_archivo) $tipo_archivo = 0; //Para la consulta a archivados /********************************************************************************* * Filename: prestamo.php * Modificado: * 1/3/2006 IIAC Basado en pedido.php. Facilita la b�squeda de los * registros de pr�stamo. *********************************************************************************/ //=============================== // prestamo begin //=============================== // Inicializa, oculta o presenta los par�metros de b�squeda dependiendo de la opci�n del men� de pr�stamos seleccionada // prestamo CustomIncludes begin include ("common.php"); // Save Page and File Name available into variables $sFileName = "prestamo.php"; // Variables de control $opcionMenu=strip($_POST["opcionMenu"]); //opci�n seleccionada del men� $pageAnt=strip($_POST["sFileName"]); $ver=$_POST["s_sql"]; //consulta // HTML Page layout ?> <html> <head> <title>Prestamos ORFEO</title> <link rel="stylesheet" href="<?=$ruta_raiz?>/estilos/orfeo.css" type="text/css"> <!--Necesario para hacer visible el calendario --> <script src="<?=$ruta_raiz?>/js/popcalendar.js"></script> <div id="spiffycalendar" class="text"></div> <link rel="stylesheet" type="text/css" href="<?=$ruta_raiz?>/js/spiffyCal/spiffyCal_v2_1.css"> </head> <body class="PageBODY"> <div align="center"> <table> <tr> <td valign="top"><?php Search_Show(); ?></td> </tr> </table> <table> <tr> <td valign="top"><?php if($ver=="") Pedidos_Show(); ?></td> </tr> </table> </div> </body> </html> <?php //=============================== // prestamo end //=============================== //=============================== // Search_Show begin //=============================== function Search_Show(){ // De sesi�n global $db; global $ruta_raiz; // Control de visualizaci�n $sFileName = $_POST["sFileName"]; $opcionMenu = $_POST["opcionMenu"]; // Valores $fechaFinal = $_POST["fechaFinal"]; $fechaInicial = $_POST["fechaInicial"]; foreach ($_GET as $key => $valor) ${$key} = $valor; foreach ($_POST as $key => $valor) ${$key} = $valor; $krd = $_SESSION["krd"]; $dependencia = $_SESSION["dependencia"]; $usua_doc = $_SESSION["usua_doc"]; // Inicializaci�n de la fecha a partir de la cual se cancelan las solicitudes if ($fechaInicial=="") { $hastaXDias=strtotime("-30 day"); $fechaInicial=date("Y-m-d",$hastaXDias); } if ($fechaFinal=="") { if ($opcionMenu==3) { $query="select PARAM_VALOR,PARAM_NOMB from SGD_PARAMETRO where PARAM_NOMB='PRESTAMO_DIAS_CANC'"; $rs = $db->conn->query($query); if(!$rs->EOF) { $x = $rs->fields("PARAM_VALOR"); // d�as por defecto $haceXDias = strtotime("-".$x." day"); $fechaFinal=date("Y-m-d",$haceXDias); } if ($pageAnt!=$sFileName) { // inicializaci�n del tiempo $v_hora_limite=date("h"); $v_minuto_limite=date("i"); $v_meridiano=date("A"); } } else{ $fechaFinal=date("Y-m-d"); } } // Set variables with search parameters $flds_PRES_ESTADO =strip($_POST["s_PRES_ESTADO"]); $flds_RADI_NUME_RADI=strip($_POST["s_RADI_NUME_RADI"]); $flds_USUA_LOGIN =strip($_POST["s_USUA_LOGIN"]); if ($opcionMenu==4) { $flds_USUA_LOGIN=$krd; } // Inicializa el usuario para el caso en que el ingresa por la opci�n de SOLICITADOS $flds_DEPE_NOMB =strip($_POST["s_DEPE_NOMB"]); $flds_USUA_NOMB =strip($_POST["s_USUA_NOMB"]); $flds_PRES_REQUERIMIENTO=strip($_POST["s_PRES_REQUERIMIENTO"]); if ($v_hora_limite=="") { $v_hora_limite =strip($_POST["s_hora_limite"]); } if ($v_minuto_limite==""){ $v_minuto_limite=strip($_POST["s_minuto_limite"]); } if ($v_meridiano=="") { $v_meridiano =strip($_POST["s_meridiano"]); } // Inicializa el titulo y la visibilidad de los criterios de b�squeda include_once "inicializarForm.inc"; // Form display ?> <form method="post" action="prestamo.php" name="busqueda"> <!-- de sesi�n !--> <input type="hidden" value=" " name="radicado"> <input type="hidden" value="" name="s_sql"> <!-- control de visualizaci�n !--> <input type="hidden" name="opcionMenu" value="<?= $opcionMenu ?>"> <input type="hidden" name="sFileName" value=""> <!-- orden de presentaci�n del resultado !--> <input type="hidden" name="FormPedidos_Sorting" value="1"> <input type="hidden" name="FormPedidos_Sorted" value="0"> <input type="hidden" name="s_Direction" value=" DESC "> <!-- control de paginaci�n !--> <input type="hidden" name="FormPedidos_Page" value="1"> <input type="hidden" name="FormStarPage" value="1"> <input type="hidden" name="FormSiguiente" value="0"> <script> //Inicializa el formulario function limpiar() { document.busqueda.action="menu_prestamo.php"; document.busqueda.submit(); } //Presenta los usuarios segun la dependencia seleccionada var codUsuaSel="<?=$flds_USUA_NOMB?>"; </script> <!--Calendario--> <script language="JavaScript" src="<?=$ruta_raiz?>/js/spiffyCal/spiffyCal_v2_1.js"></script> <script language="javascript"> setRutaRaiz ('<?=$ruta_raiz?>'); </script> <table border=0 cellpadding=0 cellspacing=2 class='borde_tab'> <tr> <td class="titulos4" colspan="2"><a name="Search"><?=$sFormTitle[$opcionMenu]; ?> </a></td> </tr> <tr id="b0" style="display:<?= $tipoBusqueda[$opcionMenu][0]; ?>"> <td class="titulos3"><p align="left">Radicado</p></td> <td class="listado5"><input type="text" name="s_RADI_NUME_RADI" maxlength="15" value="<?= $flds_RADI_NUME_RADI; ?>" size="25" class="tex_area"></td> </tr> <tr id="b1" style="display:<?= $tipoBusqueda[$opcionMenu][1]; ?>"> <td class="titulos3"><p align="left">Login de Usuario</p></td> <td class="listado5"><input type="text" name="s_USUA_LOGIN" maxlength="15" value="<?= $flds_USUA_LOGIN; ?>" size="25" class="tex_area"></td> </tr> <tr id="b2" style="display:<?= $tipoBusqueda[$opcionMenu][2]; ?>"> <td class="titulos3"><p align="left">Dependencia</p></td> <td class="listado5"><select name="s_DEPE_NOMB" class="select" onChange=" document.busqueda.s_sql.value='no'; document.busqueda.submit(); "> <option value="">- TODAS LAS DEPENDENCIAS -</option> <? $lookup_s = db_fill_array("select DEPE_CODI,DEPE_NOMB from DEPENDENCIA order by 2"); if(is_array($lookup_s)) { reset($lookup_s); while(list($key,$value)=each($lookup_s)) { if($key == $flds_DEPE_NOMB) { $option="SELECTED"; } else { $option=""; } echo "<option $option value=\"$key\">".strtoupper($value)."</option>"; } } ?> </select></td> </tr> <tr id="b3" style="display:<?= $tipoBusqueda[$opcionMenu][3]; ?>"> <td class="titulos3"><p align="left">Usuario</p></td> <td class="listado5"><select name="s_USUA_NOMB" class=select> <option value="">- TODOS LOS USUARIOS -</option> <? $validUsuaActiv=""; // Modificado Infom�trika 14-Julio-2009 // Compatibilidad con PostgreSQL 8.3 // Cambi� USUA_ESTA=1 por USUA_ESTA='1' para listar los usuarios activos. if ($opcionMenu==1) { $validUsuaActiv=" USUA_ESTA='1' "; }ELSE { $validUsuaActiv=" USUA_LOGIN IS NOT NULL "; } //Verifica que el usuario se encuentre activo para hacer el prEstamo if ($flds_DEPE_NOMB != "") $tmp = " AND DEPE_CODI= ".$flds_DEPE_NOMB; else $tmp = ""; $lookup_s = db_fill_array("select USUA_LOGIN,USUA_NOMB from USUARIO where ".$validUsuaActiv.$tmp); if(is_array($lookup_s)) { reset($lookup_s); while(list($key,$value)=each($lookup_s)) { if($key == $flds_USUA_NOMB) { $option="SELECTED"; } else { $option=""; } echo "<option $option value=\"$key\">".strtoupper($value)."</option>"; } } ?> </select></td> </tr> <tr id="b4" style="display:<?= $tipoBusqueda[$opcionMenu][4]; ?>"> <td class="titulos3"><p align="left">Requerimiento</p></td> <td class="listado5"><select name="s_PRES_REQUERIMIENTO" class=select> <option value="">- TODOS LOS TIPOS -</option> <? $lookup_s = db_fill_array("select PARAM_CODI,PARAM_VALOR from SGD_PARAMETRO where PARAM_NOMB='PRESTAMO_REQUERIMIENTO' order by PARAM_VALOR desc"); if(is_array($lookup_s)) { reset($lookup_s); while(list($key,$value)=each($lookup_s)) { if($key == $flds_PRES_REQUERIMIENTO) $option="<option SELECTED value=\"$key\">".strtoupper($value)."</option>"; else $option="<option value=\"$key\">".strtoupper($value)."</option>"; echo $option; } } ?> </select></td> </tr> <tr id="b5" style="display:<?= $tipoBusqueda[$opcionMenu][5]; ?>"> <td class="titulos3"><p align="left">Estado</p></td> <td class="listado5"><select name="s_PRES_ESTADO" class=select> <option value="">- TODOS LOS ESTADOS -</option> <? $lookup_s = db_fill_array("select PARAM_CODI,PARAM_VALOR from SGD_PARAMETRO where PARAM_NOMB='PRESTAMO_ESTADO' order by PARAM_VALOR"); if(is_array($lookup_s)) { reset($lookup_s); while(list($key,$value)=each($lookup_s)) { if($key == $flds_PRES_ESTADO) { $option="SELECTED"; } else { $option=""; } echo "<option $option value=\"$key\">".strtoupper($value)."</option>"; } } if($flds_PRES_ESTADO == -1) { $option="SELECTED"; } else { $option=""; } echo "<option $option value=\"-1\">VENCIDO</option>"; ?> </select></td> </tr> <tr id="b6" style="display:<?= $tipoBusqueda[$opcionMenu][6]; ?>"> <td class="titulos3"><p align="left">Fecha inicial<br>&nbsp;&nbsp;(aaaa-mm-dd)</p></td> <td class="listado5"><script language="javascript"> var dateAvailable1 = new ctlSpiffyCalendarBox("dateAvailable1", "busqueda","fechaInicial","btnDate1","<?=$fechaInicial?>",scBTNMODE_CUSTOMBLUE); dateAvailable1.writeControl(); dateAvailable1.dateFormat="yyyy-MM-dd"; </script></td> </tr> <tr id="b7" style="display:<?= $tipoBusqueda[$opcionMenu][7]; ?>"> <td class="titulos3"><p align="left">Fecha final<br>&nbsp;&nbsp;(aaaa-mm-dd)</p></td> <td class="listado5"><script language="javascript"> var dateAvailable2 = new ctlSpiffyCalendarBox("dateAvailable2", "busqueda","fechaFinal","btnDate2","<?=$fechaFinal?>",scBTNMODE_CUSTOMBLUE); dateAvailable2.writeControl(); dateAvailable2.dateFormat="yyyy-MM-dd"; </script> </td> </tr> <tr id="b8" style="display:<?= $tipoBusqueda[$opcionMenu][8]; ?>"> <td class="titulos3"><p align="left">Hora l&iacute;mite<br>&nbsp;&nbsp;(hh:mm m)</p></td> <td class="listado5"><select name="s_hora_limite" class=select> <? for ($i=1; $i<=12; $i++) { if ($i<=9) { $h="0".$i; } else { $h="".$i; } $seleccion=""; if ($h==$v_hora_limite) { $seleccion="SELECTED"; } ?> <option <?= $seleccion; ?> value="<?= $h;?>"><?= $h;?></option> <? } ?> </select>&nbsp;:&nbsp; <select name="s_minuto_limite" class=select> <? for ($i=0; $i<=59; $i++) { if ($i<=9) { $h="0".$i; } else { $h="".$i; } $seleccion=""; if ($h==$v_minuto_limite) { $seleccion="SELECTED"; } ?> <option <?= $seleccion; ?> value="<?= $h;?>"> <?= $h;?></option> <? } ?> </select>&nbsp;:&nbsp; <select name="s_meridiano" class=select> <? if ($v_meridiano=="AM") {?> <option value="AM" selected>am</option> <option value="PM">pm</option> <? } else {?> <option value="AM">am</option> <option value="PM" selected>pm</option> <? } ?> </select> </tr> <tr> <td class="titulos3" colspan="2"> <? if ($opcionMenu==0 || $opcionMenu==4) {?> <input type="reset" class='botones' value="Limpiar" onClick="javascript: limpiar();"> <input type="submit" class='botones' value="Generar"> <? } else {?> <input type="submit" class='botones' value="Buscar"> <? }?> </td> </tr> </table> </form> <? } //end function //=============================== // Search_Show end //=============================== //=============================== // Pedidos_Show begin //=============================== function Pedidos_Show(){ // De sesi�n global $db; global $ruta_raiz; // Control de visualizaci�n global $sFileName; global $opcionMenu; global $pageAnt; // Pagina de la cual viene // Valores $sFileName = $_POST["sFileName"]; $opcionMenu = $_POST["opcionMenu"]; // Valores $fechaFinal = $_POST["fechaFinal"]; $fechaInicial = $_POST["fechaInicial"]; $krd = $_SESSION["krd"]; $dependencia = $_SESSION["dependencia"]; $usua_doc = $_SESSION["usua_doc"]; // Set variables with search parameters $ps_PRES_ESTADO =strip($_POST["s_PRES_ESTADO"]); $ps_RADI_NUME_RADI=strip(trim($_POST["s_RADI_NUME_RADI"])); // Modificado Infom�trika 14-Julio-2009 // A la variable $ps_USUA_LOGIN se le asigna el valor de $_POST["s_USUA_LOGIN"] para // realizar la consulta, por Login de Usuario, de los radicados solicitados para pr�stamo. //$ps_USUA_LOGIN =$krd; $ps_USUA_LOGIN = strip($_POST['s_USUA_LOGIN']); ; $ps_DEPE_NOMB =strip($_POST["s_DEPE_NOMB"]); $ps_USUA_NOMB =strip($_POST["s_USUA_NOMB"]); $ps_hora_limite =strip($_POST["s_hora_limite"]); $ps_minuto_limite =strip($_POST["s_minuto_limite"]); $ps_meridiano =strip($_POST["s_meridiano"]); $ps_PRES_REQUERIMIENTO=strip($_POST["s_PRES_REQUERIMIENTO"]); if (strlen($pageAnt)==0){ // Build SQL include_once $ruta_raiz."/include/query/prestamo/builtSQL1.inc"; include_once $ruta_raiz."/include/query/prestamo/builtSQL2.inc"; include_once $ruta_raiz."/include/query/prestamo/builtSQL3.inc"; // Build ORDER statement $iSort=strip(get_param("FormPedidos_Sorting")); if(!$iSort) $iSort =20; $iSorted=strip(get_param("FormPedidos_Sorted")); $sDirection=strip(get_param("s_Direction")); if ($iSorted!=$iSort){ $sDirection=" DESC ";} else { if(strcasecmp($sDirection," DESC ")==0){ $sDirection=" ASC "; } else { $sDirection=" DESC "; } } $sOrder=" order by ".$iSort.$sDirection.",PRESTAMO_ID"; // Inicializa el titulo y la visibilidad de los resultados include_once "inicializarRTA.inc"; // Execute SQL statement $db->conn->SetFetchMode(ADODB_FETCH_ASSOC); $rs=$db->query($sSQL.$sOrder); $db->conn->SetFetchMode(ADODB_FETCH_NUM); // Process empty recordset if(!$rs || $rs->EOF) { ?> <p align="center" class="titulosError2">NO HAY REGISTROS SELECCIONADOS</p> <? return; } // Build parameters for order $form_params_search = "s_RADI_NUME_RADI=".tourl($ps_RADI_NUME_RADI)."&s_USUA_LOGIN=".tourl($ps_USUA_LOGIN). "&s_DEPE_NOMB=".tourl($ps_DEPE_NOMB)."&s_USUA_NOMB=".tourl($ps_USUA_NOMB)."&s_PRES_REQUERIMIENTO=". tourl($ps_PRES_REQUERIMIENTO)."&s_PRES_ESTADO=".tourl($ps_PRES_ESTADO)."&fechaInicial=". tourl($fechaInicial)."&fechaFinal=".tourl($fechaFinal)."&s_hora_limite=".tourl($ps_hora_limite). "&s_minuto_limite=".tourl($ps_minuto_limite)."&s_meridiano=".tourl($ps_meridiano); $form_params_page = "&FormPedidos_Page=1&FormStarPage=1&FormSiguiente=0"; $form_params=$form_params_search.$form_params_page."&opcionMenu=".tourl($opcionMenu)."&krd=".tourl($krd). "&FormPedidos_Sorted=".tourl($iSort)."&s_Direction=".tourl($sDirection)."&FormPedidos_Sorting="; // HTML column prestamo headers ?> <form method="post" action="prestamo.php" name="rta"> <input type="hidden" value='<?=$krd?>' name="krd"> <input type="hidden" value=" " name="radicado"> <input type="hidden" value="" name="prestado"> <input type="hidden" name="opcionMenu" value="<?= $opcionMenu ?>"> <!-- orden de presentaci�n del resultado en el formulario de envio !--> <input type="hidden" name="FormPedidos_Sorting" value="<?=$iSort?>"> <input type="hidden" name="FormPedidos_Sorted" value="<?=$iSorted?>"> <input type="hidden" name="s_Direction" value="<?=$sDirection?>"> <table border=0 cellpadding=0 cellspacing=2 class='borde_tab' width="100%"> <tr> <td class="titulos4" colspan="<?=$numCol?>"><a name="Search"><?= $tituloRespuesta[$opcionMenu]?></a></td> </tr> <?PHP // Titulos de las columnas include_once "inicializarTabla.inc"; //---------------------- // Process page scroller //---------------------- // Initialize records per page $iRecordsPerPage = 15; // Inicializa el valor de la pagina actual $iPage=intval(get_param("FormPedidos_Page")); // Inicializa los registros a presentar seg�n la p�gina actual $iCounter = 0; $ant=""; if($iPage > 1) { do{ $new=$rs->fields["PRESTAMO_ID"]; if ($new!=$ant) { $iCounter++; $ant=$new; } $rs->MoveNext(); }while ($iCounter < ($iPage - 1) * $iRecordsPerPage && !$rs->EOF); } $iCounterIni=$iCounter; // Display grid based on recordset $y=0; // Cantidad de registros presentados include_once "getRtaSQLAntIn.inc"; //Une en un solo campo los expedientes while($rs && !$rs->EOF && $y<$iRecordsPerPage) { // Inicializa las variables con los resultados include "getRtaSQL.inc"; if ($antfldPRESTAMO_ID!=$fldPRESTAMO_ID) { //Une en un solo campo los expedientes if ($y!=0) { include "cuerpoTabla.inc"; } // Fila de la tabla con los resultados include "getRtaSQLAnt.inc"; $y++; } else { if ($antfldEXP!=""){ $antfldEXP.="<br>"; $antfldARCH.="<br>"; } $antfldEXP.=$fldEXP; if ($fldARCH=='SI') { $encabARCH = session_name()."=".session_id()."&buscar_exp=".tourl($fldEXP)."&krd=$krd&tipo_archivo=&nomcarpeta="; $antfldARCH.="<a href='".$ruta_raiz."/expediente/datos_expediente.php?".$encabARCH."&num_expediente=".tourl($fldEXP)."&nurad=".tourl($antfldRADICADO)."' class='vinculos'>".$fldARCH."</a>"; } else { $antfldARCH.=$fldARCH; } } $rs->MoveNext(); } if ($y!=0) { include "cuerpoTabla.inc"; // Fila de la tabla con lso resultados $y++; } $cantRegPorPagina=$y; $iCounter=$iCounter+$y; ?> <script> // Inicializa el arreglo con los radicados a procesar var cantRegPorPagina=<?=$cantRegPorPagina-1?>; // Marca todas las casillas si la del titulo es marcada function seleccionarRta() { valor=document.rta.rta_.checked; <? for ($j=0; $j<$cantRegPorPagina; $j++) { ?> document.rta.rta_<?=$j?>.checked=valor; <? } ?> } // Valida y envia el formulario function enviar() { var cant=0; for (i=0; i<cantRegPorPagina; i++) { if (eval('document.rta.rta_'+i+'.checked')==true){ cant=1; break; } } if (cant==0) { alert("Debe seleccionar al menos un radicado"); } else { document.rta.prestado.value=cantRegPorPagina; document.rta.action="formEnvio.php"; document.rta.submit(); } } // Regresa al men� de pr�stamos function regresar() { document.rta.opcionMenu.value=""; document.rta.action="menu_prestamo.php"; document.rta.submit(); } </script> <? // Build parameters for page if (strcasecmp($sDirection," DESC ")==0){ $sDirectionPages=" ASC "; } else { $sDirectionPages=" DESC "; } $form_params_page = $form_params_search."&opcionMenu=".tourl($opcionMenu)."&FormPedidos_Sorted=".tourl($iSort). "&s_Direction=".tourl($sDirectionPages)."&krd=".tourl($krd)."&FormPedidos_Sorting=".tourl($iSort); // N�mero total de registros $ant=$antfldPRESTAMO_ID; while($rs && !$rs->EOF) { $new=$rs->fields["PRESTAMO_ID"]; //para el manejo de expedientes if ($new!=$ant) { $ant=$new; $iCounter++; } $rs->MoveNext(); } $iCounter--; // Inicializa p�ginas visualizables $iNumberOfPages=10; // Inicializa cantidad de p�ginas $iHasPages=intval($iCounter/$iRecordsPerPage); if ($iCounter%$iRecordsPerPage!=0) { $iHasPages++; } // Determina la p�gina inicial del intervalo $iStartPages=1; $FormSiguiente=get_param("FormSiguiente"); //Indica si (1) el n�mero de p�ginas es mayor al visualizable if($FormSiguiente==0) { $iStartPages=get_param("FormStarPage"); } elseif($FormSiguiente==-1){ $iStartPages=$iPage; } else { if($iPage>$iNumberOfPages) { $iStartPages=$iPage-$iNumberOfPages+1; } } // Genera las p�ginas visualizables $sPages= ""; if($iHasPages>$iNumberOfPages) { if($iStartPages==1){ $sPages.="|< << "; } else{ $sPages.="<a href=\"$sFileName?$form_params_page&FormPedidos_Page=1&FormStarPage=1&FormSiguiente=0&\"> <font class=\"ColumnFONT\" title=\"Ver la primera p&aacute;gina\">|<</font></a>&nbsp;"; $sPages.="&nbsp;<a href=\"$sFileName?$form_params_page&FormPedidos_Page=".tourl($iStartPages-1)."&FormStarPage=". tourl($iStartPages-1)."&FormSiguiente=-1&\"><font class=\"ColumnFONT\" title=\"Ver la p&aacute;gina ". ($iStartPages-1)."\"><<</font></a>&nbsp;&nbsp;&nbsp;"; } } for($iPageCount=$iStartPages; $iPageCount<($iStartPages+$iNumberOfPages); $iPageCount++) { if ($iPageCount<=$iHasPages) { $sPages.="<a href=\"$sFileName?$form_params_page&FormPedidos_Page=$iPageCount&FormStarPage=".tourl($iStartPages)."&FormSiguiente=0&\"> <font class=\"ColumnFONT\" title=\"Ver la p&aacute;gina ".$iPageCount."\">".$iPageCount."</font></a>&nbsp;"; } else { break; } } if($iHasPages>$iNumberOfPages) { if($iPageCount-1<$iHasPages){ $sPages.="...&nbsp;&nbsp;<a href=\"$sFileName?$form_params_page&FormPedidos_Page=$iPageCount&FormStarPage=".tourl($iStartPages). "&FormSiguiente=1&\"><font class=\"ColumnFONT\" title=\"Ver la p&aacute;gina ".$iPageCount."\">>></font></a>&nbsp;&nbsp;"; $sPages.="&nbsp;<a href=\"$sFileName?$form_params_page&FormPedidos_Page=$iHasPages&FormStarPage=tourl($iStartPages) &FormSiguiente=1&\"><font class=\"ColumnFONT\" title=\"Ver la &uacute;ltima p&aacute;gina\">>|</font></a>"; } else { $sPages.=" >> >|"; } } ?> <tr class="titulos5" align="center"> <td class="leidos" colspan="<?=($numCol+1);?>"><center><br><?=$sPages?><br><br>P&aacute;gina <?=$iPage?>/<?=$iHasPages?><br> Total de Registros: <?=$iCounter?><br>&nbsp;</center></td> </tr> <? // Botones para procesar if ($tipoRespuesta[$opcionMenu][$numRtaMax]=="") {?> <tr class="titulos4" align="center"> <td class="listado1" colspan="<?=($numCol+1);?>" align="center"><center> <input type="button" class='botones' value="<?=$tituloSubmitRta[$opcionMenu]?>" onClick="javascript:enviar();"> <input type="button" class='botones' value="Cancelar" title="Regresa al men&uacute; de pr&eacute;stamo y control de documentos" onClick="javascript:regresar();"></center> </td> </tr> <? }?> </table> </form> <? } //fin if } //fin function //=============================== // Pedidos_Show end //=============================== ?>
cejebuto/OrfeoWind
prestamo/prestamo.php
PHP
agpl-3.0
30,604
package org.ownprofile.boundary.owner.client; public class Result<T> { private boolean isSuccess; private T successValue; private Fail fail; public static Result<Void> success() { return success(null); } public static <S> Result<S> success(S successValue) { return new Result<S>(successValue); } public static <S> Result<S> fail(String message) { return fail((Throwable)null, "%s", message); } public static <S> Result<S> fail(Throwable cause, String message) { return fail(cause, "%s", message); } public static <S> Result<S> fail(String format, Object... args) { return fail(null, format, args); } public static <S> Result<S> fail(Throwable cause, String format, Object... args) { final Fail f = new Fail(cause, format, args); return new Result<S>(f); } private Result(T successValue) { this.isSuccess = true; this.successValue = successValue; } private Result(Fail fail) { this.isSuccess = false; this.fail = fail; } public boolean isSuccess() { return isSuccess; } public boolean isFail() { return !isSuccess; } public T getSuccessValue() { if (isSuccess) { return successValue; } else { throw new IllegalStateException(String.format("Result is Fail: %s", fail)); } } public Fail getFail() { if (isSuccess) { throw new IllegalStateException(String.format("Result is Success")); } else { return fail; } } @Override public String toString() { return String.format("%s: %s", isSuccess ? "SUCCESS" : "FAIL", isSuccess ? successValue : fail); } // ------------------------------ public static class Fail { private String message; private Throwable cause; private Fail(Throwable cause, String message) { this.cause = cause; this.message = message; } private Fail(Throwable cause, String format, Object... args) { this(cause, String.format(format, args)); } public String getMessage() { return message; } public Throwable getCause() { return cause; } @Override public String toString() { return String.format("%s - %s", message, cause); } } }
mchlrch/ownprofile
org.ownprofile.node/src/main/java/org/ownprofile/boundary/owner/client/Result.java
Java
agpl-3.0
2,101
<?php use Illuminate\Database\Migrations\Migration; class AddDomainIdToBusinessesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('businesses', function ($table) { $table->integer('domain_id')->unsigned()->nullable()->after('category_id'); $table->foreign('domain_id')->references('id')->on('domains')->onDelete('set null'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('businesses', function ($table) { $table->dropForeign('businesses_domain_id_foreign'); $table->dropColumn('domain_id'); }); } }
timegridio/timegrid
database/migrations/2015_12_20_014958_add_domain_id_to_businesses_table.php
PHP
agpl-3.0
763
# Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. module AWS module Core class PageResult < Array # @return [Collection] Returns the collection that was used to # populated this page of results. attr_reader :collection # @return [Integer] Returns the maximum number of results per page. # The final page in a collection may return fewer than +:per_page+ # items (e.g. +:per_page+ is 10 and there are only 7 items). attr_reader :per_page # @return [String] An opaque token that can be passed the #page method # of the collection that returned this page of results. This next # token behaves as a pseudo offset. If +next_token+ is +nil+ then # there are no more results for the collection. attr_reader :next_token # @param [Collection] collection The collection that was used to # request this page of results. The collection should respond to # #page and accept a :next_token option. # # @param [Array] items An array of result items that represent a # page of results. # # @param [Integer] per_page The number of requested items for this # page of results. If the count of items is smaller than +per_page+ # then this is the last page of results. # # @param [String] next_token (nil) A token that can be passed to the # def initialize collection, items, per_page, next_token @collection = collection @per_page = per_page @next_token = next_token super(items) end # @return [PageResult] # @raise [RuntimeError] Raises a runtime error when called against # a collection that has no more results (i.e. #last_page? == true). def next_page if last_page? raise 'unable to get the next page, already at the last page' end collection.page(:per_page => per_page, :next_token => next_token) end # @return [Boolean] Returns +true+ if this is the last page of results. def last_page? next_token.nil? end # @return [Boolean] Returns +true+ if there are more pages of results. def more? !!next_token end end end end
usmschuck/canvas
vendor/bundle/ruby/1.9.1/gems/aws-sdk-1.8.3.1/lib/aws/core/page_result.rb
Ruby
agpl-3.0
2,790
<?php /** * DAO tbMovimentacaoBancaria * @author emanuel.sampaio - Politec * @since 17/02/2011 * @version 1.0 * @package application * @subpackage application.model * @copyright © 2011 - Ministério da Cultura - Todos os direitos reservados. * @link http://www.cultura.gov.br */ class tbMovimentacaoBancaria extends GenericModel { /* dados da tabela */ protected $_banco = "SAC"; protected $_schema = "dbo"; protected $_name = "tbMovimentacaoBancaria"; /** * Método para buscar * @access public * @param string $pronac * @param boolean $conta_rejeitada * @param array $periodo * @param array $operacao * @return object */ public function buscarDados($pronac = null, $conta_rejeitada = null, $periodo = null, $operacao = null ,$tamanho=-1, $inicio=-1, $count = null) { $select = $this->select(); $select->setIntegrityCheck(false); if(isset($count)){ $select->from( array("mi" => "tbMovimentacaoBancariaItem"), array("total" => "count(*)")); } else { $select->from( array("mi" => "tbMovimentacaoBancariaItem") ,array("m.nrBanco" ,"CONVERT(CHAR(10), m.dtInicioMovimento, 103) AS dtInicioMovimento" ,"CONVERT(CHAR(10), m.dtFimMovimento, 103) AS dtFimMovimento" ,"mi.idMovimentacaoBancaria" ,"mi.tpRegistro" ,"mi.nrAgencia" ,"mi.nrDigitoConta" ,"mi.nmTituloRazao" ,"mi.nmAbreviado" ,"CONVERT(CHAR(10), mi.dtAberturaConta, 103) AS dtAberturaConta" ,"mi.nrCNPJCPF" ,"n.Descricao AS Proponente" ,"mi.vlSaldoInicial" ,"mi.tpSaldoInicial" ,"mi.vlSaldoFinal" ,"mi.tpSaldoFinal" ,"CONVERT(CHAR(10), mi.dtMovimento, 103) AS dtMovimento" ,"mi.cdHistorico" ,"mi.dsHistorico" ,"mi.nrDocumento" ,"mi.vlMovimento" ,"mi.cdMovimento" ,"mi.idMovimentacaoBancariaItem" ,"ti.idTipoInconsistencia" ,"ti.dsTipoInconsistencia" ,"(p.AnoProjeto+p.Sequencial) AS pronac" ,"p.NomeProjeto" ,"bc.Descricao AS nmBanco") ); } $select->joinInner( array("m" => $this->_name) ,"m.idMovimentacaoBancaria = mi.idMovimentacaoBancaria" ,array() ); if(!empty($conta_rejeitada) && $conta_rejeitada){ $select->joinInner( array("mx" => "tbMovimentacaoBancariaItemxTipoInconsistencia") ,"mi.idMovimentacaoBancariaItem = mx.idMovimentacaoBancariaItem" ,array() ); $select->joinInner( array("ti" => "tbTipoInconsistencia") ,"ti.idTipoInconsistencia = mx.idTipoInconsistencia" ,array() ); } else { $select->joinLeft( array("mx" => "tbMovimentacaoBancariaItemxTipoInconsistencia") ,"mi.idMovimentacaoBancariaItem = mx.idMovimentacaoBancariaItem" ,array() ); $select->joinLeft( array("ti" => "tbTipoInconsistencia") ,"ti.idTipoInconsistencia = mx.idTipoInconsistencia" ,array() ); } $select->joinLeft( array("c" => "ContaBancaria") ,"mi.nrAgencia = c.Agencia AND (mi.nrDigitoConta = c.ContaBloqueada OR mi.nrDigitoConta = c.ContaLivre)" ,array() ); $select->joinLeft( array("p" => "Projetos") ,"c.AnoProjeto = p.AnoProjeto AND c.Sequencial = p.Sequencial" ,array() ); $select->joinLeft( array("bc" => "bancos") ,"m.nrBanco = bc.Codigo" ,array() ,"AGENTES.dbo" ); $select->joinLeft( array("a" => "Agentes") ,"mi.nrCNPJCPF = a.CNPJCPF" ,array() ,"AGENTES.dbo" ); $select->joinLeft( array("n" => "Nomes") ,"a.idAgente = n.idAgente" ,array() ,"AGENTES.dbo" ); // $select->where("mi.vlSaldoInicial > 0.00"); //$select->where("mi.vlSaldoFinal > 0.00"); // busca pelo pronac if (!empty($pronac)) { $select->where("(c.AnoProjeto+c.Sequencial) = ?", $pronac); } // filtra por contas rejeitadas if (!empty($conta_rejeitada) && $conta_rejeitada) { $select->where("mx.idMovimentacaoBancariaItem IS NOT NULL"); $select->where("mx.idTipoInconsistencia IS NOT NULL"); } else { $select->where("mx.idMovimentacaoBancariaItem IS NULL"); $select->where("mx.idTipoInconsistencia IS NULL"); } // busca pelo período if (!empty($periodo)) { if ($periodo[0] == "A") // Hoje { $select->where("CONVERT(DATE, m.dtInicioMovimento) = CONVERT(DATE, GETDATE()) OR CONVERT(DATE, m.dtFimMovimento) = CONVERT(DATE, GETDATE()) OR CONVERT(DATE, mi.dtMovimento) = CONVERT(DATE, GETDATE())"); } if ($periodo[0] == "B") // Ontem { $select->where("CONVERT(DATE, m.dtInicioMovimento) = DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, m.dtFimMovimento) = DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, mi.dtMovimento) = DATEADD(DAY, -1, CONVERT(DATE, GETDATE()))"); } if ($periodo[0] == "C") // Últimos 7 dias { $select->where("CONVERT(DATE, m.dtInicioMovimento) > DATEADD(DAY, -7, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, m.dtFimMovimento) > DATEADD(DAY, -7, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, mi.dtMovimento) > DATEADD(DAY, -7, CONVERT(DATE, GETDATE()))"); } if ($periodo[0] == "D") // Semana passada (seg-dom) { $select->where("(CONVERT(DATE, m.dtInicioMovimento) >= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, -7, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -8, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -9, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -10, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -11, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -12, CONVERT(DATE, GETDATE())) END AND CONVERT(DATE, m.dtInicioMovimento) <= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) END) OR (CONVERT(DATE, m.dtFimMovimento) >= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, -7, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -8, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -9, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -10, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -11, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -12, CONVERT(DATE, GETDATE())) END AND CONVERT(DATE, m.dtFimMovimento) <= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) END) OR (CONVERT(DATE, mi.dtMovimento) >= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, -7, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -8, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -9, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -10, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -11, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -12, CONVERT(DATE, GETDATE())) END AND CONVERT(DATE, mi.dtMovimento) <= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) END)"); } if ($periodo[0] == "E") // Última semana (seg-sex) { $select->where("(CONVERT(DATE, m.dtInicioMovimento) >= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE())) END AND CONVERT(DATE, m.dtInicioMovimento) <= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) END) OR (CONVERT(DATE, m.dtFimMovimento) >= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE())) END AND CONVERT(DATE, m.dtFimMovimento) <= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) END) OR (CONVERT(DATE, mi.dtMovimento) >= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -6, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, -3, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, -4, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -5, CONVERT(DATE, GETDATE())) END AND CONVERT(DATE, mi.dtMovimento) <= CASE DATEPART(DW, GETDATE()) WHEN 1 THEN DATEADD(DAY, -2, CONVERT(DATE, GETDATE())) WHEN 2 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 3 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 4 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 5 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 6 THEN DATEADD(DAY, 0, CONVERT(DATE, GETDATE())) WHEN 7 THEN DATEADD(DAY, -1, CONVERT(DATE, GETDATE())) END)"); } if ($periodo[0] == "F") // Este mês { $select->where("DATEPART(MONTH, m.dtInicioMovimento) + DATEPART(YEAR, m.dtInicioMovimento) = DATEPART(MONTH, GETDATE()) + DATEPART(YEAR, GETDATE()) OR DATEPART(MONTH, m.dtFimMovimento) + DATEPART(YEAR, m.dtFimMovimento) = DATEPART(MONTH, GETDATE()) + DATEPART(YEAR, GETDATE()) OR DATEPART(MONTH, mi.dtMovimento) + DATEPART(YEAR, mi.dtMovimento) = DATEPART(MONTH, GETDATE()) + DATEPART(YEAR, GETDATE())"); } if ($periodo[0] == "G") // Ano passado { $select->where("DATEPART(YEAR, m.dtInicioMovimento) = (DATEPART(YEAR, GETDATE()) - 1) OR DATEPART(YEAR, m.dtFimMovimento) = (DATEPART(YEAR, GETDATE()) - 1) OR DATEPART(YEAR, mi.dtMovimento) = (DATEPART(YEAR, GETDATE()) - 1)"); } if ($periodo[0] == "H") // Últimos 12 meses { $select->where("CONVERT(DATE, m.dtInicioMovimento) >= DATEADD(MONTH , -12, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, m.dtFimMovimento) >= DATEADD(MONTH , -12, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, mi.dtMovimento) >= DATEADD(MONTH , -12, CONVERT(DATE, GETDATE()))"); } if ($periodo[0] == "I") // Últimos 6 meses { $select->where("CONVERT(DATE, m.dtInicioMovimento) >= DATEADD(MONTH , -6, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, m.dtFimMovimento) >= DATEADD(MONTH , -6, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, mi.dtMovimento) >= DATEADD(MONTH , -6, CONVERT(DATE, GETDATE()))"); } if ($periodo[0] == "J") // Últimos 3 meses { $select->where("CONVERT(DATE, m.dtInicioMovimento) >= DATEADD(MONTH , -3, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, m.dtFimMovimento) >= DATEADD(MONTH , -3, CONVERT(DATE, GETDATE())) OR CONVERT(DATE, mi.dtMovimento) >= DATEADD(MONTH , -3, CONVERT(DATE, GETDATE()))"); } if ($periodo[0] == "K") // filtra conforme uma data inicial e uma data final { if (!empty($periodo[1]) && !empty($periodo[2])) { $select->where("m.dtInicioMovimento >= ?", Data::dataAmericana($periodo[1]) . " 00:00:00"); $select->where("m.dtFimMovimento <= ?", Data::dataAmericana($periodo[2]) . " 23:59:59"); } else { if (!empty($periodo[1])) { $select->where("m.dtInicioMovimento >= ?", Data::dataAmericana($periodo[1]) . " 00:00:00"); } if (!empty($periodo[2])) { $select->where("m.dtFimMovimento <= ?", Data::dataAmericana($periodo[2]) . " 23:59:59"); } } } } // fecha if periodo // filtra pelo tipo de operação if (!empty($operacao)) { $select->where("mi.tpSaldoInicial = ? OR mi.tpSaldoInicial IS NULL", $operacao); $select->where("mi.tpSaldoFinal = ? OR mi.tpSaldoFinal IS NULL", $operacao); $select->where("mi.cdMovimento = ? OR mi.cdMovimento IS NULL", $operacao); } /*if(is_null($count)){ /*$select->order("mi.tpRegistro"); $select->order("(p.AnoProjeto+p.Sequencial)"); $select->order("m.dtInicioMovimento"); $select->order("m.dtFimMovimento"); $select->order("mi.dtMovimento"); $select->order(array(5,26,2,3,17)); }*/ //paginacao if ($tamanho > -1) { $tmpInicio = 0; if ($inicio > -1) { $tmpInicio = $inicio; } $select->limit($tamanho, $tmpInicio); } //x($select->assemble()); return $this->fetchAll($select); } // fecha método buscarDados() /** * Método para cadastrar * @access public * @param array $dados * @return integer (retorna o último id cadastrado) */ public function cadastrarDados($dados) { return $this->insert($dados); } // fecha método cadastrarDados() /** * Método para alterar * @access public * @param array $dados * @param integer $where * @return integer (quantidade de registros alterados) */ public function alterarDados($dados, $where) { $where = "idMovimentacaoBancaria = " . $where; return $this->update($dados, $where); } // fecha método alterarDados() /** * Método para excluir * @access public * @param integer $where * @return integer (quantidade de registros excluídos) */ public function excluirDados($where) { $where = "idMovimentacaoBancaria = " . $where; return $this->delete($where); } // fecha método excluirDados() } // fecha class
hackultura/novosalic
application/model/tbMovimentacaoBancaria.php
PHP
agpl-3.0
17,407
import sys import time import sys num = 1000 print_granularity = 1000 count = 0 first = True start = 0 gran_start = 0 min = 0 max = 0 avg = 0 sum = 0 total = 0 def set_print_granularity(p): global print_granularity print_granularity = p print("%s: print granularity = %s" % (sys.argv[0], print_granularity)) def loop_count(): global min, max, avg, total, gran_start, sum, start, first, count now = round(time.time() * 1000) if not first: elapsed = now - start if elapsed < min: min = elapsed if elapsed > max: max = elapsed sum = sum + elapsed start = now count = count + 1 total = total + 1 if count % print_granularity == 0 and not first: gran_elapsed = now - gran_start gran_start = now avg = sum / print_granularity print("%s: last %s run stats in msec \t\t elapsed = %s \t min = %s \t max = %s \t avg = %s \t\t total loops = %s" % (sys.argv[0], print_granularity, sum, min, max, avg, total)) # sys.stdout.write("-") # sys.stdout.flush() if first or count % print_granularity == 0: gran_start = now min = 10e10 max = -10e10 avg = 0 sum = 0 first = False
scalien/keyspace
test/concurrency/common.py
Python
agpl-3.0
1,105
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.forms.vitalsignstprbp; import ims.framework.delegates.*; abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode { abstract protected void onFormOpen() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onChkLegendValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnViewClick() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onRadioButtongrpShowByValueChanged() throws ims.framework.exceptions.PresentationLogicException; abstract protected void onBtnPrintClick() throws ims.framework.exceptions.PresentationLogicException; public final void setContext(ims.framework.UIEngine engine, GenForm form) { this.engine = engine; this.form = form; this.form.setFormOpenEvent(new FormOpen() { private static final long serialVersionUID = 1L; public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException { onFormOpen(); } }); this.form.chkLegend().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onChkLegendValueChanged(); } }); this.form.btnView().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnViewClick(); } }); this.form.grpShowBy().setValueChangedEvent(new ValueChanged() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onRadioButtongrpShowByValueChanged(); } }); this.form.btnPrint().setClickEvent(new Click() { private static final long serialVersionUID = 1L; public void handle() throws ims.framework.exceptions.PresentationLogicException { onBtnPrintClick(); } }); } public void free() { this.engine = null; this.form = null; } protected ims.framework.UIEngine engine; protected GenForm form; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/forms/vitalsignstprbp/Handlers.java
Java
agpl-3.0
4,321
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.vo.beans; public class PatientDiagnosisStatusForReferralCodingVoBean extends ims.vo.ValueObjectBean { public PatientDiagnosisStatusForReferralCodingVoBean() { } public PatientDiagnosisStatusForReferralCodingVoBean(ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.status = vo.getStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getStatus().getBean(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.status = vo.getStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getStatus().getBean(); } public ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo = null; if(map != null) vo = (ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo)map.getValueObject(this); if(vo == null) { vo = new ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.vo.LookupInstanceBean getStatus() { return this.status; } public void setStatus(ims.vo.LookupInstanceBean value) { this.status = value; } private Integer id; private int version; private ims.vo.LookupInstanceBean status; }
IMS-MAXIMS/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/refman/vo/beans/PatientDiagnosisStatusForReferralCodingVoBean.java
Java
agpl-3.0
3,988
<?php // Database Restore $locale['400'] = "Восстановление БД"; $locale['401'] = "Ошибка"; $locale['402'] = "Неверный формат файла резервной копии"; $locale['403'] = "Закрыть"; // Backup File Information $locale['410'] = "Данные о файле резервной копии"; $locale['411'] = "Данные о файле для восстановления"; $locale['412'] = "Имя файла копии:"; $locale['413'] = "Дата создания:"; $locale['414'] = "Имя базы данных:"; $locale['415'] = "Префикс таблиц ядра:"; $locale['416'] = "Таблицы:"; $locale['417'] = "Посмотреть"; $locale['418'] = "отмена"; $locale['419'] = "таблиц"; // Database Restore $locale['430'] = "Параметры восстановления"; $locale['431'] = "Имя файла:"; $locale['432'] = "Создан:"; $locale['433'] = "Создать таблицы:"; $locale['434'] = "Заполнить таблицы:"; $locale['435'] = "Выбрать:"; $locale['436'] = "все"; $locale['437'] = "ничего"; $locale['438'] = "Восстановить из резервной копии"; $locale['439'] = "Отмена"; $locale['440'] = "Поддерживаемые типы файлов:"; // Database Backup $locale['450'] = "Резервирование БД"; $locale['451'] = "Информация о базе данных"; $locale['452'] = "Общий размер таблиц:"; $locale['453'] = "Размер таблиц ядра:"; $locale['454'] = "Параметры резервирования:"; $locale['455'] = "Тип резервной копии:"; $locale['456'] = "(сжатая)"; $locale['457'] = "Таблицы БД"; $locale['458'] = "ядро"; $locale['459'] = "Создать резервную копию"; $locale['460'] = "Админпароль:"; $locale['460b'] = "Пожалуйста, введите Ваш админпароль"; $locale['461'] = "Требуемая информация"; // Backup List $locale['480'] = "Восстановить из резервной копии"; $locale['481'] = "Имя файла:"; $locale['481b'] = "Пожалуйста, укажите имя файла"; ?>
dialektika/PHP-Fusion
locale/Russian/admin/db-backup.php
PHP
agpl-3.0
2,275
#region C#raft License // This file is part of C#raft. Copyright C#raft Team // // C#raft is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #endregion using Chraft.Entity.Items; using Chraft.Utilities.Blocks; using Chraft.World.Blocks.Base; namespace Chraft.World.Blocks { class BlockStone : BlockBase { public BlockStone() { Name = "Stone"; Type = BlockData.Blocks.Stone; IsSolid = true; var item = ItemHelper.GetInstance(BlockData.Blocks.Cobblestone); item.Count = 1; LootTable.Add(item); } } }
chraft/c-raft
Chraft/World/Blocks/BlockStone.cs
C#
agpl-3.0
1,214
# -*- coding: utf-8 -*- ############################################################################## # # Odoo, Open Source Business Applications # Copyright (c) 2015 Odoo S.A. <http://openerp.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields, api class StockPicking(models.Model): _inherit = 'stock.picking' carrier_price = fields.Float(string="Shipping Cost", readonly=True) delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True) @api.multi def do_transfer(self): res = super(StockPicking, self).do_transfer() if self.carrier_id and self.carrier_id.delivery_type != 'grid': self.send_to_shipper() return res # Signature due to strange old api methods @api.model def _prepare_shipping_invoice_line(self, picking, invoice): picking.ensure_one() invoice.ensure_one() carrier = picking.carrier_id # No carrier if not carrier: return None # Carrier already invoiced on the sale order if any(inv_line.product_id.id == carrier.product_id.id for inv_line in invoice.invoice_line_ids): return None # Classic carrier if carrier.delivery_type == 'grid': return super(StockPicking, self)._prepare_shipping_invoice_line(picking, invoice) # Shipping provider price = picking.carrier_price account_id = carrier.product_id.property_account_income.id if not account_id: account_id = carrier.product_id.categ_id.property_account_income_categ.id taxes = carrier.product_id.taxes_id taxes_ids = taxes.ids # Apply original SO fiscal position if picking.sale_id.fiscal_position_id: fpos = picking.sale_id.fiscal_position_id account_id = fpos.map_account(account_id) taxes_ids = fpos.map_tax(taxes).ids res = { 'name': carrier.name, 'invoice_id': invoice.id, 'uos_id': carrier.product_id.uos_id.id, 'product_id': carrier.product_id.id, 'account_id': account_id, 'price_unit': price, 'quantity': 1, 'invoice_line_tax_ids': [(6, 0, taxes_ids)], } return res @api.one def send_to_shipper(self): res = self.carrier_id.send_shipping(self)[0] self.carrier_price = res['exact_price'] self.carrier_tracking_ref = res['tracking_number'] msg = "Shipment sent to carrier %s for expedition with tracking number %s" % (self.carrier_id.name, self.carrier_tracking_ref) self.message_post(body=msg) @api.multi def open_website_url(self): self.ensure_one() client_action = {'type': 'ir.actions.act_url', 'name': "Shipment Tracking Page", 'target': 'new', 'url': self.carrier_id.get_tracking_link(self)[0] } return client_action @api.one def cancel_shipment(self): self.carrier_id.cancel_shipment(self) msg = "Shipment %s cancelled" % self.carrier_tracking_ref self.message_post(body=msg) self.carrier_tracking_ref = False
tvtsoft/odoo8
addons/delivery/models/stock_picking.py
Python
agpl-3.0
4,025
<?php $this->applyTemplateHook('settings-nav','before'); ?> <nav id="panel-settings-nav" class="sidebar-panel"> <?php $this->applyTemplateHook('settings-nav','begin'); ?> <?php $this->applyTemplateHook('settings-nav','end'); ?> </nav> <?php $this->applyTemplateHook('settings-nav','after'); ?>
secultce/mapasculturais
src/protected/application/themes/BaseV1/layouts/parts/panel-settings-nav.php
PHP
agpl-3.0
306
/* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2007 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.ctp.server.notification; /** * * @version $Id: NotificationProviderException.java,v 1.2 2007-11-28 11:26:16 nichele Exp $ */ public class NotificationProviderException extends Exception { /** * Creates a new instance of <code>NotificationProviderException</code> without * detail message. */ public NotificationProviderException() { super(); } /** * Constructs an instance of <code>NotificationProviderException</code> with the * specified detail message. * * @param message the detail message. */ public NotificationProviderException(String message) { super(message); } /** * Constructs an instance of <code>NotificationProviderException</code> with the * specified detail message and the given cause. * * @param message the detail message. * @param cause the cause. */ public NotificationProviderException(String message, Throwable cause) { super(message, cause); } /** * Constructs an instance of <code>NotificationProviderException</code> with the * specified cause. * * @param cause the cause. */ public NotificationProviderException(Throwable cause) { super(cause); } }
accesstest3/cfunambol
ctp/ctp-server/src/main/java/com/funambol/ctp/server/notification/NotificationProviderException.java
Java
agpl-3.0
3,078
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.spinalinjuries.domain.base.impl; import ims.domain.impl.DomainImpl; public abstract class BaseSharedNewConcernImpl extends DomainImpl implements ims.spinalinjuries.domain.SharedNewConcern, ims.domain.impl.Transactional { private static final long serialVersionUID = 1L; @SuppressWarnings("unused") public void validatesaveConcern(ims.core.vo.PatientCurrentConcernVo concern, ims.core.vo.PatientShort patient) { } @SuppressWarnings("unused") public void validatelistHcps(ims.core.vo.HcpFilter filter) { } @SuppressWarnings("unused") public void validatelistProbsOnAdmission(ims.core.vo.CareContextShortVo coClinicalContactShort) { } @SuppressWarnings("unused") public void validategetConcern(ims.core.clinical.vo.PatientConcernRefVo concernId) { } }
open-health-hub/openmaxims-linux
openmaxims_workspace/SpinalInjuries/src/ims/spinalinjuries/domain/base/impl/BaseSharedNewConcernImpl.java
Java
agpl-3.0
2,507
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated on 16/04/2014, 12:31 * */ package ims.emergency.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Cornel Ventuneac */ public class TrackingLiteVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.emergency.vo.TrackingLiteVo copy(ims.emergency.vo.TrackingLiteVo valueObjectDest, ims.emergency.vo.TrackingLiteVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_Tracking(valueObjectSrc.getID_Tracking()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // CurrentArea valueObjectDest.setCurrentArea(valueObjectSrc.getCurrentArea()); // isPrimaryCare valueObjectDest.setIsPrimaryCare(valueObjectSrc.getIsPrimaryCare()); // isDischarged valueObjectDest.setIsDischarged(valueObjectSrc.getIsDischarged()); // LastMovementDateTime valueObjectDest.setLastMovementDateTime(valueObjectSrc.getLastMovementDateTime()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createTrackingLiteVoCollectionFromTracking(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.emergency.domain.objects.Tracking objects. */ public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(java.util.Set domainObjectSet) { return createTrackingLiteVoCollectionFromTracking(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.emergency.domain.objects.Tracking objects. */ public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(DomainObjectMap map, java.util.Set domainObjectSet) { ims.emergency.vo.TrackingLiteVoCollection voList = new ims.emergency.vo.TrackingLiteVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.emergency.domain.objects.Tracking domainObject = (ims.emergency.domain.objects.Tracking) iterator.next(); ims.emergency.vo.TrackingLiteVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.emergency.domain.objects.Tracking objects. */ public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(java.util.List domainObjectList) { return createTrackingLiteVoCollectionFromTracking(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.emergency.domain.objects.Tracking objects. */ public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(DomainObjectMap map, java.util.List domainObjectList) { ims.emergency.vo.TrackingLiteVoCollection voList = new ims.emergency.vo.TrackingLiteVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.emergency.domain.objects.Tracking domainObject = (ims.emergency.domain.objects.Tracking) domainObjectList.get(i); ims.emergency.vo.TrackingLiteVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.emergency.domain.objects.Tracking set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractTrackingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection) { return extractTrackingSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractTrackingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.emergency.vo.TrackingLiteVo vo = voCollection.get(i); ims.emergency.domain.objects.Tracking domainObject = TrackingLiteVoAssembler.extractTracking(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.emergency.domain.objects.Tracking list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractTrackingList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection) { return extractTrackingList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractTrackingList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.emergency.vo.TrackingLiteVo vo = voCollection.get(i); ims.emergency.domain.objects.Tracking domainObject = TrackingLiteVoAssembler.extractTracking(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.emergency.domain.objects.Tracking object. * @param domainObject ims.emergency.domain.objects.Tracking */ public static ims.emergency.vo.TrackingLiteVo create(ims.emergency.domain.objects.Tracking domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.emergency.domain.objects.Tracking object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.emergency.vo.TrackingLiteVo create(DomainObjectMap map, ims.emergency.domain.objects.Tracking domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.emergency.vo.TrackingLiteVo valueObject = (ims.emergency.vo.TrackingLiteVo) map.getValueObject(domainObject, ims.emergency.vo.TrackingLiteVo.class); if ( null == valueObject ) { valueObject = new ims.emergency.vo.TrackingLiteVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.Tracking */ public static ims.emergency.vo.TrackingLiteVo insert(ims.emergency.vo.TrackingLiteVo valueObject, ims.emergency.domain.objects.Tracking domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.Tracking */ public static ims.emergency.vo.TrackingLiteVo insert(DomainObjectMap map, ims.emergency.vo.TrackingLiteVo valueObject, ims.emergency.domain.objects.Tracking domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_Tracking(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // CurrentArea if (domainObject.getCurrentArea() != null) { if(domainObject.getCurrentArea() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already. { HibernateProxy p = (HibernateProxy) domainObject.getCurrentArea(); int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString()); valueObject.setCurrentArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(id, -1)); } else { valueObject.setCurrentArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(domainObject.getCurrentArea().getId(), domainObject.getCurrentArea().getVersion())); } } // isPrimaryCare valueObject.setIsPrimaryCare( domainObject.isIsPrimaryCare() ); // isDischarged valueObject.setIsDischarged( domainObject.isIsDischarged() ); // LastMovementDateTime java.util.Date LastMovementDateTime = domainObject.getLastMovementDateTime(); if ( null != LastMovementDateTime ) { valueObject.setLastMovementDateTime(new ims.framework.utils.DateTime(LastMovementDateTime) ); } return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.emergency.domain.objects.Tracking extractTracking(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVo valueObject) { return extractTracking(domainFactory, valueObject, new HashMap()); } public static ims.emergency.domain.objects.Tracking extractTracking(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_Tracking(); ims.emergency.domain.objects.Tracking domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.emergency.domain.objects.Tracking)domMap.get(valueObject); } // ims.emergency.vo.TrackingLiteVo ID_Tracking field is unknown domainObject = new ims.emergency.domain.objects.Tracking(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Tracking()); if (domMap.get(key) != null) { return (ims.emergency.domain.objects.Tracking)domMap.get(key); } domainObject = (ims.emergency.domain.objects.Tracking) domainFactory.getDomainObject(ims.emergency.domain.objects.Tracking.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_Tracking()); ims.emergency.configuration.domain.objects.TrackingArea value1 = null; if ( null != valueObject.getCurrentArea() ) { if (valueObject.getCurrentArea().getBoId() == null) { if (domMap.get(valueObject.getCurrentArea()) != null) { value1 = (ims.emergency.configuration.domain.objects.TrackingArea)domMap.get(valueObject.getCurrentArea()); } } else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field { value1 = domainObject.getCurrentArea(); } else { value1 = (ims.emergency.configuration.domain.objects.TrackingArea)domainFactory.getDomainObject(ims.emergency.configuration.domain.objects.TrackingArea.class, valueObject.getCurrentArea().getBoId()); } } domainObject.setCurrentArea(value1); domainObject.setIsPrimaryCare(valueObject.getIsPrimaryCare()); domainObject.setIsDischarged(valueObject.getIsDischarged()); ims.framework.utils.DateTime dateTime4 = valueObject.getLastMovementDateTime(); java.util.Date value4 = null; if ( dateTime4 != null ) { value4 = dateTime4.getJavaDate(); } domainObject.setLastMovementDateTime(value4); return domainObject; } }
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/TrackingLiteVoAssembler.java
Java
agpl-3.0
17,855
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\EventListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpKernel\Event\FinishRequestEvent; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\Routing\RequestContextAwareInterface; /** * Initializes the locale based on the current request. * * This listener works in 2 modes: * * * 2.3 compatibility mode where you must call setRequest whenever the Request changes. * * 2.4+ mode where you must pass a RequestStack instance in the constructor. * * @author Fabien Potencier <fabien@symfony.com> */ class LocaleListener implements EventSubscriberInterface { private $router; private $defaultLocale; private $requestStack; /** * RequestStack will become required in 3.0. */ public function __construct($defaultLocale = 'en', RequestContextAwareInterface $router = null, RequestStack $requestStack = null) { $this->defaultLocale = $defaultLocale; $this->requestStack = $requestStack; $this->router = $router; } public static function getSubscribedEvents() { return array( // must be registered after the Router to have access to the _locale KernelEvents::REQUEST => array( array( 'onKernelRequest', 16 ) ), KernelEvents::FINISH_REQUEST => array( array( 'onKernelFinishRequest', 0 ) ), ); } /** * Sets the current Request. * * This method was used to synchronize the Request, but as the HttpKernel * is doing that automatically now, you should never call it directly. * It is kept public for BC with the 2.3 version. * * @param Request|null $request A Request instance * * @deprecated Deprecated since version 2.4, to be removed in 3.0. */ public function setRequest(Request $request = null) { if (null === $request) { return; } $this->setLocale($request); $this->setRouterContext($request); } private function setLocale( Request $request ) { if ($locale = $request->attributes->get( '_locale' )) { $request->setLocale( $locale ); } } private function setRouterContext( Request $request ) { if (null !== $this->router) { $this->router->getContext()->setParameter( '_locale', $request->getLocale() ); } } public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); $request->setDefaultLocale($this->defaultLocale); $this->setLocale($request); $this->setRouterContext($request); } public function onKernelFinishRequest(FinishRequestEvent $event) { if (null === $this->requestStack) { return; // removed when requestStack is required } if (null !== $parentRequest = $this->requestStack->getParentRequest()) { $this->setRouterContext($parentRequest); } } }
KWZwickau/KREDA-Sphere
Library/MOC-V/Component/Router/Vendor/Symfony/Component/HttpKernel/EventListener/LocaleListener.php
PHP
agpl-3.0
3,436
package com.sapienter.jbilling.client.jspc.payment; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import com.sapienter.jbilling.client.util.Constants; public final class review_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List _jspx_dependants; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.AnnotationProcessor _jsp_annotationprocessor; public Object getDependants() { return _jspx_dependants; } public void _jspInit() { _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName()); } public void _jspDestroy() { _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.release(); _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.release(); _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.release(); } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"); if (_jspx_meth_sess_005fexistsAttribute_005f0(_jspx_page_context)) return; out.write('\r'); out.write('\n'); if (_jspx_meth_sess_005fexistsAttribute_005f1(_jspx_page_context)) return; out.write("\r\n\r\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_sess_005fexistsAttribute_005f0(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // sess:existsAttribute org.apache.taglibs.session.ExistsAttributeTag _jspx_th_sess_005fexistsAttribute_005f0 = (org.apache.taglibs.session.ExistsAttributeTag) _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.get(org.apache.taglibs.session.ExistsAttributeTag.class); _jspx_th_sess_005fexistsAttribute_005f0.setPageContext(_jspx_page_context); _jspx_th_sess_005fexistsAttribute_005f0.setParent(null); // /payment/review.jsp(30,0) name = name type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_sess_005fexistsAttribute_005f0.setName("jsp_is_refund"); // /payment/review.jsp(30,0) name = value type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_sess_005fexistsAttribute_005f0.setValue(false); int _jspx_eval_sess_005fexistsAttribute_005f0 = _jspx_th_sess_005fexistsAttribute_005f0.doStartTag(); if (_jspx_eval_sess_005fexistsAttribute_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n "); if (_jspx_meth_tiles_005finsert_005f0(_jspx_th_sess_005fexistsAttribute_005f0, _jspx_page_context)) return true; out.write('\r'); out.write('\n'); int evalDoAfterBody = _jspx_th_sess_005fexistsAttribute_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_sess_005fexistsAttribute_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f0); return true; } _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f0); return false; } private boolean _jspx_meth_tiles_005finsert_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_sess_005fexistsAttribute_005f0, PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // tiles:insert org.apache.struts.taglib.tiles.InsertTag _jspx_th_tiles_005finsert_005f0 = (org.apache.struts.taglib.tiles.InsertTag) _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.get(org.apache.struts.taglib.tiles.InsertTag.class); _jspx_th_tiles_005finsert_005f0.setPageContext(_jspx_page_context); _jspx_th_tiles_005finsert_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_sess_005fexistsAttribute_005f0); // /payment/review.jsp(31,3) name = definition type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_tiles_005finsert_005f0.setDefinition("payment.review"); // /payment/review.jsp(31,3) name = flush type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_tiles_005finsert_005f0.setFlush(true); int _jspx_eval_tiles_005finsert_005f0 = _jspx_th_tiles_005finsert_005f0.doStartTag(); if (_jspx_th_tiles_005finsert_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f0); return true; } _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f0); return false; } private boolean _jspx_meth_sess_005fexistsAttribute_005f1(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // sess:existsAttribute org.apache.taglibs.session.ExistsAttributeTag _jspx_th_sess_005fexistsAttribute_005f1 = (org.apache.taglibs.session.ExistsAttributeTag) _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.get(org.apache.taglibs.session.ExistsAttributeTag.class); _jspx_th_sess_005fexistsAttribute_005f1.setPageContext(_jspx_page_context); _jspx_th_sess_005fexistsAttribute_005f1.setParent(null); // /payment/review.jsp(33,0) name = name type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_sess_005fexistsAttribute_005f1.setName("jsp_is_refund"); int _jspx_eval_sess_005fexistsAttribute_005f1 = _jspx_th_sess_005fexistsAttribute_005f1.doStartTag(); if (_jspx_eval_sess_005fexistsAttribute_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\r\n "); if (_jspx_meth_tiles_005finsert_005f1(_jspx_th_sess_005fexistsAttribute_005f1, _jspx_page_context)) return true; out.write('\r'); out.write('\n'); int evalDoAfterBody = _jspx_th_sess_005fexistsAttribute_005f1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_sess_005fexistsAttribute_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f1); return true; } _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f1); return false; } private boolean _jspx_meth_tiles_005finsert_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_sess_005fexistsAttribute_005f1, PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // tiles:insert org.apache.struts.taglib.tiles.InsertTag _jspx_th_tiles_005finsert_005f1 = (org.apache.struts.taglib.tiles.InsertTag) _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.get(org.apache.struts.taglib.tiles.InsertTag.class); _jspx_th_tiles_005finsert_005f1.setPageContext(_jspx_page_context); _jspx_th_tiles_005finsert_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_sess_005fexistsAttribute_005f1); // /payment/review.jsp(34,3) name = definition type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_tiles_005finsert_005f1.setDefinition("refund.review"); // /payment/review.jsp(34,3) name = flush type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null _jspx_th_tiles_005finsert_005f1.setFlush(true); int _jspx_eval_tiles_005finsert_005f1 = _jspx_th_tiles_005finsert_005f1.doStartTag(); if (_jspx_th_tiles_005finsert_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f1); return true; } _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f1); return false; } }
maduhu/knx-jbilling2.2.0
build/jsp-classes/com/sapienter/jbilling/client/jspc/payment/review_jsp.java
Java
agpl-3.0
11,647
/*@author Jvlaple *Crystal of Roots */ var status = 0; var PQItems = Array(4001087, 4001088, 4001089, 4001090, 4001091, 4001092, 4001093); importPackage(net.sf.odinms.client); function start() { status = -1; action(1, 0, 0); } function action(mode, type, selection) { if (mode == -1) { cm.dispose(); } else { if (status >= 0 && mode == 0) { cm.sendOk("Ok, keep preservering!"); cm.dispose(); return; } if (mode == 1) status++; else status--; if (status == 0 ) { cm.sendYesNo("Hello I'm the Dungeon Exit NPC. Do you wish to go out from here?"); } else if (status == 1) { var eim = cm.getPlayer().getEventInstance(); cm.warp(100000000, 0); if (eim != null) { eim.unregisterPlayer(cm.getPlayer()); }cm.dispose(); } } }
ZenityMS/forgottenstorysource
scripts/npc/2111005.js
JavaScript
agpl-3.0
1,027
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.forms.notificationdialog; public interface IFormUILogicCode { // No methods yet. }
open-health-hub/openmaxims-linux
openmaxims_workspace/Core/src/ims/core/forms/notificationdialog/IFormUILogicCode.java
Java
agpl-3.0
1,804
// Copyright 2014 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package v4 var ( BundleCharms = (*Handler).bundleCharms ParseSearchParams = parseSearchParams DefaultIcon = defaultIcon ArchiveCacheVersionedMaxAge = &archiveCacheVersionedMaxAge ArchiveCacheNonVersionedMaxAge = &archiveCacheNonVersionedMaxAge ParamsLogLevels = paramsLogLevels ParamsLogTypes = paramsLogTypes ProcessIcon = processIcon UsernameAttr = usernameAttr GroupsAttr = groupsAttr GetPromulgatedURL = (*Handler).getPromulgatedURL )
mhilton/charmstore
internal/v4/export_test.go
GO
agpl-3.0
699
# frozen_string_literal: true require "test_helper" module GobiertoAdmin class UserFormTest < ActiveSupport::TestCase def valid_user_form @valid_user_form ||= UserForm.new( id: user.id, name: user.name, bio: user.bio, email: user.email ) end def invalid_user_form @invalid_user_form ||= UserForm.new( name: nil, email: nil ) end def user @user ||= users(:reed) end def test_save_with_valid_attributes assert valid_user_form.save end def test_save_with_invalid_attributes refute invalid_user_form.save end def test_error_messages_with_invalid_attributes invalid_user_form.save assert_equal 1, invalid_user_form.errors.messages[:name].size assert_equal 1, invalid_user_form.errors.messages[:email].size end def test_confirmation_email_delivery_when_changing_email email_changing_form = UserForm.new( id: user.id, email: "wadus@gobierto.dev", name: "Wadus" ) assert_difference "ActionMailer::Base.deliveries.size", 1 do email_changing_form.save end end def test_confirmation_email_delivery_when_not_changing_email assert_no_difference "ActionMailer::Base.deliveries.size" do valid_user_form.save end end end end
PopulateTools/gobierto-dev
test/forms/gobierto_admin/user_form_test.rb
Ruby
agpl-3.0
1,372
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Silviu Checherita using IMS Development Environment (version 1.80 build 5567.19951) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. package ims.scheduling.domain.impl; import java.util.ArrayList; import java.util.List; import ims.domain.DomainFactory; import ims.domain.lookups.LookupInstance; import ims.scheduling.domain.base.impl.BaseReasonTextDialogImpl; import ims.scheduling.vo.lookups.CancelAppointmentReason; import ims.scheduling.vo.lookups.CancelAppointmentReasonCollection; import ims.scheduling.vo.lookups.Status_Reason; public class ReasonTextDialogImpl extends BaseReasonTextDialogImpl { private static final long serialVersionUID = 1L; //WDEV-21736 public CancelAppointmentReasonCollection listReasons() { DomainFactory factory = getDomainFactory(); ArrayList markers = new ArrayList(); ArrayList values = new ArrayList(); String hql = "SELECT r FROM CancellationTypeReason AS t LEFT JOIN t.cancellationReason as r WHERE t.cancellationType.id = :cancellationType AND r.active = 1"; markers.add("cancellationType"); values.add(Status_Reason.HOSPITALCANCELLED.getID()); List results = factory.find(hql.toString(), markers,values); if (results == null) return null; CancelAppointmentReasonCollection col = new CancelAppointmentReasonCollection(); for (int i=0; i<results.size(); i++) { CancelAppointmentReason reason = new CancelAppointmentReason(((LookupInstance) results.get(i)).getId(), ((LookupInstance) results.get(i)).getText(), ((LookupInstance) results.get(i)).isActive()); col.add(reason); } return col; } //WDEV-21736 ends here }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Scheduling/src/ims/scheduling/domain/impl/ReasonTextDialogImpl.java
Java
agpl-3.0
3,583
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.oncology.vo.lookups; import ims.framework.cn.data.TreeNode; import java.util.ArrayList; import ims.framework.utils.Image; import ims.framework.utils.Color; public class GradeofDifferentation extends ims.vo.LookupInstVo implements TreeNode { private static final long serialVersionUID = 1L; public GradeofDifferentation() { super(); } public GradeofDifferentation(int id) { super(id, "", true); } public GradeofDifferentation(int id, String text, boolean active) { super(id, text, active, null, null, null); } public GradeofDifferentation(int id, String text, boolean active, GradeofDifferentation parent, Image image) { super(id, text, active, parent, image); } public GradeofDifferentation(int id, String text, boolean active, GradeofDifferentation parent, Image image, Color color) { super(id, text, active, parent, image, color); } public GradeofDifferentation(int id, String text, boolean active, GradeofDifferentation parent, Image image, Color color, int order) { super(id, text, active, parent, image, color, order); } public static GradeofDifferentation buildLookup(ims.vo.LookupInstanceBean bean) { return new GradeofDifferentation(bean.getId(), bean.getText(), bean.isActive()); } public String toString() { if(getText() != null) return getText(); return ""; } public TreeNode getParentNode() { return (GradeofDifferentation)super.getParentInstance(); } public GradeofDifferentation getParent() { return (GradeofDifferentation)super.getParentInstance(); } public void setParent(GradeofDifferentation parent) { super.setParentInstance(parent); } public TreeNode[] getChildren() { ArrayList children = super.getChildInstances(); GradeofDifferentation[] typedChildren = new GradeofDifferentation[children.size()]; for (int i = 0; i < children.size(); i++) { typedChildren[i] = (GradeofDifferentation)children.get(i); } return typedChildren; } public int addChild(TreeNode child) { if (child instanceof GradeofDifferentation) { super.addChild((GradeofDifferentation)child); } return super.getChildInstances().size(); } public int removeChild(TreeNode child) { if (child instanceof GradeofDifferentation) { super.removeChild((GradeofDifferentation)child); } return super.getChildInstances().size(); } public Image getExpandedImage() { return super.getImage(); } public Image getCollapsedImage() { return super.getImage(); } public static ims.framework.IItemCollection getNegativeInstancesAsIItemCollection() { GradeofDifferentationCollection result = new GradeofDifferentationCollection(); return result; } public static GradeofDifferentation[] getNegativeInstances() { return new GradeofDifferentation[] {}; } public static String[] getNegativeInstanceNames() { return new String[] {}; } public static GradeofDifferentation getNegativeInstance(String name) { if(name == null) return null; // No negative instances found return null; } public static GradeofDifferentation getNegativeInstance(Integer id) { if(id == null) return null; // No negative instances found return null; } public int getTypeId() { return TYPE_ID; } public static final int TYPE_ID = 1251032; }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/oncology/vo/lookups/GradeofDifferentation.java
Java
agpl-3.0
5,476
/* * RapidMiner * * Copyright (C) 2001-2014 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ package com.rapid_i.deployment.update.client; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.rapid_i.deployment.update.client.listmodels.AbstractPackageListModel; import com.rapidminer.deployment.client.wsimport.PackageDescriptor; import com.rapidminer.deployment.client.wsimport.UpdateService; import com.rapidminer.gui.RapidMinerGUI; import com.rapidminer.gui.tools.ExtendedJScrollPane; import com.rapidminer.gui.tools.ProgressThread; import com.rapidminer.gui.tools.ResourceAction; import com.rapidminer.gui.tools.SwingTools; import com.rapidminer.gui.tools.dialogs.ButtonDialog; import com.rapidminer.gui.tools.dialogs.ConfirmDialog; import com.rapidminer.io.process.XMLTools; import com.rapidminer.tools.FileSystemService; import com.rapidminer.tools.I18N; import com.rapidminer.tools.LogService; import com.rapidminer.tools.ParameterService; import com.rapidminer.tools.XMLException; /** * The Dialog is eventually shown at the start of RapidMiner, if the user purchased extensions online but haven't installed them yet. * * @author Dominik Halfkann */ public class PendingPurchasesInstallationDialog extends ButtonDialog { private static final long serialVersionUID = 1L; private final PackageDescriptorCache packageDescriptorCache = new PackageDescriptorCache(); private AbstractPackageListModel purchasedModel = new PurchasedNotInstalledModel(packageDescriptorCache); JCheckBox neverAskAgain = new JCheckBox(I18N.getMessage(I18N.getGUIBundle(), "gui.dialog.purchased_not_installed.not_check_on_startup")); private final List<String> packages; private boolean isConfirmed; private LinkedList<PackageDescriptor> installablePackageList; private JButton remindNeverButton; private JButton remindLaterButton; private JButton okButton; private class PurchasedNotInstalledModel extends AbstractPackageListModel { private static final long serialVersionUID = 1L; public PurchasedNotInstalledModel(PackageDescriptorCache cache) { super(cache, "gui.dialog.update.tab.no_packages"); } @Override public List<String> handleFetchPackageNames() { return packages; } } public PendingPurchasesInstallationDialog(List<String> packages) { super("purchased_not_installed"); this.packages = packages; remindNeverButton = remindNeverButton(); remindLaterButton = remindLaterButton(); okButton = makeOkButton("install_purchased"); layoutDefault(makeContentPanel(), NORMAL, okButton, remindNeverButton, remindLaterButton); this.setPreferredSize(new Dimension(404, 430)); this.setMaximumSize(new Dimension(404, 430)); this.setMinimumSize(new Dimension(404, 300)); this.setSize(new Dimension(404, 430)); } private JPanel makeContentPanel() { BorderLayout layout = new BorderLayout(12, 12); JPanel panel = new JPanel(layout); panel.setBorder(new EmptyBorder(0, 12, 8, 12)); panel.add(createExtensionListScrollPane(purchasedModel), BorderLayout.CENTER); purchasedModel.update(); JPanel southPanel = new JPanel(new BorderLayout(0, 7)); JLabel question = new JLabel(I18N.getMessage(I18N.getGUIBundle(), "gui.dialog.purchased_not_installed.should_install")); southPanel.add(question, BorderLayout.CENTER); southPanel.add(neverAskAgain, BorderLayout.SOUTH); panel.add(southPanel, BorderLayout.SOUTH); return panel; } private JScrollPane createExtensionListScrollPane(AbstractPackageListModel model) { final JList updateList = new JList(model); updateList.setCellRenderer(new UpdateListCellRenderer(true)); JScrollPane extensionListScrollPane = new ExtendedJScrollPane(updateList); extensionListScrollPane.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); return extensionListScrollPane; } private JButton remindLaterButton() { Action Action = new ResourceAction("ask_later") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { wasConfirmed = false; checkNeverAskAgain(); close(); } }; getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "CLOSE"); getRootPane().getActionMap().put("CLOSE", Action); JButton button = new JButton(Action); getRootPane().setDefaultButton(button); return button; } private JButton remindNeverButton() { Action Action = new ResourceAction("ask_never") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { wasConfirmed = false; checkNeverAskAgain(); neverRemindAgain(); close(); } }; JButton button = new JButton(Action); getRootPane().setDefaultButton(button); return button; } @Override protected void ok() { checkNeverAskAgain(); startUpdate(getPackageDescriptorList()); dispose(); } public List<PackageDescriptor> getPackageDescriptorList() { List<PackageDescriptor> packageList = new ArrayList<PackageDescriptor>(); for (int a = 0; a < purchasedModel.getSize(); a++) { Object listItem = purchasedModel.getElementAt(a); if (listItem instanceof PackageDescriptor) { packageList.add((PackageDescriptor) listItem); } } return packageList; } public void startUpdate(final List<PackageDescriptor> downloadList) { final UpdateService service; try { service = UpdateManager.getService(); } catch (Exception e) { SwingTools.showSimpleErrorMessage("failed_update_server", e, UpdateManager.getBaseUrl()); return; } new ProgressThread("resolving_dependencies", true) { @Override public void run() { try { getProgressListener().setTotal(100); remindLaterButton.setEnabled(false); remindNeverButton.setEnabled(false); final HashMap<PackageDescriptor, HashSet<PackageDescriptor>> dependency = UpdateDialog.resolveDependency(downloadList, packageDescriptorCache); getProgressListener().setCompleted(30); installablePackageList = UpdateDialog.getPackagesforInstallation(dependency); final HashMap<String, String> licenseNameToLicenseTextMap = UpdateDialog.collectLicenses(installablePackageList,getProgressListener(),100,30,100); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { isConfirmed = ConfirmLicensesDialog.confirm(dependency, licenseNameToLicenseTextMap); new ProgressThread("installing_updates", true) { @Override public void run() { try { if (isConfirmed) { getProgressListener().setTotal(100); getProgressListener().setCompleted(20); UpdateService service = UpdateManager.getService(); UpdateManager um = new UpdateManager(service); List<PackageDescriptor> installedPackages = um.performUpdates(installablePackageList, getProgressListener()); getProgressListener().setCompleted(40); if (installedPackages.size() > 0) { int confirmation = SwingTools.showConfirmDialog((installedPackages.size() == 1 ? "update.complete_restart" : "update.complete_restart1"), ConfirmDialog.YES_NO_OPTION, installedPackages.size()); if (confirmation == ConfirmDialog.YES_OPTION) { RapidMinerGUI.getMainFrame().exit(true); } else if (confirmation == ConfirmDialog.NO_OPTION) { if (installedPackages.size() == installablePackageList.size()) { dispose(); } } } getProgressListener().complete(); } } catch (Exception e) { SwingTools.showSimpleErrorMessage("error_installing_update", e, e.getMessage()); } finally { getProgressListener().complete(); } } }.start(); } }); remindLaterButton.setEnabled(true); remindNeverButton.setEnabled(true); getProgressListener().complete(); } catch (Exception e) { SwingTools.showSimpleErrorMessage("error_resolving_dependencies", e, e.getMessage()); } } }.start(); } private void checkNeverAskAgain() { if (neverAskAgain.isSelected()) { ParameterService.setParameterValue(RapidMinerGUI.PROPERTY_RAPIDMINER_GUI_PURCHASED_NOT_INSTALLED_CHECK, "false"); ParameterService.saveParameters(); } } private void neverRemindAgain() { LogService.getRoot().log(Level.CONFIG, "com.rapid_i.deployment.update.client.PurchasedNotInstalledDialog.saving_ignored_extensions_file"); Document doc; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); } catch (ParserConfigurationException e) { LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapid_i.deployment.update.client.PurchasedNotInstalledDialog.creating_xml_document_error", e), e); return; } Element root = doc.createElement(UpdateManager.NEVER_REMIND_INSTALL_EXTENSIONS_FILE_NAME); doc.appendChild(root); for (String i : purchasedModel.fetchPackageNames()) { Element entryElem = doc.createElement("extension_name"); entryElem.setTextContent(i); root.appendChild(entryElem); } File file = FileSystemService.getUserConfigFile(UpdateManager.NEVER_REMIND_INSTALL_EXTENSIONS_FILE_NAME); try { XMLTools.stream(doc, file, null); } catch (XMLException e) { LogService.getRoot().log(Level.WARNING, I18N.getMessage(LogService.getRoot().getResourceBundle(), "com.rapid_i.deployment.update.client.PurchasedNotInstalledDialog.saving_ignored_extensions_file_error", e), e); } } }
rapidminer/rapidminer-5
src/com/rapid_i/deployment/update/client/PendingPurchasesInstallationDialog.java
Java
agpl-3.0
11,249
def _checkInput(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 base = 1 while current_index < index: old_base = current_number current_number = current_number + base base = old_base current_index += 1 pass return current_number def recursion(index): if index <= 1: return index return recursion(index - 1) + recursion(index - 2) def fib_from_recursion_func(index): _checkInput(index) return recursion(index) calculate = fib_from_recursion_func
feroda/lessons-python4beginners
students/2016-09-04/simone-cosma/fibonacci.py
Python
agpl-3.0
1,035
// Generated by CoffeeScript 1.10.0 var Bill, baseKonnector, filterExisting, linkBankOperation, ovhFetcher, saveDataAndFile; ovhFetcher = require('../lib/ovh_fetcher'); filterExisting = require('../lib/filter_existing'); saveDataAndFile = require('../lib/save_data_and_file'); linkBankOperation = require('../lib/link_bank_operation'); baseKonnector = require('../lib/base_konnector'); Bill = require('../models/bill'); module.exports = { createNew: function(ovhApi, name, slug) { var connector, fetchBills, fileOptions, logger, ovhFetcherInstance; fileOptions = { vendor: slug, dateFormat: 'YYYYMMDD' }; logger = require('printit')({ prefix: name, date: true }); ovhFetcherInstance = ovhFetcher["new"](ovhApi, slug, logger); fetchBills = function(requiredFields, entries, body, next) { return ovhFetcherInstance.fetchBills(requiredFields, entries, body, next); }; return connector = baseKonnector.createNew({ name: name, fields: { loginUrl: "link", token: "hidden", folderPath: "folder" }, models: [Bill], fetchOperations: [ fetchBills, filterExisting(logger, Bill), saveDataAndFile(logger, Bill, fileOptions, ['bill']), linkBankOperation({ log: logger, model: Bill, identifier: slug, dateDelta: 4, amountDelta: 0.1 }) ] }); } };
frankrousseau/konnectors
build/server/lib/base_ovh_konnector.js
JavaScript
agpl-3.0
1,438
class SubscribersController < ApplicationController def create @subscriber = Subscriber.new(params[:subscriber]) if @subscriber.save flash[:notice] = "Success! You have been sent a subscription email. Please click the confirmation link in that email to confirm your subscription."\ else flash[:error] = "We're having trouble with that email address. Either it's invalid or you have already signed up to watch this story." end redirect_to :back end def confirm @subscriber = Subscriber.find_by_invite_token(params[:id]) @subscriber.subscribe if @subscriber end def cancel @subscriber = Subscriber.find_by_invite_token(params[:id]) @subscriber.cancel if @subscriber end end
chandresh/spot-us
app/controllers/subscribers_controller.rb
Ruby
agpl-3.0
752
""" Braitenberg Vehicle2b The more light sensed on the left side the faster the right motor moves. The more light sensed on the right side the faster the left motor moves. This causes the robot to turn towards a light source. """ from pyrobot.brain import Brain, avg class Vehicle(Brain): def setup(self): self.robot.light[0].units = "SCALED" def step(self): leftSpeed = max([s.value for s in self.robot.light[0]["right"]]) rightSpeed = max([s.value for s in self.robot.light[0]["left"]]) print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed self.motors(leftSpeed, rightSpeed) def INIT(engine): if engine.robot.type not in ['K-Team', 'Pyrobot']: raise "Robot should have light sensors!" return Vehicle('Braitenberg2a', engine)
emilydolson/forestcat
pyrobot/plugins/brains/BraitenbergVehicle2b.py
Python
agpl-3.0
789
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as # //# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5589.25814) * WARNING: DO NOT MODIFY the content of this file * Generated on 12/10/2015, 13:25 * */ package ims.emergency.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Florin Blindu */ public class EDPartialAdmissionForDischargeDetailOutcomeVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo copy(ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObjectDest, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_EDPartialAdmission(valueObjectSrc.getID_EDPartialAdmission()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // DecisionToAdmitDateTime valueObjectDest.setDecisionToAdmitDateTime(valueObjectSrc.getDecisionToAdmitDateTime()); // Specialty valueObjectDest.setSpecialty(valueObjectSrc.getSpecialty()); // AllocatedStatus valueObjectDest.setAllocatedStatus(valueObjectSrc.getAllocatedStatus()); // AllocatedBedType valueObjectDest.setAllocatedBedType(valueObjectSrc.getAllocatedBedType()); // AuthoringInfo valueObjectDest.setAuthoringInfo(valueObjectSrc.getAuthoringInfo()); // AllocatedDateTime valueObjectDest.setAllocatedDateTime(valueObjectSrc.getAllocatedDateTime()); // AdmittingConsultant valueObjectDest.setAdmittingConsultant(valueObjectSrc.getAdmittingConsultant()); // AccomodationRequestedType valueObjectDest.setAccomodationRequestedType(valueObjectSrc.getAccomodationRequestedType()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.emergency.domain.objects.EDPartialAdmission objects. */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(java.util.Set domainObjectSet) { return createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.emergency.domain.objects.EDPartialAdmission objects. */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap map, java.util.Set domainObjectSet) { ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voList = new ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.emergency.domain.objects.EDPartialAdmission domainObject = (ims.emergency.domain.objects.EDPartialAdmission) iterator.next(); ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.emergency.domain.objects.EDPartialAdmission objects. */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(java.util.List domainObjectList) { return createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.emergency.domain.objects.EDPartialAdmission objects. */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap map, java.util.List domainObjectList) { ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voList = new ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.emergency.domain.objects.EDPartialAdmission domainObject = (ims.emergency.domain.objects.EDPartialAdmission) domainObjectList.get(i); ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.emergency.domain.objects.EDPartialAdmission set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractEDPartialAdmissionSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection) { return extractEDPartialAdmissionSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractEDPartialAdmissionSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = voCollection.get(i); ims.emergency.domain.objects.EDPartialAdmission domainObject = EDPartialAdmissionForDischargeDetailOutcomeVoAssembler.extractEDPartialAdmission(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.emergency.domain.objects.EDPartialAdmission list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractEDPartialAdmissionList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection) { return extractEDPartialAdmissionList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractEDPartialAdmissionList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = voCollection.get(i); ims.emergency.domain.objects.EDPartialAdmission domainObject = EDPartialAdmissionForDischargeDetailOutcomeVoAssembler.extractEDPartialAdmission(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.emergency.domain.objects.EDPartialAdmission object. * @param domainObject ims.emergency.domain.objects.EDPartialAdmission */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo create(ims.emergency.domain.objects.EDPartialAdmission domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.emergency.domain.objects.EDPartialAdmission object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo create(DomainObjectMap map, ims.emergency.domain.objects.EDPartialAdmission domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject = (ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo) map.getValueObject(domainObject, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo.class); if ( null == valueObject ) { valueObject = new ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.EDPartialAdmission */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo insert(ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject, ims.emergency.domain.objects.EDPartialAdmission domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.emergency.domain.objects.EDPartialAdmission */ public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo insert(DomainObjectMap map, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject, ims.emergency.domain.objects.EDPartialAdmission domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_EDPartialAdmission(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // DecisionToAdmitDateTime java.util.Date DecisionToAdmitDateTime = domainObject.getDecisionToAdmitDateTime(); if ( null != DecisionToAdmitDateTime ) { valueObject.setDecisionToAdmitDateTime(new ims.framework.utils.DateTime(DecisionToAdmitDateTime) ); } // Specialty ims.domain.lookups.LookupInstance instance2 = domainObject.getSpecialty(); if ( null != instance2 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance2.getImage() != null) { img = new ims.framework.utils.ImagePath(instance2.getImage().getImageId(), instance2.getImage().getImagePath()); } color = instance2.getColor(); if (color != null) color.getValue(); ims.core.vo.lookups.Specialty voLookup2 = new ims.core.vo.lookups.Specialty(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color); ims.core.vo.lookups.Specialty parentVoLookup2 = voLookup2; ims.domain.lookups.LookupInstance parent2 = instance2.getParent(); while (parent2 != null) { if (parent2.getImage() != null) { img = new ims.framework.utils.ImagePath(parent2.getImage().getImageId(), parent2.getImage().getImagePath() ); } else { img = null; } color = parent2.getColor(); if (color != null) color.getValue(); parentVoLookup2.setParent(new ims.core.vo.lookups.Specialty(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color)); parentVoLookup2 = parentVoLookup2.getParent(); parent2 = parent2.getParent(); } valueObject.setSpecialty(voLookup2); } // AllocatedStatus ims.domain.lookups.LookupInstance instance3 = domainObject.getAllocatedStatus(); if ( null != instance3 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance3.getImage() != null) { img = new ims.framework.utils.ImagePath(instance3.getImage().getImageId(), instance3.getImage().getImagePath()); } color = instance3.getColor(); if (color != null) color.getValue(); ims.emergency.vo.lookups.AllocationStatus voLookup3 = new ims.emergency.vo.lookups.AllocationStatus(instance3.getId(),instance3.getText(), instance3.isActive(), null, img, color); ims.emergency.vo.lookups.AllocationStatus parentVoLookup3 = voLookup3; ims.domain.lookups.LookupInstance parent3 = instance3.getParent(); while (parent3 != null) { if (parent3.getImage() != null) { img = new ims.framework.utils.ImagePath(parent3.getImage().getImageId(), parent3.getImage().getImagePath() ); } else { img = null; } color = parent3.getColor(); if (color != null) color.getValue(); parentVoLookup3.setParent(new ims.emergency.vo.lookups.AllocationStatus(parent3.getId(),parent3.getText(), parent3.isActive(), null, img, color)); parentVoLookup3 = parentVoLookup3.getParent(); parent3 = parent3.getParent(); } valueObject.setAllocatedStatus(voLookup3); } // AllocatedBedType ims.domain.lookups.LookupInstance instance4 = domainObject.getAllocatedBedType(); if ( null != instance4 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance4.getImage() != null) { img = new ims.framework.utils.ImagePath(instance4.getImage().getImageId(), instance4.getImage().getImagePath()); } color = instance4.getColor(); if (color != null) color.getValue(); ims.emergency.vo.lookups.AllocatedBedType voLookup4 = new ims.emergency.vo.lookups.AllocatedBedType(instance4.getId(),instance4.getText(), instance4.isActive(), null, img, color); ims.emergency.vo.lookups.AllocatedBedType parentVoLookup4 = voLookup4; ims.domain.lookups.LookupInstance parent4 = instance4.getParent(); while (parent4 != null) { if (parent4.getImage() != null) { img = new ims.framework.utils.ImagePath(parent4.getImage().getImageId(), parent4.getImage().getImagePath() ); } else { img = null; } color = parent4.getColor(); if (color != null) color.getValue(); parentVoLookup4.setParent(new ims.emergency.vo.lookups.AllocatedBedType(parent4.getId(),parent4.getText(), parent4.isActive(), null, img, color)); parentVoLookup4 = parentVoLookup4.getParent(); parent4 = parent4.getParent(); } valueObject.setAllocatedBedType(voLookup4); } // AuthoringInfo valueObject.setAuthoringInfo(ims.core.vo.domain.AuthoringInformationVoAssembler.create(map, domainObject.getAuthoringInfo()) ); // AllocatedDateTime java.util.Date AllocatedDateTime = domainObject.getAllocatedDateTime(); if ( null != AllocatedDateTime ) { valueObject.setAllocatedDateTime(new ims.framework.utils.DateTime(AllocatedDateTime) ); } // AdmittingConsultant valueObject.setAdmittingConsultant(ims.core.vo.domain.HcpMinVoAssembler.create(map, domainObject.getAdmittingConsultant()) ); // AccomodationRequestedType ims.domain.lookups.LookupInstance instance8 = domainObject.getAccomodationRequestedType(); if ( null != instance8 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance8.getImage() != null) { img = new ims.framework.utils.ImagePath(instance8.getImage().getImageId(), instance8.getImage().getImagePath()); } color = instance8.getColor(); if (color != null) color.getValue(); ims.core.vo.lookups.AccomodationRequestedType voLookup8 = new ims.core.vo.lookups.AccomodationRequestedType(instance8.getId(),instance8.getText(), instance8.isActive(), null, img, color); ims.core.vo.lookups.AccomodationRequestedType parentVoLookup8 = voLookup8; ims.domain.lookups.LookupInstance parent8 = instance8.getParent(); while (parent8 != null) { if (parent8.getImage() != null) { img = new ims.framework.utils.ImagePath(parent8.getImage().getImageId(), parent8.getImage().getImagePath() ); } else { img = null; } color = parent8.getColor(); if (color != null) color.getValue(); parentVoLookup8.setParent(new ims.core.vo.lookups.AccomodationRequestedType(parent8.getId(),parent8.getText(), parent8.isActive(), null, img, color)); parentVoLookup8 = parentVoLookup8.getParent(); parent8 = parent8.getParent(); } valueObject.setAccomodationRequestedType(voLookup8); } return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.emergency.domain.objects.EDPartialAdmission extractEDPartialAdmission(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject) { return extractEDPartialAdmission(domainFactory, valueObject, new HashMap()); } public static ims.emergency.domain.objects.EDPartialAdmission extractEDPartialAdmission(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_EDPartialAdmission(); ims.emergency.domain.objects.EDPartialAdmission domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.emergency.domain.objects.EDPartialAdmission)domMap.get(valueObject); } // ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo ID_EDPartialAdmission field is unknown domainObject = new ims.emergency.domain.objects.EDPartialAdmission(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_EDPartialAdmission()); if (domMap.get(key) != null) { return (ims.emergency.domain.objects.EDPartialAdmission)domMap.get(key); } domainObject = (ims.emergency.domain.objects.EDPartialAdmission) domainFactory.getDomainObject(ims.emergency.domain.objects.EDPartialAdmission.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_EDPartialAdmission()); ims.framework.utils.DateTime dateTime1 = valueObject.getDecisionToAdmitDateTime(); java.util.Date value1 = null; if ( dateTime1 != null ) { value1 = dateTime1.getJavaDate(); } domainObject.setDecisionToAdmitDateTime(value1); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value2 = null; if ( null != valueObject.getSpecialty() ) { value2 = domainFactory.getLookupInstance(valueObject.getSpecialty().getID()); } domainObject.setSpecialty(value2); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value3 = null; if ( null != valueObject.getAllocatedStatus() ) { value3 = domainFactory.getLookupInstance(valueObject.getAllocatedStatus().getID()); } domainObject.setAllocatedStatus(value3); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value4 = null; if ( null != valueObject.getAllocatedBedType() ) { value4 = domainFactory.getLookupInstance(valueObject.getAllocatedBedType().getID()); } domainObject.setAllocatedBedType(value4); // SaveAsRefVO - treated as a refVo in extract methods ims.core.clinical.domain.objects.AuthoringInformation value5 = null; if ( null != valueObject.getAuthoringInfo() ) { if (valueObject.getAuthoringInfo().getBoId() == null) { if (domMap.get(valueObject.getAuthoringInfo()) != null) { value5 = (ims.core.clinical.domain.objects.AuthoringInformation)domMap.get(valueObject.getAuthoringInfo()); } } else { value5 = (ims.core.clinical.domain.objects.AuthoringInformation)domainFactory.getDomainObject(ims.core.clinical.domain.objects.AuthoringInformation.class, valueObject.getAuthoringInfo().getBoId()); } } domainObject.setAuthoringInfo(value5); ims.framework.utils.DateTime dateTime6 = valueObject.getAllocatedDateTime(); java.util.Date value6 = null; if ( dateTime6 != null ) { value6 = dateTime6.getJavaDate(); } domainObject.setAllocatedDateTime(value6); // SaveAsRefVO - treated as a refVo in extract methods ims.core.resource.people.domain.objects.Hcp value7 = null; if ( null != valueObject.getAdmittingConsultant() ) { if (valueObject.getAdmittingConsultant().getBoId() == null) { if (domMap.get(valueObject.getAdmittingConsultant()) != null) { value7 = (ims.core.resource.people.domain.objects.Hcp)domMap.get(valueObject.getAdmittingConsultant()); } } else { value7 = (ims.core.resource.people.domain.objects.Hcp)domainFactory.getDomainObject(ims.core.resource.people.domain.objects.Hcp.class, valueObject.getAdmittingConsultant().getBoId()); } } domainObject.setAdmittingConsultant(value7); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value8 = null; if ( null != valueObject.getAccomodationRequestedType() ) { value8 = domainFactory.getLookupInstance(valueObject.getAccomodationRequestedType().getID()); } domainObject.setAccomodationRequestedType(value8); return domainObject; } }
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/EDPartialAdmissionForDischargeDetailOutcomeVoAssembler.java
Java
agpl-3.0
28,003
/* * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license: http://github.com/azerothcore/azerothcore-wotlk/LICENSE-GPL2 * Copyright (C) 2008-2016 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> */ #include "GameObjectAI.h" //GameObjectAI::GameObjectAI(GameObject* g) : go(g) {} int GameObjectAI::Permissible(const GameObject* go) { if (go->GetAIName() == "GameObjectAI") return PERMIT_BASE_SPECIAL; return PERMIT_BASE_NO; } NullGameObjectAI::NullGameObjectAI(GameObject* g) : GameObjectAI(g) {}
DantestyleXD/azerothcore-wotlk
src/game/AI/CoreAI/GameObjectAI.cpp
C++
agpl-3.0
609
class AddNameIndexToGames < ActiveRecord::Migration[4.2] def change add_index :games, :name end end
BatedUrGonnaDie/splits-io
db/migrate/20140925231311_add_name_index_to_games.rb
Ruby
agpl-3.0
108
<?php /** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. */ /** * @param array $params * @param $template * * @return bool|mixed|string */ function smarty_function_flink($params, $template) { $file = $params['file']; $request = Shopware()->Front()->Request(); $docPath = Shopware()->Container()->getParameter('shopware.app.rootdir'); // Check if we got an URI or a local link if (!empty($file) && strpos($file, '/') !== 0 && strpos($file, '://') === false) { $useIncludePath = $template->smarty->getUseIncludePath(); /** @var string[] $templateDirs */ $templateDirs = $template->smarty->getTemplateDir(); // Try to find the file on the filesystem foreach ($templateDirs as $dir) { if (file_exists($dir . $file)) { $file = Enlight_Loader::realpath($dir) . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $file); break; } if ($useIncludePath) { if ($dir === '.' . DIRECTORY_SEPARATOR) { $dir = ''; } if (($result = Enlight_Loader::isReadable($dir . $file)) !== false) { $file = $result; break; } } } // Some cleanup code if (strpos($file, $docPath) === 0) { $file = substr($file, strlen($docPath)); } // Make sure we have the right separator for the web context if (DIRECTORY_SEPARATOR !== '/') { $file = str_replace(DIRECTORY_SEPARATOR, '/', $file); } if (strpos($file, './') === 0) { $file = substr($file, 2); } if ($request !== null) { $file = $request->getBasePath() . '/' . ltrim($file, '/'); } } if (empty($file) && $request !== null) { $file = $request->getBasePath() . '/'; } if ($request !== null && !empty($params['fullPath']) && strpos($file, '/') === 0) { $file = $request->getScheme() . '://' . $request->getHttpHost() . $file; } return $file; }
simkli/shopware
engine/Library/Enlight/Template/Plugins/function.flink.php
PHP
agpl-3.0
3,003
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import store from './store' import VueBootstrap from 'bootstrap-vue' import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' Vue.use(VueBootstrap) // HTTP Client we use. import Axios from 'axios' // TODO: Set these during build time. Axios.defaults.baseURL = 'http://localhost:8080' Axios.defaults.headers['Content-Type'] = 'application/json; charset=UTF-8' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, template: '<App/>', components: { App } })
praelatus/backend
client/src/main.js
JavaScript
agpl-3.0
761
/* * Concept profile generation tool suite * Copyright (C) 2015 Biosemantics Group, Erasmus University Medical Center, * Rotterdam, The Netherlands * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package JochemBuilder.KEGGcompound; import org.erasmusmc.ontology.OntologyFileLoader; import org.erasmusmc.ontology.OntologyStore; import org.erasmusmc.ontology.ontologyutilities.OntologyCurator; import org.erasmusmc.utilities.StringUtilities; import JochemBuilder.SharedCurationScripts.CasperForJochem; import JochemBuilder.SharedCurationScripts.CurateUsingManualCurationFile; import JochemBuilder.SharedCurationScripts.RemoveDictAndCompanyNamesAtEndOfTerm; import JochemBuilder.SharedCurationScripts.RewriteFurther; import JochemBuilder.SharedCurationScripts.SaveOnlyCASandInchiEntries; public class KEGGcompoundImport { public static String date = "110809"; public static String home = "/home/khettne/Projects/Jochem"; public static String keggcImportFile = home+"/KEGG/Compound/compound"; public static String compoundToDrugMappingOutFile = home+"/KEGG/Compound/compoundToDrugMapping"; public static String keggcToInchiMappingFile = home+"/KEGG/Compound/compound.inchi"; public static String keggcDictionariesLog = home+"/KEGG/Compound/KEGGc_dictionaries_"+date+".log"; public static String keggcRewriteLog = home+"/KEGG/Compound/KEGGcCAS_casperFiltered_"+date+".log"; public static String keggcLowerCaseLog = home+"/KEGG/Compound/KEGGcCAS_lowerCase_"+date+".log"; public static String termsToRemove = "keggcTermsToRemove.txt"; public static String keggcCuratedOntologyPath = home+"/KEGG/Compound/KEGGcCAS_curated_"+date+".ontology"; public static String keggcCuratedLog = home+"/KEGG/Compound/KEGGcCAS_curated_"+date+".log"; public static void main(String[] args) { OntologyStore ontology = new OntologyStore(); OntologyFileLoader loader = new OntologyFileLoader(); //Make unprocessed thesaurus ChemicalsFromKEGGcompound keggchem = new ChemicalsFromKEGGcompound(); ontology = keggchem.run(keggcImportFile, compoundToDrugMappingOutFile); RemoveDictAndCompanyNamesAtEndOfTerm remove = new RemoveDictAndCompanyNamesAtEndOfTerm(); ontology = remove.run(ontology, keggcDictionariesLog); MapKEGGc2InChI mapOntology = new MapKEGGc2InChI(); ontology = mapOntology.map(ontology, keggcToInchiMappingFile); // CAS and InChI SaveOnlyCASandInchiEntries make = new SaveOnlyCASandInchiEntries(); ontology = make.run(ontology); //Rewrite CasperForJochem casper = new CasperForJochem(); casper.run(ontology, keggcRewriteLog); // Make some entries lower case and filter further RewriteFurther rewrite = new RewriteFurther(); ontology = rewrite.run(ontology, keggcLowerCaseLog); //Remove terms based on medline frequency CurateUsingManualCurationFile curate = new CurateUsingManualCurationFile(); ontology = curate.run(ontology, keggcCuratedLog,termsToRemove); //Set default flags and save ontology OntologyCurator curator = new OntologyCurator(); curator.curateAndPrepare(ontology); loader.save(ontology,keggcCuratedOntologyPath); System.out.println("Done! " + StringUtilities.now()); } }
BiosemanticsDotOrg/GeneDiseasePlosBio
java/DataImport/src/JochemBuilder/KEGGcompound/KEGGcompoundImport.java
Java
agpl-3.0
3,807
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. * */ package com.xpn.xwiki.objects; import java.io.IOException; import java.io.Serializable; import java.io.StringWriter; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.dom.DOMDocument; import org.dom4j.dom.DOMElement; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import com.xpn.xwiki.web.Utils; /** * @version $Id$ */ // TODO: shouldn't this be abstract? toFormString and toText // will never work unless getValue is overriden public class BaseProperty extends BaseElement implements PropertyInterface, Serializable, Cloneable { private BaseCollection object; private int id; /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#getObject() */ public BaseCollection getObject() { return this.object; } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#setObject(com.xpn.xwiki.objects.BaseCollection) */ public void setObject(BaseCollection object) { this.object = object; } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.BaseElement#equals(java.lang.Object) */ @Override public boolean equals(Object el) { // Same Java object, they sure are equal if (this == el) { return true; } // I hate this.. needed for hibernate to find the object // when loading the collections.. if ((this.object == null) || ((BaseProperty) el).getObject() == null) { return (hashCode() == el.hashCode()); } if (!super.equals(el)) { return false; } return (getId() == ((BaseProperty) el).getId()); } public int getId() { // I hate this.. needed for hibernate to find the object // when loading the collections.. if (this.object == null) { return this.id; } else { return getObject().getId(); } } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#setId(int) */ public void setId(int id) { // I hate this.. needed for hibernate to find the object // when loading the collections.. this.id = id; } /** * {@inheritDoc} * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { // I hate this.. needed for hibernate to find the object // when loading the collections.. return ("" + getId() + getName()).hashCode(); } public String getClassType() { return getClass().getName(); } public void setClassType(String type) { } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.BaseElement#clone() */ @Override public Object clone() { BaseProperty property = (BaseProperty) super.clone(); property.setObject(getObject()); return property; } public Object getValue() { return null; } public void setValue(Object value) { } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#toXML() */ public Element toXML() { Element el = new DOMElement(getName()); Object value = getValue(); el.setText((value == null) ? "" : value.toString()); return el; } /** * {@inheritDoc} * * @see com.xpn.xwiki.objects.PropertyInterface#toFormString() */ public String toFormString() { return Utils.formEncode(toText()); } public String toText() { Object value = getValue(); return (value == null) ? "" : value.toString(); } public String toXMLString() { Document doc = new DOMDocument(); doc.setRootElement(toXML()); OutputFormat outputFormat = new OutputFormat("", true); StringWriter out = new StringWriter(); XMLWriter writer = new XMLWriter(out, outputFormat); try { writer.write(doc); return out.toString(); } catch (IOException e) { e.printStackTrace(); return ""; } } /** * {@inheritDoc} * * @see java.lang.Object#toString() */ @Override public String toString() { return toXMLString(); } public Object getCustomMappingValue() { return getValue(); } }
xwiki-contrib/sankoreorg
xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/objects/BaseProperty.java
Java
lgpl-2.1
5,379
// --------------------------------------------------------------------- // // Copyright (C) 1999 - 2015 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- //TODO: Do neighbors for dx and povray smooth triangles ////////////////////////////////////////////////////////////////////// // Remarks on the implementations // // Variable names: in most functions, variable names have been // standardized in the following way: // // n1, n2, ni Number of points in coordinate direction 1, 2, i // will be 1 if i>=dim // // i1, i2, ii Loop variable running up to ni // // d1, d2, di Multiplicators for ii to find positions in the // array of nodes. ////////////////////////////////////////////////////////////////////// #include <deal.II/base/data_out_base.h> #include <deal.II/base/utilities.h> #include <deal.II/base/parameter_handler.h> #include <deal.II/base/thread_management.h> #include <deal.II/base/memory_consumption.h> #include <deal.II/base/std_cxx11/shared_ptr.h> #include <deal.II/base/mpi.h> #include <cstring> #include <algorithm> #include <iomanip> #include <ctime> #include <cmath> #include <set> #include <sstream> #include <fstream> // we use uint32_t and uint8_t below, which are declared here: #include <stdint.h> #ifdef DEAL_II_WITH_ZLIB # include <zlib.h> #endif #ifdef DEAL_II_WITH_HDF5 #include <hdf5.h> #endif DEAL_II_NAMESPACE_OPEN // we need the following exception from a global function, so can't declare it // in the usual way inside a class namespace { DeclException2 (ExcUnexpectedInput, std::string, std::string, << "Unexpected input: expected line\n <" << arg1 << ">\nbut got\n <" << arg2 << ">"); } namespace { #ifdef DEAL_II_WITH_ZLIB // the functions in this namespace are // taken from the libb64 project, see // http://sourceforge.net/projects/libb64 // // libb64 has been placed in the public // domain namespace base64 { typedef enum { step_A, step_B, step_C } base64_encodestep; typedef struct { base64_encodestep step; char result; } base64_encodestate; void base64_init_encodestate(base64_encodestate *state_in) { state_in->step = step_A; state_in->result = 0; } inline char base64_encode_value(char value_in) { static const char *encoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; if (value_in > 63) return '='; return encoding[(int)value_in]; } int base64_encode_block(const char *plaintext_in, int length_in, char *code_out, base64_encodestate *state_in) { const char *plainchar = plaintext_in; const char *const plaintextend = plaintext_in + length_in; char *codechar = code_out; char result; char fragment; result = state_in->result; switch (state_in->step) { while (1) { case step_A: if (plainchar == plaintextend) { state_in->result = result; state_in->step = step_A; return codechar - code_out; } fragment = *plainchar++; result = (fragment & 0x0fc) >> 2; *codechar++ = base64_encode_value(result); result = (fragment & 0x003) << 4; case step_B: if (plainchar == plaintextend) { state_in->result = result; state_in->step = step_B; return codechar - code_out; } fragment = *plainchar++; result |= (fragment & 0x0f0) >> 4; *codechar++ = base64_encode_value(result); result = (fragment & 0x00f) << 2; case step_C: if (plainchar == plaintextend) { state_in->result = result; state_in->step = step_C; return codechar - code_out; } fragment = *plainchar++; result |= (fragment & 0x0c0) >> 6; *codechar++ = base64_encode_value(result); result = (fragment & 0x03f) >> 0; *codechar++ = base64_encode_value(result); } } /* control should not reach here */ return codechar - code_out; } int base64_encode_blockend(char *code_out, base64_encodestate *state_in) { char *codechar = code_out; switch (state_in->step) { case step_B: *codechar++ = base64_encode_value(state_in->result); *codechar++ = '='; *codechar++ = '='; break; case step_C: *codechar++ = base64_encode_value(state_in->result); *codechar++ = '='; break; case step_A: break; } *codechar++ = '\0'; return codechar - code_out; } } /** * Do a base64 encoding of the given data. * * The function allocates memory as * necessary and returns a pointer to * it. The calling function must release * this memory again. */ char * encode_block (const char *data, const int data_size) { base64::base64_encodestate state; base64::base64_init_encodestate(&state); char *encoded_data = new char[2*data_size+1]; const int encoded_length_data = base64::base64_encode_block (data, data_size, encoded_data, &state); base64::base64_encode_blockend (encoded_data + encoded_length_data, &state); return encoded_data; } #endif #ifdef DEAL_II_WITH_ZLIB /** * Do a zlib compression followed * by a base64 encoding of the * given data. The result is then * written to the given stream. */ template <typename T> void write_compressed_block (const std::vector<T> &data, std::ostream &output_stream) { if (data.size() != 0) { // allocate a buffer for compressing // data and do so uLongf compressed_data_length = compressBound (data.size() * sizeof(T)); char *compressed_data = new char[compressed_data_length]; int err = compress2 ((Bytef *) compressed_data, &compressed_data_length, (const Bytef *) &data[0], data.size() * sizeof(T), Z_BEST_COMPRESSION); (void)err; Assert (err == Z_OK, ExcInternalError()); // now encode the compression header const uint32_t compression_header[4] = { 1, /* number of blocks */ (uint32_t)(data.size() * sizeof(T)), /* size of block */ (uint32_t)(data.size() * sizeof(T)), /* size of last block */ (uint32_t)compressed_data_length }; /* list of compressed sizes of blocks */ char *encoded_header = encode_block ((char *)&compression_header[0], 4 * sizeof(compression_header[0])); output_stream << encoded_header; delete[] encoded_header; // next do the compressed // data encoding in base64 char *encoded_data = encode_block (compressed_data, compressed_data_length); delete[] compressed_data; output_stream << encoded_data; delete[] encoded_data; } } #endif } // some declarations of functions and locally used classes namespace DataOutBase { namespace { /** * Class holding the data of one cell of a patch in two space * dimensions for output. It is the projection of a cell in * three-dimensional space (two coordinates, one height value) to * the direction of sight. */ class SvgCell { public: // Center of the cell (three-dimensional) Point<3> center; /** * Vector of vertices of this cell (three-dimensional) */ Point<3> vertices[4]; /** * Depth into the picture, which is defined as the distance from * an observer at an the origin in direction of the line of sight. */ float depth; /** * Vector of vertices of this cell (projected, two-dimensional). */ Point<2> projected_vertices[4]; // Center of the cell (projected, two-dimensional) Point<2> projected_center; /** * Comparison operator for sorting. */ bool operator < (const SvgCell &) const; }; bool SvgCell::operator < (const SvgCell &e) const { // note the "wrong" order in // which we sort the elements return depth > e.depth; } /** * Class holding the data of one cell of a patch in two space * dimensions for output. It is the projection of a cell in * three-dimensional space (two coordinates, one height value) to * the direction of sight. */ class EpsCell2d { public: /** * Vector of vertices of this cell. */ Point<2> vertices[4]; /** * Data value from which the actual colors will be computed by the * colorization function stated in the <tt>EpsFlags</tt> class. */ float color_value; /** * Depth into the picture, which is defined as the distance from * an observer at an the origin in direction of the line of sight. */ float depth; /** * Comparison operator for sorting. */ bool operator < (const EpsCell2d &) const; }; /** * This is a helper function for the write_gmv() function. There, * the data in the patches needs to be copied around as output is * one variable globally at a time, rather than all data on each * vertex at a time. This copying around can be done detached from * the main thread, and is thus moved into this separate function. * * Note that because of the similarity of the formats, this function * is also used by the Vtk and Tecplot output functions. */ template <int dim, int spacedim> void write_gmv_reorder_data_vectors (const std::vector<Patch<dim,spacedim> > &patches, Table<2,double> &data_vectors) { // unlike in the main function, we // don't have here the data_names // field, so we initialize it with // the number of data sets in the // first patch. the equivalence of // these two definitions is checked // in the main function. // we have to take care, however, whether the // points are appended to the end of the // patch->data table const unsigned int n_data_sets =patches[0].points_are_available ? (patches[0].data.n_rows() - spacedim) : patches[0].data.n_rows(); Assert (data_vectors.size()[0] == n_data_sets, ExcInternalError()); // loop over all patches unsigned int next_value = 0; for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch != patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; (void)n_subdivisions; Assert ((patch->data.n_rows() == n_data_sets && !patch->points_are_available) || (patch->data.n_rows() == n_data_sets+spacedim && patch->points_are_available), ExcDimensionMismatch (patch->points_are_available ? (n_data_sets + spacedim) : n_data_sets, patch->data.n_rows())); Assert ((n_data_sets == 0) || (patch->data.n_cols() == Utilities::fixed_power<dim>(n_subdivisions+1)), ExcInvalidDatasetSize (patch->data.n_cols(), n_subdivisions+1)); for (unsigned int i=0; i<patch->data.n_cols(); ++i, ++next_value) for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) data_vectors[data_set][next_value] = patch->data(data_set,i); } for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) Assert (data_vectors[data_set].size() == next_value, ExcInternalError()); } } } //----------------------------------------------------------------------// // DataOutFilter class member functions //----------------------------------------------------------------------// template<int dim> void DataOutBase::DataOutFilter::write_point(const unsigned int &index, const Point<dim> &p) { Map3DPoint::const_iterator it; unsigned int internal_ind; Point<3> int_pt; for (int d=0; d<3; ++d) int_pt(d) = (d < dim ? p(d) : 0); node_dim = dim; it = existing_points.find(int_pt); // If the point isn't in the set, or we're not filtering duplicate points, add it if (it == existing_points.end() || !flags.filter_duplicate_vertices) { internal_ind = existing_points.size(); existing_points.insert(std::make_pair(int_pt, internal_ind)); } else { internal_ind = it->second; } // Now add the index to the list of filtered points filtered_points[index] = internal_ind; } void DataOutBase::DataOutFilter::internal_add_cell(const unsigned int &cell_index, const unsigned int &pt_index) { filtered_cells[cell_index] = filtered_points[pt_index]; } void DataOutBase::DataOutFilter::fill_node_data(std::vector<double> &node_data) const { Map3DPoint::const_iterator it; node_data.resize(existing_points.size()*node_dim); for (it=existing_points.begin(); it!=existing_points.end(); ++it) { for (int d=0; d<node_dim; ++d) node_data[node_dim*it->second+d] = it->first(d); } } void DataOutBase::DataOutFilter::fill_cell_data(const unsigned int &local_node_offset, std::vector<unsigned int> &cell_data) const { std::map<unsigned int, unsigned int>::const_iterator it; cell_data.resize(filtered_cells.size()); for (it=filtered_cells.begin(); it!=filtered_cells.end(); ++it) { cell_data[it->first] = it->second+local_node_offset; } } template<int dim> void DataOutBase::DataOutFilter::write_cell( unsigned int index, unsigned int start, unsigned int d1, unsigned int d2, unsigned int d3) { unsigned int base_entry = index * GeometryInfo<dim>::vertices_per_cell; n_cell_verts = GeometryInfo<dim>::vertices_per_cell; internal_add_cell(base_entry+0, start); internal_add_cell(base_entry+1, start+d1); if (dim>=2) { internal_add_cell(base_entry+2, start+d2+d1); internal_add_cell(base_entry+3, start+d2); if (dim>=3) { internal_add_cell(base_entry+4, start+d3); internal_add_cell(base_entry+5, start+d3+d1); internal_add_cell(base_entry+6, start+d3+d2+d1); internal_add_cell(base_entry+7, start+d3+d2); } } } void DataOutBase::DataOutFilter::write_data_set(const std::string &name, const unsigned int &dimension, const unsigned int &set_num, const Table<2,double> &data_vectors) { unsigned int num_verts = existing_points.size(); unsigned int i, r, d, new_dim; // HDF5/XDMF output only supports 1D or 3D output, so force rearrangement if needed if (flags.xdmf_hdf5_output && dimension != 1) new_dim = 3; else new_dim = dimension; // Record the data set name, dimension, and allocate space for it data_set_names.push_back(name); data_set_dims.push_back(new_dim); data_sets.push_back(std::vector<double>(new_dim*num_verts)); // TODO: averaging, min/max, etc for merged vertices for (i=0; i<filtered_points.size(); ++i) { for (d=0; d<new_dim; ++d) { r = filtered_points[i]; if (d < dimension) data_sets.back()[r*new_dim+d] = data_vectors(set_num+d, i); else data_sets.back()[r*new_dim+d] = 0; } } } //----------------------------------------------------------------------// //Auxiliary data //----------------------------------------------------------------------// namespace { const char *gmv_cell_type[4] = { "", "line 2", "quad 4", "hex 8" }; const char *ucd_cell_type[4] = { "", "line", "quad", "hex" }; const char *tecplot_cell_type[4] = { "", "lineseg", "quadrilateral", "brick" }; #ifdef DEAL_II_HAVE_TECPLOT const unsigned int tecplot_binary_cell_type[4] = { 0, 0, 1, 3 }; #endif // NOTE: The dimension of the array is choosen to 5 to allow the choice // DataOutBase<deal_II_dimension,deal_II_dimension+1> in general // Wolfgang supposed that we don't need it in general, but however this // choice avoids a -Warray-bounds check warning const unsigned int vtk_cell_type[5] = { 0, 3, 9, 12, static_cast<unsigned int>(-1) }; //----------------------------------------------------------------------// //Auxiliary functions //----------------------------------------------------------------------// //For a given patch, compute the node interpolating the corner nodes //linearly at the point (xstep, ystep, zstep)*1./n_subdivisions. //If the points are saved in the patch->data member, return the //saved point instead //TODO: Make this function return its value, rather than using a reference // as first argument; take a reference for 'patch', not a pointer template <int dim, int spacedim> inline void compute_node( Point<spacedim> &node, const DataOutBase::Patch<dim,spacedim> *patch, const unsigned int xstep, const unsigned int ystep, const unsigned int zstep, const unsigned int n_subdivisions) { if (patch->points_are_available) { unsigned int point_no=0; // note: switch without break ! switch (dim) { case 3: Assert (zstep<n_subdivisions+1, ExcIndexRange(zstep,0,n_subdivisions+1)); point_no+=(n_subdivisions+1)*(n_subdivisions+1)*zstep; case 2: Assert (ystep<n_subdivisions+1, ExcIndexRange(ystep,0,n_subdivisions+1)); point_no+=(n_subdivisions+1)*ystep; case 1: Assert (xstep<n_subdivisions+1, ExcIndexRange(xstep,0,n_subdivisions+1)); point_no+=xstep; // break here for dim<=3 break; default: Assert (false, ExcNotImplemented()); } for (unsigned int d=0; d<spacedim; ++d) node[d]=patch->data(patch->data.size(0)-spacedim+d,point_no); } else { // perform a dim-linear interpolation const double stepsize=1./n_subdivisions, xfrac=xstep*stepsize; node = (patch->vertices[1] * xfrac) + (patch->vertices[0] * (1-xfrac)); if (dim>1) { const double yfrac=ystep*stepsize; node*= 1-yfrac; node += ((patch->vertices[3] * xfrac) + (patch->vertices[2] * (1-xfrac))) * yfrac; if (dim>2) { const double zfrac=zstep*stepsize; node *= (1-zfrac); node += (((patch->vertices[5] * xfrac) + (patch->vertices[4] * (1-xfrac))) * (1-yfrac) + ((patch->vertices[7] * xfrac) + (patch->vertices[6] * (1-xfrac))) * yfrac) * zfrac; } } } } template<int dim, int spacedim> static void compute_sizes(const std::vector<DataOutBase::Patch<dim, spacedim> > &patches, unsigned int &n_nodes, unsigned int &n_cells) { n_nodes = 0; n_cells = 0; for (typename std::vector<DataOutBase::Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { n_nodes += Utilities::fixed_power<dim>(patch->n_subdivisions+1); n_cells += Utilities::fixed_power<dim>(patch->n_subdivisions); } } /** * Class for writing basic * entities in @ref * SoftwareOpenDX format, * depending on the flags. */ class DXStream { public: /** * Constructor, storing * persistent values for * later use. */ DXStream (std::ostream &stream, const DataOutBase::DXFlags flags); /** * Output operator for points. */ template <int dim> void write_point (const unsigned int index, const Point<dim> &); /** * Do whatever is necessary to * terminate the list of points. */ void flush_points (); /** * Write dim-dimensional cell * with first vertex at * number start and further * vertices offset by the * specified values. Values * not needed are ignored. * * The order of vertices for * these cells in different * dimensions is * <ol> * <li> [0,1] * <li> [0,2,1,3] * <li> [0,4,2,6,1,5,3,7] * </ol> */ template <int dim> void write_cell (const unsigned int index, const unsigned int start, const unsigned int x_offset, const unsigned int y_offset, const unsigned int z_offset); /** * Do whatever is necessary to * terminate the list of cells. */ void flush_cells (); /** * Write a complete set of * data for a single node. * * The index given as first * argument indicates the * number of a data set, as * some output formats require * this number to be printed. */ template<typename data> void write_dataset (const unsigned int index, const std::vector<data> &values); /** * Forwarding of output stream */ template <typename T> std::ostream &operator<< (const T &); private: /** * The ostream to use. Since * the life span of these * objects is small, we use a * very simple storage * technique. */ std::ostream &stream; /** * The flags controlling the output */ const DataOutBase::DXFlags flags; }; /** * Class for writing basic * entities in @ref SoftwareGMV * format, depending on the * flags. */ class GmvStream { public: /** * Constructor, storing * persistent values for * later use. */ GmvStream (std::ostream &stream, const DataOutBase::GmvFlags flags); /** * Output operator for points. */ template <int dim> void write_point (const unsigned int index, const Point<dim> &); /** * Do whatever is necessary to * terminate the list of points. */ void flush_points (); /** * Write dim-dimensional cell * with first vertex at * number start and further * vertices offset by the * specified values. Values * not needed are ignored. * * The order of vertices for * these cells in different * dimensions is * <ol> * <li> [0,1] * <li> [0,1,3,2] * <li> [0,1,3,2,4,5,7,6] * </ol> */ template <int dim> void write_cell(const unsigned int index, const unsigned int start, const unsigned int x_offset, const unsigned int y_offset, const unsigned int z_offset); /** * Do whatever is necessary to * terminate the list of cells. */ void flush_cells (); /** * Forwarding of output stream */ template <typename T> std::ostream &operator<< (const T &); /** * Since GMV reads the x, y * and z coordinates in * separate fields, we enable * write() to output only a * single selected component * at once and do this dim * times for the whole set of * nodes. This integer can be * used to select the * component written. */ unsigned int selected_component; private: /** * The ostream to use. Since * the life span of these * objects is small, we use a * very simple storage * technique. */ std::ostream &stream; /** * The flags controlling the output */ const DataOutBase::GmvFlags flags; }; /** * Class for writing basic * entities in @ref * SoftwareTecplot format, * depending on the flags. */ class TecplotStream { public: /** * Constructor, storing * persistent values for * later use. */ TecplotStream (std::ostream &stream, const DataOutBase::TecplotFlags flags); /** * Output operator for points. */ template <int dim> void write_point (const unsigned int index, const Point<dim> &); /** * Do whatever is necessary to * terminate the list of points. */ void flush_points (); /** * Write dim-dimensional cell * with first vertex at * number start and further * vertices offset by the * specified values. Values * not needed are ignored. * * The order of vertices for * these cells in different * dimensions is * <ol> * <li> [0,1] * <li> [0,1,3,2] * <li> [0,1,3,2,4,5,7,6] * </ol> */ template <int dim> void write_cell(const unsigned int index, const unsigned int start, const unsigned int x_offset, const unsigned int y_offset, const unsigned int z_offset); /** * Do whatever is necessary to * terminate the list of cells. */ void flush_cells (); /** * Forwarding of output stream */ template <typename T> std::ostream &operator<< (const T &); /** * Since TECPLOT reads the x, y * and z coordinates in * separate fields, we enable * write() to output only a * single selected component * at once and do this dim * times for the whole set of * nodes. This integer can be * used to select the * component written. */ unsigned int selected_component; private: /** * The ostream to use. Since * the life span of these * objects is small, we use a * very simple storage * technique. */ std::ostream &stream; /** * The flags controlling the output */ const DataOutBase::TecplotFlags flags; }; /** * Class for writing basic * entities in UCD format for * @ref SoftwareAVS, depending on * the flags. */ class UcdStream { public: /** * Constructor, storing * persistent values for * later use. */ UcdStream (std::ostream &stream, const DataOutBase::UcdFlags flags); /** * Output operator for points. */ template <int dim> void write_point (const unsigned int index, const Point<dim> &); /** * Do whatever is necessary to * terminate the list of points. */ void flush_points (); /** * Write dim-dimensional cell * with first vertex at * number start and further * vertices offset by the * specified values. Values * not needed are ignored. * * The additional offset 1 is * added inside this * function. * * The order of vertices for * these cells in different * dimensions is * <ol> * <li> [0,1] * <li> [0,1,3,2] * <li> [0,1,5,4,2,3,7,6] * </ol> */ template <int dim> void write_cell(const unsigned int index, const unsigned int start, const unsigned int x_offset, const unsigned int y_offset, const unsigned int z_offset); /** * Do whatever is necessary to * terminate the list of cells. */ void flush_cells (); /** * Write a complete set of * data for a single node. * * The index given as first * argument indicates the * number of a data set, as * some output formats require * this number to be printed. */ template<typename data> void write_dataset (const unsigned int index, const std::vector<data> &values); /** * Forwarding of output stream */ template <typename T> std::ostream &operator<< (const T &); private: /** * The ostream to use. Since * the life span of these * objects is small, we use a * very simple storage * technique. */ std::ostream &stream; /** * The flags controlling the output */ const DataOutBase::UcdFlags flags; }; /** * Class for writing basic * entities in @ref SoftwareVTK * format, depending on the * flags. */ class VtkStream { public: /** * Constructor, storing * persistent values for * later use. */ VtkStream (std::ostream &stream, const DataOutBase::VtkFlags flags); /** * Output operator for points. */ template <int dim> void write_point (const unsigned int index, const Point<dim> &); /** * Do whatever is necessary to * terminate the list of points. */ void flush_points (); /** * Write dim-dimensional cell * with first vertex at * number start and further * vertices offset by the * specified values. Values * not needed are ignored. * * The order of vertices for * these cells in different * dimensions is * <ol> * <li> [0,1] * <li> [] * <li> [] * </ol> */ template <int dim> void write_cell(const unsigned int index, const unsigned int start, const unsigned int x_offset, const unsigned int y_offset, const unsigned int z_offset); /** * Do whatever is necessary to * terminate the list of cells. */ void flush_cells (); /** * Forwarding of output stream */ template <typename T> std::ostream &operator<< (const T &); private: /** * The ostream to use. Since * the life span of these * objects is small, we use a * very simple storage * technique. */ std::ostream &stream; /** * The flags controlling the output */ const DataOutBase::VtkFlags flags; }; class VtuStream { public: /** * Constructor, storing * persistent values for * later use. */ VtuStream (std::ostream &stream, const DataOutBase::VtkFlags flags); /** * Output operator for points. */ template <int dim> void write_point (const unsigned int index, const Point<dim> &); /** * Do whatever is necessary to * terminate the list of points. */ void flush_points (); /** * Write dim-dimensional cell * with first vertex at * number start and further * vertices offset by the * specified values. Values * not needed are ignored. * * The order of vertices for * these cells in different * dimensions is * <ol> * <li> [0,1] * <li> [] * <li> [] * </ol> */ template <int dim> void write_cell(const unsigned int index, const unsigned int start, const unsigned int x_offset, const unsigned int y_offset, const unsigned int z_offset); /** * Do whatever is necessary to * terminate the list of cells. */ void flush_cells (); /** * Forwarding of output stream */ template <typename T> std::ostream &operator<< (const T &); /** * Forwarding of output stream. * * If libz was found during * configuration, this operator * compresses and encodes the * entire data * block. Otherwise, it simply * writes it element by * element. */ template <typename T> std::ostream &operator<< (const std::vector<T> &); private: /** * The ostream to use. Since * the life span of these * objects is small, we use a * very simple storage * technique. */ std::ostream &stream; /** * The flags controlling the output */ const DataOutBase::VtkFlags flags; /** * A list of vertices and * cells, to be used in case we * want to compress the data. * * The data types of these * arrays needs to match what * we print in the XML-preamble * to the respective parts of * VTU files (e.g. Float64 and * Int32) */ std::vector<double> vertices; std::vector<int32_t> cells; }; //----------------------------------------------------------------------// DXStream::DXStream(std::ostream &out, const DataOutBase::DXFlags f) : stream(out), flags(f) {} template<int dim> void DXStream::write_point (const unsigned int, const Point<dim> &p) { if (flags.coordinates_binary) { float data[dim]; for (unsigned int d=0; d<dim; ++d) data[d] = p(d); stream.write(reinterpret_cast<const char *>(data), dim * sizeof(*data)); } else { for (unsigned int d=0; d<dim; ++d) stream << p(d) << '\t'; stream << '\n'; } } void DXStream::flush_points () {} template<int dim> void DXStream::write_cell( unsigned int, unsigned int start, unsigned int d1, unsigned int d2, unsigned int d3) { int nodes[1<<dim]; nodes[GeometryInfo<dim>::dx_to_deal[0]] = start; nodes[GeometryInfo<dim>::dx_to_deal[1]] = start+d1; if (dim>=2) { // Add shifted line in y direction nodes[GeometryInfo<dim>::dx_to_deal[2]] = start+d2; nodes[GeometryInfo<dim>::dx_to_deal[3]] = start+d2+d1; if (dim>=3) { // Add shifted quad in z direction nodes[GeometryInfo<dim>::dx_to_deal[4]] = start+d3; nodes[GeometryInfo<dim>::dx_to_deal[5]] = start+d3+d1; nodes[GeometryInfo<dim>::dx_to_deal[6]] = start+d3+d2; nodes[GeometryInfo<dim>::dx_to_deal[7]] = start+d3+d2+d1; } } if (flags.int_binary) stream.write(reinterpret_cast<const char *>(nodes), (1<<dim) * sizeof(*nodes)); else { const unsigned int final = (1<<dim) - 1; for (unsigned int i=0; i<final ; ++i) stream << nodes[i] << '\t'; stream << nodes[final] << '\n'; } } void DXStream::flush_cells () {} template<typename data> inline void DXStream::write_dataset(const unsigned int /*index*/, const std::vector<data> &values) { if (flags.data_binary) { stream.write(reinterpret_cast<const char *>(&values[0]), values.size()*sizeof(data)); } else { for (unsigned int i=0; i<values.size(); ++i) stream << '\t' << values[i]; stream << '\n'; } } //----------------------------------------------------------------------// GmvStream::GmvStream (std::ostream &out, const DataOutBase::GmvFlags f) : selected_component(numbers::invalid_unsigned_int), stream(out), flags(f) {} template<int dim> void GmvStream::write_point (const unsigned int, const Point<dim> &p) { Assert(selected_component != numbers::invalid_unsigned_int, ExcNotInitialized()); stream << p(selected_component) << ' '; } void GmvStream::flush_points () {} template<int dim> void GmvStream::write_cell( unsigned int, unsigned int s, unsigned int d1, unsigned int d2, unsigned int d3) { // Vertices are numbered starting // with one. const unsigned int start=s+1; stream << gmv_cell_type[dim] << '\n'; stream << start << '\t' << start+d1; if (dim>=2) { stream << '\t' << start+d2+d1 << '\t' << start+d2; if (dim>=3) { stream << '\t' << start+d3 << '\t' << start+d3+d1 << '\t' << start+d3+d2+d1 << '\t' << start+d3+d2; } } stream << '\n'; } void GmvStream::flush_cells () {} //----------------------------------------------------------------------// TecplotStream::TecplotStream(std::ostream &out, const DataOutBase::TecplotFlags f) : selected_component(numbers::invalid_unsigned_int), stream(out), flags(f) {} template<int dim> void TecplotStream::write_point (const unsigned int, const Point<dim> &p) { Assert(selected_component != numbers::invalid_unsigned_int, ExcNotInitialized()); stream << p(selected_component) << '\n'; } void TecplotStream::flush_points () {} template<int dim> void TecplotStream::write_cell( unsigned int, unsigned int s, unsigned int d1, unsigned int d2, unsigned int d3) { const unsigned int start = s+1; stream << start << '\t' << start+d1; if (dim>=2) { stream << '\t' << start+d2+d1 << '\t' << start+d2; if (dim>=3) { stream << '\t' << start+d3 << '\t' << start+d3+d1 << '\t' << start+d3+d2+d1 << '\t' << start+d3+d2; } } stream << '\n'; } void TecplotStream::flush_cells () {} //----------------------------------------------------------------------// UcdStream::UcdStream(std::ostream &out, const DataOutBase::UcdFlags f) : stream(out), flags(f) {} template<int dim> void UcdStream::write_point (const unsigned int index, const Point<dim> &p) { stream << index+1 << " "; // write out coordinates for (unsigned int i=0; i<dim; ++i) stream << p(i) << ' '; // fill with zeroes for (unsigned int i=dim; i<3; ++i) stream << "0 "; stream << '\n'; } void UcdStream::flush_points () {} template<int dim> void UcdStream::write_cell( unsigned int index, unsigned int start, unsigned int d1, unsigned int d2, unsigned int d3) { int nodes[1<<dim]; nodes[GeometryInfo<dim>::ucd_to_deal[0]] = start; nodes[GeometryInfo<dim>::ucd_to_deal[1]] = start+d1; if (dim>=2) { // Add shifted line in y direction nodes[GeometryInfo<dim>::ucd_to_deal[2]] = start+d2; nodes[GeometryInfo<dim>::ucd_to_deal[3]] = start+d2+d1; if (dim>=3) { // Add shifted quad in z direction nodes[GeometryInfo<dim>::ucd_to_deal[4]] = start+d3; nodes[GeometryInfo<dim>::ucd_to_deal[5]] = start+d3+d1; nodes[GeometryInfo<dim>::ucd_to_deal[6]] = start+d3+d2; nodes[GeometryInfo<dim>::ucd_to_deal[7]] = start+d3+d2+d1; } } // Write out all cells and remember // that all indices must be shifted // by one. stream << index+1 << "\t0 " << ucd_cell_type[dim]; const unsigned int final = (1<<dim); for (unsigned int i=0; i<final ; ++i) stream << '\t' << nodes[i]+1; stream << '\n'; } void UcdStream::flush_cells () {} template<typename data> inline void UcdStream::write_dataset(const unsigned int index, const std::vector<data> &values) { stream << index+1; for (unsigned int i=0; i<values.size(); ++i) stream << '\t' << values[i]; stream << '\n'; } //----------------------------------------------------------------------// VtkStream::VtkStream(std::ostream &out, const DataOutBase::VtkFlags f) : stream(out), flags(f) {} template<int dim> void VtkStream::write_point (const unsigned int, const Point<dim> &p) { // write out coordinates stream << p; // fill with zeroes for (unsigned int i=dim; i<3; ++i) stream << " 0"; stream << '\n'; } void VtkStream::flush_points () {} template<int dim> void VtkStream::write_cell( unsigned int, unsigned int start, unsigned int d1, unsigned int d2, unsigned int d3) { stream << GeometryInfo<dim>::vertices_per_cell << '\t' << start << '\t' << start+d1; if (dim>=2) { stream << '\t' << start+d2+d1 << '\t' << start+d2; if (dim>=3) { stream << '\t' << start+d3 << '\t' << start+d3+d1 << '\t' << start+d3+d2+d1 << '\t' << start+d3+d2; } } stream << '\n'; } void VtkStream::flush_cells () {} VtuStream::VtuStream(std::ostream &out, const DataOutBase::VtkFlags f) : stream(out), flags(f) {} template<int dim> void VtuStream::write_point (const unsigned int, const Point<dim> &p) { #if !defined(DEAL_II_WITH_ZLIB) // write out coordinates stream << p; // fill with zeroes for (unsigned int i=dim; i<3; ++i) stream << " 0"; stream << '\n'; #else // if we want to compress, then // first collect all the data in // an array for (unsigned int i=0; i<dim; ++i) vertices.push_back(p[i]); for (unsigned int i=dim; i<3; ++i) vertices.push_back(0); #endif } void VtuStream::flush_points () { #ifdef DEAL_II_WITH_ZLIB // compress the data we have in // memory and write them to the // stream. then release the data *this << vertices << '\n'; vertices.clear (); #endif } template<int dim> void VtuStream::write_cell( unsigned int, unsigned int start, unsigned int d1, unsigned int d2, unsigned int d3) { #if !defined(DEAL_II_WITH_ZLIB) stream << start << '\t' << start+d1; if (dim>=2) { stream << '\t' << start+d2+d1 << '\t' << start+d2; if (dim>=3) { stream << '\t' << start+d3 << '\t' << start+d3+d1 << '\t' << start+d3+d2+d1 << '\t' << start+d3+d2; } } stream << '\n'; #else cells.push_back (start); cells.push_back (start+d1); if (dim>=2) { cells.push_back (start+d2+d1); cells.push_back (start+d2); if (dim>=3) { cells.push_back (start+d3); cells.push_back (start+d3+d1); cells.push_back (start+d3+d2+d1); cells.push_back (start+d3+d2); } } #endif } void VtuStream::flush_cells () { #ifdef DEAL_II_WITH_ZLIB // compress the data we have in // memory and write them to the // stream. then release the data *this << cells << '\n'; cells.clear (); #endif } template <typename T> std::ostream & VtuStream::operator<< (const std::vector<T> &data) { #ifdef DEAL_II_WITH_ZLIB // compress the data we have in // memory and write them to the // stream. then release the data write_compressed_block (data, stream); #else for (unsigned int i=0; i<data.size(); ++i) stream << data[i] << ' '; #endif return stream; } template <typename T> std::ostream & DXStream::operator<< (const T &t) { stream << t; return stream; } template <typename T> std::ostream & GmvStream::operator<< (const T &t) { stream << t; return stream; } template <typename T> std::ostream & UcdStream::operator<< (const T &t) { stream << t; return stream; } template <typename T> std::ostream & VtkStream::operator<< (const T &t) { stream << t; return stream; } } //----------------------------------------------------------------------// namespace DataOutBase { template <int dim, int spacedim> const unsigned int Patch<dim,spacedim>::space_dim; const unsigned int Deal_II_IntermediateFlags::format_version; template <int dim, int spacedim> const unsigned int Patch<dim,spacedim>::no_neighbor; template <int dim, int spacedim> Patch<dim,spacedim>::Patch () : patch_index(no_neighbor), n_subdivisions (1), points_are_available(false) // all the other data has a // constructor of its own, except // for the "neighbors" field, which // we set to invalid values. { for (unsigned int i=0; i<GeometryInfo<dim>::faces_per_cell; ++i) neighbors[i] = no_neighbor; Assert (dim<=spacedim, ExcIndexRange(dim,0,spacedim)); Assert (spacedim<=3, ExcNotImplemented()); } template <int dim, int spacedim> bool Patch<dim,spacedim>::operator == (const Patch &patch) const { //TODO: make tolerance relative const double epsilon=3e-16; for (unsigned int i=0; i<GeometryInfo<dim>::vertices_per_cell; ++i) if (vertices[i].distance(patch.vertices[i]) > epsilon) return false; for (unsigned int i=0; i<GeometryInfo<dim>::faces_per_cell; ++i) if (neighbors[i] != patch.neighbors[i]) return false; if (patch_index != patch.patch_index) return false; if (n_subdivisions != patch.n_subdivisions) return false; if (points_are_available != patch.points_are_available) return false; if (data.n_rows() != patch.data.n_rows()) return false; if (data.n_cols() != patch.data.n_cols()) return false; for (unsigned int i=0; i<data.n_rows(); ++i) for (unsigned int j=0; j<data.n_cols(); ++j) if (data[i][j] != patch.data[i][j]) return false; return true; } template <int dim, int spacedim> std::size_t Patch<dim,spacedim>::memory_consumption () const { return (sizeof(vertices) / sizeof(vertices[0]) * MemoryConsumption::memory_consumption(vertices[0]) + MemoryConsumption::memory_consumption(n_subdivisions) + MemoryConsumption::memory_consumption(data) + MemoryConsumption::memory_consumption(points_are_available)); } UcdFlags::UcdFlags (const bool write_preamble) : write_preamble (write_preamble) {} PovrayFlags::PovrayFlags (const bool smooth, const bool bicubic_patch, const bool external_data) : smooth (smooth), bicubic_patch(bicubic_patch), external_data(external_data) {} DataOutFilterFlags::DataOutFilterFlags (const bool filter_duplicate_vertices, const bool xdmf_hdf5_output) : filter_duplicate_vertices(filter_duplicate_vertices), xdmf_hdf5_output(xdmf_hdf5_output) {} void DataOutFilterFlags::declare_parameters (ParameterHandler &prm) { prm.declare_entry ("Filter duplicate vertices", "false", Patterns::Bool(), "Whether to remove duplicate vertex values."); prm.declare_entry ("XDMF HDF5 output", "false", Patterns::Bool(), "Whether the data will be used in an XDMF/HDF5 combination."); } void DataOutFilterFlags::parse_parameters (const ParameterHandler &prm) { filter_duplicate_vertices = prm.get_bool ("Filter duplicate vertices"); xdmf_hdf5_output = prm.get_bool ("XDMF HDF5 output"); } std::size_t DataOutFilterFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } DXFlags::DXFlags (const bool write_neighbors, const bool int_binary, const bool coordinates_binary, const bool data_binary) : write_neighbors(write_neighbors), int_binary(int_binary), coordinates_binary(coordinates_binary), data_binary(data_binary), data_double(false) {} void DXFlags::declare_parameters (ParameterHandler &prm) { prm.declare_entry ("Write neighbors", "true", Patterns::Bool(), "A boolean field indicating whether neighborship " "information between cells is to be written to the " "OpenDX output file"); prm.declare_entry ("Integer format", "ascii", Patterns::Selection("ascii|32|64"), "Output format of integer numbers, which is " "either a text representation (ascii) or binary integer " "values of 32 or 64 bits length"); prm.declare_entry ("Coordinates format", "ascii", Patterns::Selection("ascii|32|64"), "Output format of vertex coordinates, which is " "either a text representation (ascii) or binary " "floating point values of 32 or 64 bits length"); prm.declare_entry ("Data format", "ascii", Patterns::Selection("ascii|32|64"), "Output format of data values, which is " "either a text representation (ascii) or binary " "floating point values of 32 or 64 bits length"); } void DXFlags::parse_parameters (const ParameterHandler &prm) { write_neighbors = prm.get_bool ("Write neighbors"); //TODO:[GK] Read the new parameters } std::size_t DXFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } void UcdFlags::declare_parameters (ParameterHandler &prm) { prm.declare_entry ("Write preamble", "true", Patterns::Bool(), "A flag indicating whether a comment should be " "written to the beginning of the output file " "indicating date and time of creation as well " "as the creating program"); } void UcdFlags::parse_parameters (const ParameterHandler &prm) { write_preamble = prm.get_bool ("Write preamble"); } std::size_t UcdFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } GnuplotFlags::GnuplotFlags () : dummy (0) {} void GnuplotFlags::declare_parameters (ParameterHandler &/*prm*/) {} void GnuplotFlags::parse_parameters (const ParameterHandler &/*prm*/) const {} size_t GnuplotFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } SvgFlags::SvgFlags (const unsigned int height_vector, const int azimuth_angle, const int polar_angle, const unsigned int line_thickness, const bool margin, const bool draw_colorbar) : height(4000), width(0), height_vector(height_vector), azimuth_angle(azimuth_angle), polar_angle(polar_angle), line_thickness(line_thickness), margin(margin), draw_colorbar(draw_colorbar) {} std::size_t SvgFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } void PovrayFlags::declare_parameters (ParameterHandler &prm) { prm.declare_entry ("Use smooth triangles", "false", Patterns::Bool(), "A flag indicating whether POVRAY should use smoothed " "triangles instead of the usual ones"); prm.declare_entry ("Use bicubic patches", "false", Patterns::Bool(), "Whether POVRAY should use bicubic patches"); prm.declare_entry ("Include external file", "true", Patterns::Bool (), "Whether camera and lightling information should " "be put into an external file \"data.inc\" or into " "the POVRAY input file"); } void PovrayFlags::parse_parameters (const ParameterHandler &prm) { smooth = prm.get_bool ("Use smooth triangles"); bicubic_patch = prm.get_bool ("Use bicubic patches"); external_data = prm.get_bool ("Include external file"); } std::size_t PovrayFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } EpsFlags::EpsFlags (const unsigned int height_vector, const unsigned int color_vector, const SizeType size_type, const unsigned int size, const double line_width, const double azimut_angle, const double turn_angle, const double z_scaling, const bool draw_mesh, const bool draw_cells, const bool shade_cells, const ColorFunction color_function) : height_vector(height_vector), color_vector(color_vector), size_type(size_type), size(size), line_width(line_width), azimut_angle(azimut_angle), turn_angle(turn_angle), z_scaling(z_scaling), draw_mesh(draw_mesh), draw_cells(draw_cells), shade_cells(shade_cells), color_function(color_function) {} EpsFlags::RgbValues EpsFlags::default_color_function (const double x, const double xmin, const double xmax) { RgbValues rgb_values = { 0,0,0 }; // A difficult color scale: // xmin = black (1) // 3/4*xmin+1/4*xmax = blue (2) // 1/2*xmin+1/2*xmax = green (3) // 1/4*xmin+3/4*xmax = red (4) // xmax = white (5) // Makes the following color functions: // // red green blue // __ // / /\ / /\ / // ____/ __/ \/ / \__/ // { 0 (1) - (3) // r = { ( 4*x-2*xmin+2*xmax)/(xmax-xmin) (3) - (4) // { 1 (4) - (5) // // { 0 (1) - (2) // g = { ( 4*x-3*xmin- xmax)/(xmax-xmin) (2) - (3) // { (-4*x+ xmin+3*xmax)/(xmax-xmin) (3) - (4) // { ( 4*x- xmin-3*xmax)/(xmax-xmin) (4) - (5) // // { ( 4*x-4*xmin )/(xmax-xmin) (1) - (2) // b = { (-4*x+2*xmin+2*xmax)/(xmax-xmin) (2) - (3) // { 0 (3) - (4) // { ( 4*x- xmin-3*xmax)/(xmax-xmin) (4) - (5) double sum = xmax+ xmin; double sum13 = xmin+3*xmax; double sum22 = 2*xmin+2*xmax; double sum31 = 3*xmin+ xmax; double dif = xmax-xmin; double rezdif = 1.0/dif; int where; if (x<(sum31)/4) where = 0; else if (x<(sum22)/4) where = 1; else if (x<(sum13)/4) where = 2; else where = 3; if (dif!=0) { switch (where) { case 0: rgb_values.red = 0; rgb_values.green = 0; rgb_values.blue = (x-xmin)*4.*rezdif; break; case 1: rgb_values.red = 0; rgb_values.green = (4*x-3*xmin-xmax)*rezdif; rgb_values.blue = (sum22-4.*x)*rezdif; break; case 2: rgb_values.red = (4*x-2*sum)*rezdif; rgb_values.green = (xmin+3*xmax-4*x)*rezdif; rgb_values.blue = 0; break; case 3: rgb_values.red = 1; rgb_values.green = (4*x-xmin-3*xmax)*rezdif; rgb_values.blue = (4.*x-sum13)*rezdif; default: break; } } else // White rgb_values.red = rgb_values.green = rgb_values.blue = 1; return rgb_values; } EpsFlags::RgbValues EpsFlags::grey_scale_color_function (const double x, const double xmin, const double xmax) { EpsFlags::RgbValues rgb_values; rgb_values.red = rgb_values.blue = rgb_values.green = (x-xmin)/(xmax-xmin); return rgb_values; } EpsFlags::RgbValues EpsFlags::reverse_grey_scale_color_function (const double x, const double xmin, const double xmax) { EpsFlags::RgbValues rgb_values; rgb_values.red = rgb_values.blue = rgb_values.green = 1-(x-xmin)/(xmax-xmin); return rgb_values; } bool EpsCell2d::operator < (const EpsCell2d &e) const { // note the "wrong" order in // which we sort the elements return depth > e.depth; } void EpsFlags::declare_parameters (ParameterHandler &prm) { prm.declare_entry ("Index of vector for height", "0", Patterns::Integer(), "Number of the input vector that is to be used to " "generate height information"); prm.declare_entry ("Index of vector for color", "0", Patterns::Integer(), "Number of the input vector that is to be used to " "generate color information"); prm.declare_entry ("Scale to width or height", "width", Patterns::Selection ("width|height"), "Whether width or height should be scaled to match " "the given size"); prm.declare_entry ("Size (width or height) in eps units", "300", Patterns::Integer(), "The size (width or height) to which the eps output " "file is to be scaled"); prm.declare_entry ("Line widths in eps units", "0.5", Patterns::Double(), "The width in which the postscript renderer is to " "plot lines"); prm.declare_entry ("Azimut angle", "60", Patterns::Double(0,180), "Angle of the viewing position against the vertical " "axis"); prm.declare_entry ("Turn angle", "30", Patterns::Double(0,360), "Angle of the viewing direction against the y-axis"); prm.declare_entry ("Scaling for z-axis", "1", Patterns::Double (), "Scaling for the z-direction relative to the scaling " "used in x- and y-directions"); prm.declare_entry ("Draw mesh lines", "true", Patterns::Bool(), "Whether the mesh lines, or only the surface should be " "drawn"); prm.declare_entry ("Fill interior of cells", "true", Patterns::Bool(), "Whether only the mesh lines, or also the interior of " "cells should be plotted. If this flag is false, then " "one can see through the mesh"); prm.declare_entry ("Color shading of interior of cells", "true", Patterns::Bool(), "Whether the interior of cells shall be shaded"); prm.declare_entry ("Color function", "default", Patterns::Selection ("default|grey scale|reverse grey scale"), "Name of a color function used to colorize mesh lines " "and/or cell interiors"); } void EpsFlags::parse_parameters (const ParameterHandler &prm) { height_vector = prm.get_integer ("Index of vector for height"); color_vector = prm.get_integer ("Index of vector for color"); if (prm.get ("Scale to width or height") == "width") size_type = width; else size_type = height; size = prm.get_integer ("Size (width or height) in eps units"); line_width = prm.get_double ("Line widths in eps units"); azimut_angle = prm.get_double ("Azimut angle"); turn_angle = prm.get_double ("Turn angle"); z_scaling = prm.get_double ("Scaling for z-axis"); draw_mesh = prm.get_bool ("Draw mesh lines"); draw_cells = prm.get_bool ("Fill interior of cells"); shade_cells = prm.get_bool ("Color shading of interior of cells"); if (prm.get("Color function") == "default") color_function = &default_color_function; else if (prm.get("Color function") == "grey scale") color_function = &grey_scale_color_function; else if (prm.get("Color function") == "reverse grey scale") color_function = &reverse_grey_scale_color_function; else // we shouldn't get here, since // the parameter object should // already have checked that the // given value is valid Assert (false, ExcInternalError()); } std::size_t EpsFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } GmvFlags::GmvFlags () {} void GmvFlags::declare_parameters (ParameterHandler &/*prm*/) {} void GmvFlags::parse_parameters (const ParameterHandler &/*prm*/) const {} std::size_t GmvFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } TecplotFlags:: TecplotFlags (const char *tecplot_binary_file_name, const char *zone_name) : tecplot_binary_file_name(tecplot_binary_file_name), zone_name(zone_name) {} void TecplotFlags::declare_parameters (ParameterHandler &/*prm*/) {} void TecplotFlags::parse_parameters (const ParameterHandler &/*prm*/) const {} std::size_t TecplotFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } VtkFlags::VtkFlags (const double time, const unsigned int cycle, const bool print_date_and_time) : time (time), cycle (cycle), print_date_and_time (print_date_and_time) {} void VtkFlags::declare_parameters (ParameterHandler &/*prm*/) {} void VtkFlags::parse_parameters (const ParameterHandler &/*prm*/) const {} std::size_t VtkFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } Deal_II_IntermediateFlags::Deal_II_IntermediateFlags () : dummy (0) {} void Deal_II_IntermediateFlags::declare_parameters (ParameterHandler &/*prm*/) {} void Deal_II_IntermediateFlags::parse_parameters (const ParameterHandler &/*prm*/) const {} std::size_t Deal_II_IntermediateFlags::memory_consumption () const { // only simple data elements, so // use sizeof operator return sizeof (*this); } OutputFormat parse_output_format (const std::string &format_name) { if (format_name == "none") return none; if (format_name == "dx") return dx; if (format_name == "ucd") return ucd; if (format_name == "gnuplot") return gnuplot; if (format_name == "povray") return povray; if (format_name == "eps") return eps; if (format_name == "gmv") return gmv; if (format_name == "tecplot") return tecplot; if (format_name == "tecplot_binary") return tecplot_binary; if (format_name == "vtk") return vtk; if (format_name == "vtu") return vtu; if (format_name == "deal.II intermediate") return deal_II_intermediate; if (format_name == "hdf5") return hdf5; AssertThrow (false, ExcMessage ("The given file format name is not recognized: <" + format_name + ">")); // return something invalid return OutputFormat(-1); } std::string get_output_format_names () { return "none|dx|ucd|gnuplot|povray|eps|gmv|tecplot|tecplot_binary|vtk|vtu|hdf5|svg|deal.II intermediate"; } std::string default_suffix (const OutputFormat output_format) { switch (output_format) { case none: return ""; case dx: return ".dx"; case ucd: return ".inp"; case gnuplot: return ".gnuplot"; case povray: return ".pov"; case eps: return ".eps"; case gmv: return ".gmv"; case tecplot: return ".dat"; case tecplot_binary: return ".plt"; case vtk: return ".vtk"; case vtu: return ".vtu"; case deal_II_intermediate: return ".d2"; case hdf5: return ".h5"; case svg: return ".svg"; default: Assert (false, ExcNotImplemented()); return ""; } } //----------------------------------------------------------------------// template <int dim, int spacedim, typename STREAM> void write_nodes (const std::vector<Patch<dim,spacedim> > &patches, STREAM &out) { Assert (dim<=3, ExcNotImplemented()); unsigned int count = 0; // We only need this point below, // but it does not harm to declare // it here. Point<spacedim> node; for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; // Length of loops in all // dimensions. If a dimension // is not used, a loop of // length one will do the job. const unsigned int n1 = (dim>0) ? n : 1; const unsigned int n2 = (dim>1) ? n : 1; const unsigned int n3 = (dim>2) ? n : 1; for (unsigned int i3=0; i3<n3; ++i3) for (unsigned int i2=0; i2<n2; ++i2) for (unsigned int i1=0; i1<n1; ++i1) { compute_node(node, &*patch, i1, i2, i3, n_subdivisions); out.write_point(count++, node); } } out.flush_points (); } template <int dim, int spacedim, typename STREAM> void write_cells (const std::vector<Patch<dim,spacedim> > &patches, STREAM &out) { Assert (dim<=3, ExcNotImplemented()); unsigned int count = 0; unsigned int first_vertex_of_patch = 0; // Array to hold all the node // numbers of a cell. 8 is // sufficient for 3D for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; // Length of loops in all dimensons const unsigned int n1 = (dim>0) ? n_subdivisions : 1; const unsigned int n2 = (dim>1) ? n_subdivisions : 1; const unsigned int n3 = (dim>2) ? n_subdivisions : 1; // Offsets of outer loops unsigned int d1 = 1; unsigned int d2 = n; unsigned int d3 = n*n; for (unsigned int i3=0; i3<n3; ++i3) for (unsigned int i2=0; i2<n2; ++i2) for (unsigned int i1=0; i1<n1; ++i1) { const unsigned int offset = first_vertex_of_patch+i3*d3+i2*d2+i1*d1; // First write line in x direction out.template write_cell<dim>(count++, offset, d1, d2, d3); } // finally update the number // of the first vertex of this patch first_vertex_of_patch += Utilities::fixed_power<dim>(n_subdivisions+1); } out.flush_cells (); } template <int dim, int spacedim, class STREAM> void write_data ( const std::vector<Patch<dim,spacedim> > &patches, unsigned int n_data_sets, const bool double_precision, STREAM &out) { Assert (dim<=3, ExcNotImplemented()); unsigned int count = 0; for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch = patches.begin(); patch != patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; // Length of loops in all dimensions Assert ((patch->data.n_rows() == n_data_sets && !patch->points_are_available) || (patch->data.n_rows() == n_data_sets+spacedim && patch->points_are_available), ExcDimensionMismatch (patch->points_are_available ? (n_data_sets + spacedim) : n_data_sets, patch->data.n_rows())); Assert (patch->data.n_cols() == Utilities::fixed_power<dim>(n), ExcInvalidDatasetSize (patch->data.n_cols(), n)); std::vector<float> floats(n_data_sets); std::vector<double> doubles(n_data_sets); // Data is already in // lexicographic ordering for (unsigned int i=0; i<Utilities::fixed_power<dim>(n); ++i, ++count) if (double_precision) { for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) doubles[data_set] = patch->data(data_set, i); out.write_dataset(count, doubles); } else { for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) floats[data_set] = patch->data(data_set, i); out.write_dataset(count, floats); } } } namespace { /** * This function projects a three-dimensional point (Point<3> point) * onto a two-dimensional image plane, specified by the position of * the camera viewing system (Point<3> camera_position), camera * direction (Point<3> camera_position), camera horizontal (Point<3> * camera_horizontal, necessary for the correct alignment of the * later images), and the focus of the camera (float camera_focus). */ Point<2> svg_project_point(Point<3> point, Point<3> camera_position, Point<3> camera_direction, Point<3> camera_horizontal, float camera_focus) { Point<3> camera_vertical; camera_vertical[0] = camera_horizontal[1] * camera_direction[2] - camera_horizontal[2] * camera_direction[1]; camera_vertical[1] = camera_horizontal[2] * camera_direction[0] - camera_horizontal[0] * camera_direction[2]; camera_vertical[2] = camera_horizontal[0] * camera_direction[1] - camera_horizontal[1] * camera_direction[0]; float phi; phi = camera_focus; phi /= (point[0] - camera_position[0]) * camera_direction[0] + (point[1] - camera_position[1]) * camera_direction[1] + (point[2] - camera_position[2]) * camera_direction[2]; Point<3> projection; projection[0] = camera_position[0] + phi * (point[0] - camera_position[0]); projection[1] = camera_position[1] + phi * (point[1] - camera_position[1]); projection[2] = camera_position[2] + phi * (point[2] - camera_position[2]); Point<2> projection_decomposition; projection_decomposition[0] = (projection[0] - camera_position[0] - camera_focus * camera_direction[0]) * camera_horizontal[0]; projection_decomposition[0] += (projection[1] - camera_position[1] - camera_focus * camera_direction[1]) * camera_horizontal[1]; projection_decomposition[0] += (projection[2] - camera_position[2] - camera_focus * camera_direction[2]) * camera_horizontal[2]; projection_decomposition[1] = (projection[0] - camera_position[0] - camera_focus * camera_direction[0]) * camera_vertical[0]; projection_decomposition[1] += (projection[1] - camera_position[1] - camera_focus * camera_direction[1]) * camera_vertical[1]; projection_decomposition[1] += (projection[2] - camera_position[2] - camera_focus * camera_direction[2]) * camera_vertical[2]; return projection_decomposition; } /** * Function to compute the gradient parameters for a triangle with * given values for the vertices. */ Point<6> svg_get_gradient_parameters(Point<3> points[]) { Point<3> v_min, v_max, v_inter; // Use the Bubblesort algorithm to sort the points with respect to the third coordinate for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2-i; ++j) { if (points[j][2] > points[j + 1][2]) { Point<3> temp = points[j]; points[j] = points[j+1]; points[j+1] = temp; } } } // save the related three-dimensional vectors v_min, v_inter, and v_max v_min = points[0]; v_inter = points[1]; v_max = points[2]; Point<2> A[2]; Point<2> b, gradient; // determine the plane offset c A[0][0] = v_max[0] - v_min[0]; A[0][1] = v_inter[0] - v_min[0]; A[1][0] = v_max[1] - v_min[1]; A[1][1] = v_inter[1] - v_min[1]; b[0] = - v_min[0]; b[1] = - v_min[1]; double x, sum; bool col_change = false; if (A[0][0] == 0) { col_change = true; A[0][0] = A[0][1]; A[0][1] = 0; double temp = A[1][0]; A[1][0] = A[1][1]; A[1][1] = temp; } for (unsigned int k = 0; k < 1; k++) { for (unsigned int i = k+1; i < 2; i++) { x = A[i][k] / A[k][k]; for (unsigned int j = k+1; j < 2; j++) A[i][j] = A[i][j] - A[k][j] * x; b[i] = b[i] - b[k]*x; } } b[1] = b[1] / A[1][1]; for (int i = 0; i >= 0; i--) { sum = b[i]; for (unsigned int j = i+1; j < 2; j++) sum = sum - A[i][j] * b[j]; b[i] = sum / A[i][i]; } if (col_change) { double temp = b[0]; b[0] = b[1]; b[1] = temp; } double c = b[0] * (v_max[2] - v_min[2]) + b[1] * (v_inter[2] - v_min[2]) + v_min[2]; // Determine the first entry of the gradient (phi, cf. documentation) A[0][0] = v_max[0] - v_min[0]; A[0][1] = v_inter[0] - v_min[0]; A[1][0] = v_max[1] - v_min[1]; A[1][1] = v_inter[1] - v_min[1]; b[0] = 1.0 - v_min[0]; b[1] = - v_min[1]; col_change = false; if (A[0][0] == 0) { col_change = true; A[0][0] = A[0][1]; A[0][1] = 0; double temp = A[1][0]; A[1][0] = A[1][1]; A[1][1] = temp; } for (unsigned int k = 0; k < 1; k++) { for (unsigned int i = k+1; i < 2; i++) { x = A[i][k] / A[k][k]; for (unsigned int j = k+1; j < 2; j++) A[i][j] = A[i][j] - A[k][j] * x; b[i] = b[i] - b[k] * x; } } b[1]=b[1] / A[1][1]; for (int i = 0; i >= 0; i--) { sum = b[i]; for (unsigned int j = i+1; j < 2; j++) sum = sum - A[i][j]*b[j]; b[i] = sum / A[i][i]; } if (col_change) { double temp = b[0]; b[0] = b[1]; b[1] = temp; } gradient[0] = b[0] * (v_max[2] - v_min[2]) + b[1] * (v_inter[2] - v_min[2]) - c + v_min[2]; // determine the second entry of the gradient A[0][0] = v_max[0] - v_min[0]; A[0][1] = v_inter[0] - v_min[0]; A[1][0] = v_max[1] - v_min[1]; A[1][1] = v_inter[1] - v_min[1]; b[0] = - v_min[0]; b[1] = 1.0 - v_min[1]; col_change = false; if (A[0][0] == 0) { col_change = true; A[0][0] = A[0][1]; A[0][1] = 0; double temp = A[1][0]; A[1][0] = A[1][1]; A[1][1] = temp; } for (unsigned int k = 0; k < 1; k++) { for (unsigned int i = k+1; i < 2; i++) { x = A[i][k] / A[k][k]; for (unsigned int j = k+1; j < 2; j++) A[i][j] = A[i][j] - A[k][j] * x; b[i] = b[i] - b[k] * x; } } b[1] = b[1] / A[1][1]; for (int i = 0; i >= 0; i--) { sum = b[i]; for (unsigned int j = i+1; j < 2; j++) sum = sum - A[i][j] * b[j]; b[i] = sum / A[i][i]; } if (col_change) { double temp = b[0]; b[0] = b[1]; b[1] = temp; } gradient[1] = b[0] * (v_max[2] - v_min[2]) + b[1] * (v_inter[2] - v_min[2]) - c + v_min[2]; // normalize the gradient double gradient_norm = sqrt(pow(gradient[0], 2.0) + pow(gradient[1], 2.0)); gradient[0] /= gradient_norm; gradient[1] /= gradient_norm; double lambda = - gradient[0] * (v_min[0] - v_max[0]) - gradient[1] * (v_min[1] - v_max[1]); Point<6> gradient_parameters(true); gradient_parameters[0] = v_min[0]; gradient_parameters[1] = v_min[1]; gradient_parameters[2] = v_min[0] + lambda * gradient[0]; gradient_parameters[3] = v_min[1] + lambda * gradient[1]; gradient_parameters[4] = v_min[2]; gradient_parameters[5] = v_max[2]; return gradient_parameters; } } template <int dim, int spacedim> void write_ucd (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const UcdFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif const unsigned int n_data_sets = data_names.size(); UcdStream ucd_out(out, flags); // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim> (patches, n_nodes, n_cells); /////////////////////// // preamble if (flags.write_preamble) { std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "# This file was generated by the deal.II library." << '\n' << "# Date = " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << '\n' << "# Time = " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << '\n' << "#" << '\n' << "# For a description of the UCD format see the AVS Developer's guide." << '\n' << "#" << '\n'; } // start with ucd data out << n_nodes << ' ' << n_cells << ' ' << n_data_sets << ' ' << 0 << ' ' // no cell data at present << 0 // no model data << '\n'; write_nodes(patches, ucd_out); out << '\n'; write_cells(patches, ucd_out); out << '\n'; ///////////////////////////// // now write data if (n_data_sets != 0) { out << n_data_sets << " "; // number of vectors for (unsigned int i=0; i<n_data_sets; ++i) out << 1 << ' '; // number of components; // only 1 supported presently out << '\n'; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << data_names[data_set] << ",dimensionless" // no units supported at present << '\n'; write_data(patches, n_data_sets, true, ucd_out); } // make sure everything now gets to // disk out.flush (); // assert the stream is still ok AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_dx (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const DXFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif // Stream with special features for dx output DXStream dx_out(out, flags); // Variable counting the offset of // binary data. unsigned int offset = 0; const unsigned int n_data_sets = data_names.size(); // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim>(patches, n_nodes, n_cells); // start with vertices order is // lexicographical, x varying // fastest out << "object \"vertices\" class array type float rank 1 shape " << spacedim << " items " << n_nodes; if (flags.coordinates_binary) { out << " lsb ieee data 0" << '\n'; offset += n_nodes * spacedim * sizeof(float); } else { out << " data follows" << '\n'; write_nodes(patches, dx_out); } /////////////////////////////// // first write the coordinates of all vertices ///////////////////////////////////////// // write cells out << "object \"cells\" class array type int rank 1 shape " << GeometryInfo<dim>::vertices_per_cell << " items " << n_cells; if (flags.int_binary) { out << " lsb binary data " << offset << '\n'; offset += n_cells * sizeof (int); } else { out << " data follows" << '\n'; write_cells(patches, dx_out); out << '\n'; } out << "attribute \"element type\" string \""; if (dim==1) out << "lines"; if (dim==2) out << "quads"; if (dim==3) out << "cubes"; out << "\"" << '\n' << "attribute \"ref\" string \"positions\"" << '\n'; //TODO:[GK] Patches must be of same size! ///////////////////////////// // write neighbor information if (flags.write_neighbors) { out << "object \"neighbors\" class array type int rank 1 shape " << GeometryInfo<dim>::faces_per_cell << " items " << n_cells << " data follows"; for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { const unsigned int n = patch->n_subdivisions; const unsigned int n1 = (dim>0) ? n : 1; const unsigned int n2 = (dim>1) ? n : 1; const unsigned int n3 = (dim>2) ? n : 1; unsigned int cells_per_patch = Utilities::fixed_power<dim>(n); unsigned int dx = 1; unsigned int dy = n; unsigned int dz = n*n; const unsigned int patch_start = patch->patch_index * cells_per_patch; for (unsigned int i3=0; i3<n3; ++i3) for (unsigned int i2=0; i2<n2; ++i2) for (unsigned int i1=0; i1<n1; ++i1) { const unsigned int nx = i1*dx; const unsigned int ny = i2*dy; const unsigned int nz = i3*dz; out << '\n'; // Direction -x // Last cell in row // of other patch if (i1==0) { const unsigned int nn = patch->neighbors[0]; out << '\t'; if (nn != patch->no_neighbor) out << (nn*cells_per_patch+ny+nz+dx*(n-1)); else out << "-1"; } else { out << '\t' << patch_start+nx-dx+ny+nz; } // Direction +x // First cell in row // of other patch if (i1 == n-1) { const unsigned int nn = patch->neighbors[1]; out << '\t'; if (nn != patch->no_neighbor) out << (nn*cells_per_patch+ny+nz); else out << "-1"; } else { out << '\t' << patch_start+nx+dx+ny+nz; } if (dim<2) continue; // Direction -y if (i2==0) { const unsigned int nn = patch->neighbors[2]; out << '\t'; if (nn != patch->no_neighbor) out << (nn*cells_per_patch+nx+nz+dy*(n-1)); else out << "-1"; } else { out << '\t' << patch_start+nx+ny-dy+nz; } // Direction +y if (i2 == n-1) { const unsigned int nn = patch->neighbors[3]; out << '\t'; if (nn != patch->no_neighbor) out << (nn*cells_per_patch+nx+nz); else out << "-1"; } else { out << '\t' << patch_start+nx+ny+dy+nz; } if (dim<3) continue; // Direction -z if (i3==0) { const unsigned int nn = patch->neighbors[4]; out << '\t'; if (nn != patch->no_neighbor) out << (nn*cells_per_patch+nx+ny+dz*(n-1)); else out << "-1"; } else { out << '\t' << patch_start+nx+ny+nz-dz; } // Direction +z if (i3 == n-1) { const unsigned int nn = patch->neighbors[5]; out << '\t'; if (nn != patch->no_neighbor) out << (nn*cells_per_patch+nx+ny); else out << "-1"; } else { out << '\t' << patch_start+nx+ny+nz+dz; } } out << '\n'; } } ///////////////////////////// // now write data if (n_data_sets != 0) { out << "object \"data\" class array type float rank 1 shape " << n_data_sets << " items " << n_nodes; if (flags.data_binary) { out << " lsb ieee data " << offset << '\n'; offset += n_data_sets * n_nodes * ((flags.data_double) ? sizeof(double) : sizeof(float)); } else { out << " data follows" << '\n'; write_data(patches, n_data_sets, flags.data_double, dx_out); } // loop over all patches out << "attribute \"dep\" string \"positions\"" << '\n'; } else { out << "object \"data\" class constantarray type float rank 0 items " << n_nodes << " data follows" << '\n' << '0' << '\n'; } // no model data out << "object \"deal data\" class field" << '\n' << "component \"positions\" value \"vertices\"" << '\n' << "component \"connections\" value \"cells\"" << '\n' << "component \"data\" value \"data\"" << '\n'; if (flags.write_neighbors) out << "component \"neighbors\" value \"neighbors\"" << '\n'; if (true) { std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "attribute \"created\" string \"" << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << ' ' << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << '"' << '\n'; } out << "end" << '\n'; // Write all binary data now if (flags.coordinates_binary) write_nodes(patches, dx_out); if (flags.int_binary) write_cells(patches, dx_out); if (flags.data_binary) write_data(patches, n_data_sets, flags.data_double, dx_out); // make sure everything now gets to // disk out.flush (); // assert the stream is still ok AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_gnuplot (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const GnuplotFlags &/*flags*/, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif const unsigned int n_data_sets = data_names.size(); // write preamble if (true) { // block this to have local // variables destroyed after // use const std::time_t time1= std::time (0); const std::tm *time = std::localtime(&time1); out << "# This file was generated by the deal.II library." << '\n' << "# Date = " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << '\n' << "# Time = " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << '\n' << "#" << '\n' << "# For a description of the GNUPLOT format see the GNUPLOT manual." << '\n' << "#" << '\n' << "# "; switch (spacedim) { case 1: out << "<x> "; break; case 2: out << "<x> <y> "; break; case 3: out << "<x> <y> <z> "; break; default: Assert (false, ExcNotImplemented()); } for (unsigned int i=0; i<data_names.size(); ++i) out << '<' << data_names[i] << "> "; out << '\n'; } // loop over all patches for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch != patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; // Length of loops in all dimensions const unsigned int n1 = (dim>0) ? n : 1; const unsigned int n2 = (dim>1) ? n : 1; const unsigned int n3 = (dim>2) ? n : 1; unsigned int d1 = 1; unsigned int d2 = n; unsigned int d3 = n*n; Assert ((patch->data.n_rows() == n_data_sets && !patch->points_are_available) || (patch->data.n_rows() == n_data_sets+spacedim && patch->points_are_available), ExcDimensionMismatch (patch->points_are_available ? (n_data_sets + spacedim) : n_data_sets, patch->data.n_rows())); Assert (patch->data.n_cols() == Utilities::fixed_power<dim>(n), ExcInvalidDatasetSize (patch->data.n_cols(), n_subdivisions+1)); Point<spacedim> this_point; Point<spacedim> node; if (dim<3) { for (unsigned int i2=0; i2<n2; ++i2) { for (unsigned int i1=0; i1<n1; ++i1) { // compute coordinates for // this patch point compute_node(node, &*patch, i1, i2, 0, n_subdivisions); out << node << ' '; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << patch->data(data_set,i1*d1+i2*d2) << ' '; out << '\n'; } // end of row in patch if (dim>1) out << '\n'; } // end of patch if (dim==1) out << '\n'; out << '\n'; } else if (dim==3) { // for all grid points: draw // lines into all positive // coordinate directions if // there is another grid point // there for (unsigned int i3=0; i3<n3; ++i3) for (unsigned int i2=0; i2<n2; ++i2) for (unsigned int i1=0; i1<n1; ++i1) { // compute coordinates for // this patch point compute_node(this_point, &*patch, i1, i2, i3, n_subdivisions); // line into positive x-direction // if possible if (i1 < n_subdivisions) { // write point here // and its data out << this_point; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ' ' << patch->data(data_set,i1*d1+i2*d2+i3*d3); out << '\n'; // write point there // and its data compute_node(node, &*patch, i1+1, i2, i3, n_subdivisions); out << node; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ' ' << patch->data(data_set,(i1+1)*d1+i2*d2+i3*d3); out << '\n'; // end of line out << '\n' << '\n'; } // line into positive y-direction // if possible if (i2 < n_subdivisions) { // write point here // and its data out << this_point; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ' ' << patch->data(data_set, i1*d1+i2*d2+i3*d3); out << '\n'; // write point there // and its data compute_node(node, &*patch, i1, i2+1, i3, n_subdivisions); out << node; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ' ' << patch->data(data_set,i1*d1+(i2+1)*d2+i3*d3); out << '\n'; // end of line out << '\n' << '\n'; } // line into positive z-direction // if possible if (i3 < n_subdivisions) { // write point here // and its data out << this_point; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ' ' << patch->data(data_set,i1*d1+i2*d2+i3*d3); out << '\n'; // write point there // and its data compute_node(node, &*patch, i1, i2, i3+1, n_subdivisions); out << node; for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ' ' << patch->data(data_set,i1*d1+i2*d2+(i3+1)*d3); out << '\n'; // end of line out << '\n' << '\n'; } } } else Assert (false, ExcNotImplemented()); } // make sure everything now gets to // disk out.flush (); AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_povray (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const PovrayFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif Assert (dim==2, ExcNotImplemented()); // only for 2-D surfaces on a 2-D plane Assert (spacedim==2, ExcNotImplemented()); const unsigned int n_data_sets = data_names.size(); (void)n_data_sets; // write preamble if (true) { // block this to have local // variables destroyed after use const std::time_t time1= std::time (0); const std::tm *time = std::localtime(&time1); out << "/* This file was generated by the deal.II library." << '\n' << " Date = " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << '\n' << " Time = " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << '\n' << '\n' << " For a description of the POVRAY format see the POVRAY manual." << '\n' << "*/ " << '\n'; // include files out << "#include \"colors.inc\" " << '\n' << "#include \"textures.inc\" " << '\n'; // use external include file for textures, // camera and light if (flags.external_data) out << "#include \"data.inc\" " << '\n'; else // all definitions in data file { // camera out << '\n' << '\n' << "camera {" << '\n' << " location <1,4,-7>" << '\n' << " look_at <0,0,0>" << '\n' << " angle 30" << '\n' << "}" << '\n'; // light out << '\n' << "light_source {" << '\n' << " <1,4,-7>" << '\n' << " color Grey" << '\n' << "}" << '\n'; out << '\n' << "light_source {" << '\n' << " <0,20,0>" << '\n' << " color White" << '\n' << "}" << '\n'; } } // max. and min. heigth of solution Assert(patches.size()>0, ExcInternalError()); double hmin=patches[0].data(0,0); double hmax=patches[0].data(0,0); for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch != patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; Assert ((patch->data.n_rows() == n_data_sets && !patch->points_are_available) || (patch->data.n_rows() == n_data_sets+spacedim && patch->points_are_available), ExcDimensionMismatch (patch->points_are_available ? (n_data_sets + spacedim) : n_data_sets, patch->data.n_rows())); Assert (patch->data.n_cols() == Utilities::fixed_power<dim>(n_subdivisions+1), ExcInvalidDatasetSize (patch->data.n_cols(), n_subdivisions+1)); for (unsigned int i=0; i<n_subdivisions+1; ++i) for (unsigned int j=0; j<n_subdivisions+1; ++j) { const int dl = i*(n_subdivisions+1)+j; if (patch->data(0,dl)<hmin) hmin=patch->data(0,dl); if (patch->data(0,dl)>hmax) hmax=patch->data(0,dl); } } out << "#declare HMIN=" << hmin << ";" << '\n' << "#declare HMAX=" << hmax << ";" << '\n' << '\n'; if (!flags.external_data) { // texture with scaled niveau lines // 10 lines in the surface out << "#declare Tex=texture{" << '\n' << " pigment {" << '\n' << " gradient y" << '\n' << " scale y*(HMAX-HMIN)*" << 0.1 << '\n' << " color_map {" << '\n' << " [0.00 color Light_Purple] " << '\n' << " [0.95 color Light_Purple] " << '\n' << " [1.00 color White] " << '\n' << "} } }" << '\n' << '\n'; } if (!flags.bicubic_patch) { // start of mesh header out << '\n' << "mesh {" << '\n'; } // loop over all patches for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch != patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; const unsigned int d1=1; const unsigned int d2=n; Assert ((patch->data.n_rows() == n_data_sets && !patch->points_are_available) || (patch->data.n_rows() == n_data_sets+spacedim && patch->points_are_available), ExcDimensionMismatch (patch->points_are_available ? (n_data_sets + spacedim) : n_data_sets, patch->data.n_rows())); Assert (patch->data.n_cols() == Utilities::fixed_power<dim>(n), ExcInvalidDatasetSize (patch->data.n_cols(), n_subdivisions+1)); std::vector<Point<spacedim> > ver(n*n); for (unsigned int i2=0; i2<n; ++i2) for (unsigned int i1=0; i1<n; ++i1) { // compute coordinates for // this patch point, storing in ver compute_node(ver[i1*d1+i2*d2], &*patch, i1, i2, 0, n_subdivisions); } if (!flags.bicubic_patch) { // approximate normal // vectors in patch std::vector<Point<3> > nrml; // only if smooth triangles are used if (flags.smooth) { nrml.resize(n*n); // These are // difference // quotients of // the surface // mapping. We // take them // symmetric // inside the // patch and // one-sided at // the edges Point<3> h1,h2; // Now compute normals in every point for (unsigned int i=0; i<n; ++i) for (unsigned int j=0; j<n; ++j) { const unsigned int il = (i==0) ? i : (i-1); const unsigned int ir = (i==n_subdivisions) ? i : (i+1); const unsigned int jl = (j==0) ? j : (j-1); const unsigned int jr = (j==n_subdivisions) ? j : (j+1); h1(0)=ver[ir*d1+j*d2](0) - ver[il*d1+j*d2](0); h1(1)=patch->data(0,ir*d1+j*d2)- patch->data(0,il*d1+j*d2); h1(2)=ver[ir*d1+j*d2](1) - ver[il*d1+j*d2](1); h2(0)=ver[i*d1+jr*d2](0) - ver[i*d1+jl*d2](0); h2(1)=patch->data(0,i*d1+jr*d2)- patch->data(0,i*d1+jl*d2); h2(2)=ver[i*d1+jr*d2](1) - ver[i*d1+jl*d2](1); nrml[i*d1+j*d2](0)=h1(1)*h2(2)-h1(2)*h2(1); nrml[i*d1+j*d2](1)=h1(2)*h2(0)-h1(0)*h2(2); nrml[i*d1+j*d2](2)=h1(0)*h2(1)-h1(1)*h2(0); // normalize Vector double norm=std::sqrt( std::pow(nrml[i*d1+j*d2](0),2.)+ std::pow(nrml[i*d1+j*d2](1),2.)+ std::pow(nrml[i*d1+j*d2](2),2.)); if (nrml[i*d1+j*d2](1)<0) norm*=-1.; for (unsigned int k=0; k<3; ++k) nrml[i*d1+j*d2](k)/=norm; } } // setting up triangles for (unsigned int i=0; i<n_subdivisions; ++i) for (unsigned int j=0; j<n_subdivisions; ++j) { // down/left vertex of triangle const int dl = i*d1+j*d2; if (flags.smooth) { // writing smooth_triangles // down/right triangle out << "smooth_triangle {" << '\n' << "\t<" << ver[dl](0) << "," << patch->data(0,dl) << "," << ver[dl](1) << ">, <" << nrml[dl](0) << ", " << nrml[dl](1) << ", " << nrml[dl](2) << ">," << '\n'; out << " \t<" << ver[dl+d1](0) << "," << patch->data(0,dl+d1) << "," << ver[dl+d1](1) << ">, <" << nrml[dl+d1](0) << ", " << nrml[dl+d1](1) << ", " << nrml[dl+d1](2) << ">," << '\n'; out << "\t<" << ver[dl+d1+d2](0) << "," << patch->data(0,dl+d1+d2) << "," << ver[dl+d1+d2](1) << ">, <" << nrml[dl+d1+d2](0) << ", " << nrml[dl+d1+d2](1) << ", " << nrml[dl+d1+d2](2) << ">}" << '\n'; // upper/left triangle out << "smooth_triangle {" << '\n' << "\t<" << ver[dl](0) << "," << patch->data(0,dl) << "," << ver[dl](1) << ">, <" << nrml[dl](0) << ", " << nrml[dl](1) << ", " << nrml[dl](2) << ">," << '\n'; out << "\t<" << ver[dl+d1+d2](0) << "," << patch->data(0,dl+d1+d2) << "," << ver[dl+d1+d2](1) << ">, <" << nrml[dl+d1+d2](0) << ", " << nrml[dl+d1+d2](1) << ", " << nrml[dl+d1+d2](2) << ">," << '\n'; out << "\t<" << ver[dl+d2](0) << "," << patch->data(0,dl+d2) << "," << ver[dl+d2](1) << ">, <" << nrml[dl+d2](0) << ", " << nrml[dl+d2](1) << ", " << nrml[dl+d2](2) << ">}" << '\n'; } else { // writing standard triangles // down/right triangle out << "triangle {" << '\n' << "\t<" << ver[dl](0) << "," << patch->data(0,dl) << "," << ver[dl](1) << ">," << '\n'; out << "\t<" << ver[dl+d1](0) << "," << patch->data(0,dl+d1) << "," << ver[dl+d1](1) << ">," << '\n'; out << "\t<" << ver[dl+d1+d2](0) << "," << patch->data(0,dl+d1+d2) << "," << ver[dl+d1+d2](1) << ">}" << '\n'; // upper/left triangle out << "triangle {" << '\n' << "\t<" << ver[dl](0) << "," << patch->data(0,dl) << "," << ver[dl](1) << ">," << '\n'; out << "\t<" << ver[dl+d1+d2](0) << "," << patch->data(0,dl+d1+d2) << "," << ver[dl+d1+d2](1) << ">," << '\n'; out << "\t<" << ver[dl+d2](0) << "," << patch->data(0,dl+d2) << "," << ver[dl+d2](1) << ">}" << '\n'; } } } else { // writing bicubic_patch Assert (n_subdivisions==3, ExcDimensionMismatch(n_subdivisions,3)); out << '\n' << "bicubic_patch {" << '\n' << " type 0" << '\n' << " flatness 0" << '\n' << " u_steps 0" << '\n' << " v_steps 0" << '\n'; for (int i=0; i<16; ++i) { out << "\t<" << ver[i](0) << "," << patch->data(0,i) << "," << ver[i](1) << ">"; if (i!=15) out << ","; out << '\n'; } out << " texture {Tex}" << '\n' << "}" << '\n'; } } if (!flags.bicubic_patch) { // the end of the mesh out << " texture {Tex}" << '\n' << "}" << '\n' << '\n'; } // make sure everything now gets to // disk out.flush (); AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_eps (const std::vector<Patch<dim,spacedim> > &/*patches*/, const std::vector<std::string> &/*data_names*/, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const EpsFlags &/*flags*/, std::ostream &/*out*/) { // not implemented, see the documentation of the function AssertThrow (dim==2, ExcNotImplemented()); } template <int spacedim> void write_eps (const std::vector<Patch<2,spacedim> > &patches, const std::vector<std::string> &/*data_names*/, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const EpsFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif const unsigned int old_precision = out.precision(); // set up an array of cells to be // written later. this array holds the // cells of all the patches as // projected to the plane perpendicular // to the line of sight. // // note that they are kept sorted by // the set, where we chose the value // of the center point of the cell // along the line of sight as value // for sorting std::multiset<EpsCell2d> cells; // two variables in which we // will store the minimum and // maximum values of the field // to be used for colorization // // preset them by 0 to calm down the // compiler; they are initialized later double min_color_value=0, max_color_value=0; // Array for z-coordinates of points. // The elevation determined by a function if spacedim=2 // or the z-cooridate of the grid point if spacedim=3 double heights[4] = { 0, 0, 0, 0 }; // compute the cells for output and // enter them into the set above // note that since dim==2, we // have exactly four vertices per // patch and per cell for (typename std::vector<Patch<2,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; const unsigned int d1 = 1; const unsigned int d2 = n; for (unsigned int i2=0; i2<n_subdivisions; ++i2) for (unsigned int i1=0; i1<n_subdivisions; ++i1) { Point<spacedim> points[4]; compute_node(points[0], &*patch, i1, i2, 0, n_subdivisions); compute_node(points[1], &*patch, i1+1, i2, 0, n_subdivisions); compute_node(points[2], &*patch, i1, i2+1, 0, n_subdivisions); compute_node(points[3], &*patch, i1+1, i2+1, 0, n_subdivisions); switch (spacedim) { case 2: Assert ((flags.height_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.height_vector, 0, patch->data.n_rows())); heights[0] = patch->data.n_rows() != 0 ? patch->data(flags.height_vector,i1*d1 + i2*d2) * flags.z_scaling : 0; heights[1] = patch->data.n_rows() != 0 ? patch->data(flags.height_vector,(i1+1)*d1 + i2*d2) * flags.z_scaling : 0; heights[2] = patch->data.n_rows() != 0 ? patch->data(flags.height_vector,i1*d1 + (i2+1)*d2) * flags.z_scaling : 0; heights[3] = patch->data.n_rows() != 0 ? patch->data(flags.height_vector,(i1+1)*d1 + (i2+1)*d2) * flags.z_scaling : 0; break; case 3: // Copy z-coordinates into the height vector for (unsigned int i=0; i<4; ++i) heights[i] = points[i](2); break; default: Assert(false, ExcNotImplemented()); } // now compute the projection of // the bilinear cell given by the // four vertices and their heights // and write them to a proper // cell object. note that we only // need the first two components // of the projected position for // output, but we need the value // along the line of sight for // sorting the cells for back-to- // front-output // // this computation was first written // by Stefan Nauber. please no-one // ask me why it works that way (or // may be not), especially not about // the angles and the sign of // the height field, I don't know // it. EpsCell2d eps_cell; const double pi = numbers::PI; const double cx = -std::cos(pi-flags.azimut_angle * 2*pi / 360.), cz = -std::cos(flags.turn_angle * 2*pi / 360.), sx = std::sin(pi-flags.azimut_angle * 2*pi / 360.), sz = std::sin(flags.turn_angle * 2*pi / 360.); for (unsigned int vertex=0; vertex<4; ++vertex) { const double x = points[vertex](0), y = points[vertex](1), z = -heights[vertex]; eps_cell.vertices[vertex](0) = - cz*x+ sz*y; eps_cell.vertices[vertex](1) = -cx*sz*x-cx*cz*y-sx*z; // ( 1 0 0 ) // D1 = ( 0 cx -sx ) // ( 0 sx cx ) // ( cy 0 sy ) // Dy = ( 0 1 0 ) // (-sy 0 cy ) // ( cz -sz 0 ) // Dz = ( sz cz 0 ) // ( 0 0 1 ) // ( cz -sz 0 )( 1 0 0 )(x) ( cz*x-sz*(cx*y-sx*z)+0*(sx*y+cx*z) ) // Dxz = ( sz cz 0 )( 0 cx -sx )(y) = ( sz*x+cz*(cx*y-sx*z)+0*(sx*y+cx*z) ) // ( 0 0 1 )( 0 sx cx )(z) ( 0*x+ *(cx*y-sx*z)+1*(sx*y+cx*z) ) } // compute coordinates of // center of cell const Point<spacedim> center_point = (points[0] + points[1] + points[2] + points[3]) / 4; const double center_height = -(heights[0] + heights[1] + heights[2] + heights[3]) / 4; // compute the depth into // the picture eps_cell.depth = -sx*sz*center_point(0) -sx*cz*center_point(1) +cx*center_height; if (flags.draw_cells && flags.shade_cells) { Assert ((flags.color_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.color_vector, 0, patch->data.n_rows())); const double color_values[4] = { patch->data.n_rows() != 0 ? patch->data(flags.color_vector,i1 *d1 + i2 *d2) : 1, patch->data.n_rows() != 0 ? patch->data(flags.color_vector,(i1+1)*d1 + i2 *d2) : 1, patch->data.n_rows() != 0 ? patch->data(flags.color_vector,i1 *d1 + (i2+1)*d2) : 1, patch->data.n_rows() != 0 ? patch->data(flags.color_vector,(i1+1)*d1 + (i2+1)*d2) : 1 }; // set color value to average of the value // at the vertices eps_cell.color_value = (color_values[0] + color_values[1] + color_values[3] + color_values[2]) / 4; // update bounds of color // field if (patch == patches.begin()) min_color_value = max_color_value = eps_cell.color_value; else { min_color_value = (min_color_value < eps_cell.color_value ? min_color_value : eps_cell.color_value); max_color_value = (max_color_value > eps_cell.color_value ? max_color_value : eps_cell.color_value); } } // finally add this cell cells.insert (eps_cell); } } // find out minimum and maximum x and // y coordinates to compute offsets // and scaling factors double x_min = cells.begin()->vertices[0](0); double x_max = x_min; double y_min = cells.begin()->vertices[0](1); double y_max = y_min; for (typename std::multiset<EpsCell2d>::const_iterator cell=cells.begin(); cell!=cells.end(); ++cell) for (unsigned int vertex=0; vertex<4; ++vertex) { x_min = std::min (x_min, cell->vertices[vertex](0)); x_max = std::max (x_max, cell->vertices[vertex](0)); y_min = std::min (y_min, cell->vertices[vertex](1)); y_max = std::max (y_max, cell->vertices[vertex](1)); } // scale in x-direction such that // in the output 0 <= x <= 300. // don't scale in y-direction to // preserve the shape of the // triangulation const double scale = (flags.size / (flags.size_type==EpsFlags::width ? x_max - x_min : y_min - y_max)); const Point<2> offset(x_min, y_min); // now write preamble if (true) { // block this to have local // variables destroyed after // use std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "%!PS-Adobe-2.0 EPSF-1.2" << '\n' << "%%Title: deal.II Output" << '\n' << "%%Creator: the deal.II library" << '\n' << "%%Creation Date: " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << " - " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << '\n' << "%%BoundingBox: " // lower left corner << "0 0 " // upper right corner << static_cast<unsigned int>( (x_max-x_min) * scale + 0.5) << ' ' << static_cast<unsigned int>( (y_max-y_min) * scale + 0.5) << '\n'; // define some abbreviations to keep // the output small: // m=move turtle to // l=define a line // s=set rgb color // sg=set gray value // lx=close the line and plot the line // lf=close the line and fill the interior out << "/m {moveto} bind def" << '\n' << "/l {lineto} bind def" << '\n' << "/s {setrgbcolor} bind def" << '\n' << "/sg {setgray} bind def" << '\n' << "/lx {lineto closepath stroke} bind def" << '\n' << "/lf {lineto closepath fill} bind def" << '\n'; out << "%%EndProlog" << '\n' << '\n'; // set fine lines out << flags.line_width << " setlinewidth" << '\n'; // allow only five digits // for output (instead of the // default six); this should suffice // even for fine grids, but reduces // the file size significantly out << std::setprecision (5); } // check if min and max // values for the color are // actually different. If // that is not the case (such // things happen, for // example, in the very first // time step of a time // dependent problem, if the // initial values are zero), // all values are equal, and // then we can draw // everything in an arbitrary // color. Thus, change one of // the two values arbitrarily if (max_color_value == min_color_value) max_color_value = min_color_value+1; // now we've got all the information // we need. write the cells. // note: due to the ordering, we // traverse the list of cells // back-to-front for (typename std::multiset<EpsCell2d>::const_iterator cell=cells.begin(); cell!=cells.end(); ++cell) { if (flags.draw_cells) { if (flags.shade_cells) { const EpsFlags::RgbValues rgb_values = (*flags.color_function) (cell->color_value, min_color_value, max_color_value); // write out color if (rgb_values.is_grey()) out << rgb_values.red << " sg "; else out << rgb_values.red << ' ' << rgb_values.green << ' ' << rgb_values.blue << " s "; } else out << "1 sg "; out << (cell->vertices[0]-offset) * scale << " m " << (cell->vertices[1]-offset) * scale << " l " << (cell->vertices[3]-offset) * scale << " l " << (cell->vertices[2]-offset) * scale << " lf" << '\n'; } if (flags.draw_mesh) out << "0 sg " // draw lines in black << (cell->vertices[0]-offset) * scale << " m " << (cell->vertices[1]-offset) * scale << " l " << (cell->vertices[3]-offset) * scale << " l " << (cell->vertices[2]-offset) * scale << " lx" << '\n'; } out << "showpage" << '\n'; // make sure everything now gets to // disk out << std::setprecision(old_precision); out.flush (); AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_gmv (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const GmvFlags &flags, std::ostream &out) { Assert(dim<=3, ExcNotImplemented()); AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif GmvStream gmv_out(out, flags); const unsigned int n_data_sets = data_names.size(); // check against # of data sets in // first patch. checks against all // other patches are made in // write_gmv_reorder_data_vectors Assert ((patches[0].data.n_rows() == n_data_sets && !patches[0].points_are_available) || (patches[0].data.n_rows() == n_data_sets+spacedim && patches[0].points_are_available), ExcDimensionMismatch (patches[0].points_are_available ? (n_data_sets + spacedim) : n_data_sets, patches[0].data.n_rows())); /////////////////////// // preamble out << "gmvinput ascii" << '\n' << '\n'; // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim>(patches, n_nodes, n_cells); // in gmv format the vertex // coordinates and the data have an // order that is a bit unpleasant // (first all x coordinates, then // all y coordinate, ...; first all // data of variable 1, then // variable 2, etc), so we have to // copy the data vectors a bit around // // note that we copy vectors when // looping over the patches since we // have to write them one variable // at a time and don't want to use // more than one loop // // this copying of data vectors can // be done while we already output // the vertices, so do this on a // separate task and when wanting // to write out the data, we wait // for that task to finish Table<2,double> data_vectors (n_data_sets, n_nodes); void (*fun_ptr) (const std::vector<Patch<dim,spacedim> > &, Table<2,double> &) = &write_gmv_reorder_data_vectors<dim,spacedim>; Threads::Task<> reorder_task = Threads::new_task (fun_ptr, patches, data_vectors); /////////////////////////////// // first make up a list of used // vertices along with their // coordinates // // note that we have to print // 3 dimensions out << "nodes " << n_nodes << '\n'; for (unsigned int d=0; d<spacedim; ++d) { gmv_out.selected_component = d; write_nodes(patches, gmv_out); out << '\n'; } gmv_out.selected_component = numbers::invalid_unsigned_int; for (unsigned int d=spacedim; d<3; ++d) { for (unsigned int i=0; i<n_nodes; ++i) out << "0 "; out << '\n'; } ///////////////////////////////// // now for the cells. note that // vertices are counted from 1 onwards out << "cells " << n_cells << '\n'; write_cells(patches, gmv_out); /////////////////////////////////////// // data output. out << "variable" << '\n'; // now write the data vectors to // @p{out} first make sure that all // data is in place reorder_task.join (); // then write data. // the '1' means: node data (as opposed // to cell data, which we do not // support explicitly here) for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) { out << data_names[data_set] << " 1" << '\n'; std::copy (data_vectors[data_set].begin(), data_vectors[data_set].end(), std::ostream_iterator<double>(out, " ")); out << '\n' << '\n'; } // end of variable section out << "endvars" << '\n'; // end of output out << "endgmv" << '\n'; // make sure everything now gets to // disk out.flush (); // assert the stream is still ok AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_tecplot (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const TecplotFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif TecplotStream tecplot_out(out, flags); const unsigned int n_data_sets = data_names.size(); // check against # of data sets in // first patch. checks against all // other patches are made in // write_gmv_reorder_data_vectors Assert ((patches[0].data.n_rows() == n_data_sets && !patches[0].points_are_available) || (patches[0].data.n_rows() == n_data_sets+spacedim && patches[0].points_are_available), ExcDimensionMismatch (patches[0].points_are_available ? (n_data_sets + spacedim) : n_data_sets, patches[0].data.n_rows())); // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim>(patches, n_nodes, n_cells); /////////// // preamble { std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "# This file was generated by the deal.II library." << '\n' << "# Date = " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << '\n' << "# Time = " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << '\n' << "#" << '\n' << "# For a description of the Tecplot format see the Tecplot documentation." << '\n' << "#" << '\n'; out << "Variables="; switch (spacedim) { case 1: out << "\"x\""; break; case 2: out << "\"x\", \"y\""; break; case 3: out << "\"x\", \"y\", \"z\""; break; default: Assert (false, ExcNotImplemented()); } for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) out << ", \"" << data_names[data_set] << "\""; out << '\n'; out << "zone "; if (flags.zone_name) out << "t=\"" << flags.zone_name << "\" "; out << "f=feblock, n=" << n_nodes << ", e=" << n_cells << ", et=" << tecplot_cell_type[dim] << '\n'; } // in Tecplot FEBLOCK format the vertex // coordinates and the data have an // order that is a bit unpleasant // (first all x coordinates, then // all y coordinate, ...; first all // data of variable 1, then // variable 2, etc), so we have to // copy the data vectors a bit around // // note that we copy vectors when // looping over the patches since we // have to write them one variable // at a time and don't want to use // more than one loop // // this copying of data vectors can // be done while we already output // the vertices, so do this on a // separate task and when wanting // to write out the data, we wait // for that task to finish Table<2,double> data_vectors (n_data_sets, n_nodes); void (*fun_ptr) (const std::vector<Patch<dim,spacedim> > &, Table<2,double> &) = &write_gmv_reorder_data_vectors<dim,spacedim>; Threads::Task<> reorder_task = Threads::new_task (fun_ptr, patches, data_vectors); /////////////////////////////// // first make up a list of used // vertices along with their // coordinates for (unsigned int d=0; d<spacedim; ++d) { tecplot_out.selected_component = d; write_nodes(patches, tecplot_out); out << '\n'; } /////////////////////////////////////// // data output. // // now write the data vectors to // @p{out} first make sure that all // data is in place reorder_task.join (); // then write data. for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) { std::copy (data_vectors[data_set].begin(), data_vectors[data_set].end(), std::ostream_iterator<double>(out, "\n")); out << '\n'; } write_cells(patches, tecplot_out); // make sure everything now gets to // disk out.flush (); // assert the stream is still ok AssertThrow (out, ExcIO()); } //--------------------------------------------------------------------------- // Macros for handling Tecplot API data #ifdef DEAL_II_HAVE_TECPLOT namespace { class TecplotMacros { public: TecplotMacros(const unsigned int n_nodes = 0, const unsigned int n_vars = 0, const unsigned int n_cells = 0, const unsigned int n_vert = 0); ~TecplotMacros(); float &nd(const unsigned int i, const unsigned int j); int &cd(const unsigned int i, const unsigned int j); std::vector<float> nodalData; std::vector<int> connData; private: unsigned int n_nodes; unsigned int n_vars; unsigned int n_cells; unsigned int n_vert; }; inline TecplotMacros::TecplotMacros(const unsigned int n_nodes, const unsigned int n_vars, const unsigned int n_cells, const unsigned int n_vert) : n_nodes(n_nodes), n_vars(n_vars), n_cells(n_cells), n_vert(n_vert) { nodalData.resize(n_nodes*n_vars); connData.resize(n_cells*n_vert); } inline TecplotMacros::~TecplotMacros() {} inline float &TecplotMacros::nd (const unsigned int i, const unsigned int j) { return nodalData[i*n_nodes+j]; } inline int &TecplotMacros::cd (const unsigned int i, const unsigned int j) { return connData[i+j*n_vert]; } } #endif //--------------------------------------------------------------------------- template <int dim, int spacedim> void write_tecplot_binary (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &vector_data_ranges, const TecplotFlags &flags, std::ostream &out) { #ifndef DEAL_II_HAVE_TECPLOT // simply call the ASCII output // function if the Tecplot API // isn't present write_tecplot (patches, data_names, vector_data_ranges, flags, out); return; #else // Tecplot binary output only good // for 2D & 3D if (dim == 1) { write_tecplot (patches, data_names, vector_data_ranges, flags, out); return; } // if the user hasn't specified a // file name we should call the // ASCII function and use the // ostream @p{out} instead of doing // something silly later char *file_name = (char *) flags.tecplot_binary_file_name; if (file_name == NULL) { // At least in debug mode we // should tell users why they // don't get tecplot binary // output Assert(false, ExcMessage("Specify the name of the tecplot_binary" " file through the TecplotFlags interface.")); write_tecplot (patches, data_names, vector_data_ranges, flags, out); return; } AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif const unsigned int n_data_sets = data_names.size(); // check against # of data sets in // first patch. checks against all // other patches are made in // write_gmv_reorder_data_vectors Assert ((patches[0].data.n_rows() == n_data_sets && !patches[0].points_are_available) || (patches[0].data.n_rows() == n_data_sets+spacedim && patches[0].points_are_available), ExcDimensionMismatch (patches[0].points_are_available ? (n_data_sets + spacedim) : n_data_sets, patches[0].data.n_rows())); // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim>(patches, n_nodes, n_cells); // local variables only needed to write Tecplot // binary output files const unsigned int vars_per_node = (spacedim+n_data_sets), nodes_per_cell = GeometryInfo<dim>::vertices_per_cell; TecplotMacros tm(n_nodes, vars_per_node, n_cells, nodes_per_cell); int is_double = 0, tec_debug = 0, cell_type = tecplot_binary_cell_type[dim]; std::string tec_var_names; switch (spacedim) { case 2: tec_var_names = "x y"; break; case 3: tec_var_names = "x y z"; break; default: Assert(false, ExcNotImplemented()); } for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) { tec_var_names += " "; tec_var_names += data_names[data_set]; } // in Tecplot FEBLOCK format the vertex // coordinates and the data have an // order that is a bit unpleasant // (first all x coordinates, then // all y coordinate, ...; first all // data of variable 1, then // variable 2, etc), so we have to // copy the data vectors a bit around // // note that we copy vectors when // looping over the patches since we // have to write them one variable // at a time and don't want to use // more than one loop // // this copying of data vectors can // be done while we already output // the vertices, so do this on a // separate task and when wanting // to write out the data, we wait // for that task to finish Table<2,double> data_vectors (n_data_sets, n_nodes); void (*fun_ptr) (const std::vector<Patch<dim,spacedim> > &, Table<2,double> &) = &write_gmv_reorder_data_vectors<dim,spacedim>; Threads::Task<> reorder_task = Threads::new_task (fun_ptr, patches, data_vectors); /////////////////////////////// // first make up a list of used // vertices along with their // coordinates for (unsigned int d=1; d<=spacedim; ++d) { unsigned int entry=0; for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; switch (dim) { case 2: { for (unsigned int j=0; j<n_subdivisions+1; ++j) for (unsigned int i=0; i<n_subdivisions+1; ++i) { const double x_frac = i * 1./n_subdivisions, y_frac = j * 1./n_subdivisions; tm.nd((d-1),entry) = static_cast<float>( (((patch->vertices[1](d-1) * x_frac) + (patch->vertices[0](d-1) * (1-x_frac))) * (1-y_frac) + ((patch->vertices[3](d-1) * x_frac) + (patch->vertices[2](d-1) * (1-x_frac))) * y_frac) ); entry++; } break; } case 3: { for (unsigned int j=0; j<n_subdivisions+1; ++j) for (unsigned int k=0; k<n_subdivisions+1; ++k) for (unsigned int i=0; i<n_subdivisions+1; ++i) { const double x_frac = i * 1./n_subdivisions, y_frac = k * 1./n_subdivisions, z_frac = j * 1./n_subdivisions; // compute coordinates for // this patch point tm.nd((d-1),entry) = static_cast<float>( ((((patch->vertices[1](d-1) * x_frac) + (patch->vertices[0](d-1) * (1-x_frac))) * (1-y_frac) + ((patch->vertices[3](d-1) * x_frac) + (patch->vertices[2](d-1) * (1-x_frac))) * y_frac) * (1-z_frac) + (((patch->vertices[5](d-1) * x_frac) + (patch->vertices[4](d-1) * (1-x_frac))) * (1-y_frac) + ((patch->vertices[7](d-1) * x_frac) + (patch->vertices[6](d-1) * (1-x_frac))) * y_frac) * z_frac) ); entry++; } break; } default: Assert (false, ExcNotImplemented()); } } } /////////////////////////////////////// // data output. // reorder_task.join (); // then write data. for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) for (unsigned int entry=0; entry<data_vectors[data_set].size(); entry++) tm.nd((spacedim+data_set),entry) = static_cast<float>(data_vectors[data_set][entry]); ///////////////////////////////// // now for the cells. note that // vertices are counted from 1 onwards unsigned int first_vertex_of_patch = 0; unsigned int elem=0; for (typename std::vector<Patch<dim,spacedim> >::const_iterator patch=patches.begin(); patch!=patches.end(); ++patch) { const unsigned int n_subdivisions = patch->n_subdivisions; const unsigned int n = n_subdivisions+1; const unsigned int d1=1; const unsigned int d2=n; const unsigned int d3=n*n; // write out the cells making // up this patch switch (dim) { case 2: { for (unsigned int i2=0; i2<n_subdivisions; ++i2) for (unsigned int i1=0; i1<n_subdivisions; ++i1) { tm.cd(0,elem) = first_vertex_of_patch+(i1 )*d1+(i2 )*d2+1; tm.cd(1,elem) = first_vertex_of_patch+(i1+1)*d1+(i2 )*d2+1; tm.cd(2,elem) = first_vertex_of_patch+(i1+1)*d1+(i2+1)*d2+1; tm.cd(3,elem) = first_vertex_of_patch+(i1 )*d1+(i2+1)*d2+1; elem++; } break; } case 3: { for (unsigned int i3=0; i3<n_subdivisions; ++i3) for (unsigned int i2=0; i2<n_subdivisions; ++i2) for (unsigned int i1=0; i1<n_subdivisions; ++i1) { // note: vertex indices start with 1! tm.cd(0,elem) = first_vertex_of_patch+(i1 )*d1+(i2 )*d2+(i3 )*d3+1; tm.cd(1,elem) = first_vertex_of_patch+(i1+1)*d1+(i2 )*d2+(i3 )*d3+1; tm.cd(2,elem) = first_vertex_of_patch+(i1+1)*d1+(i2+1)*d2+(i3 )*d3+1; tm.cd(3,elem) = first_vertex_of_patch+(i1 )*d1+(i2+1)*d2+(i3 )*d3+1; tm.cd(4,elem) = first_vertex_of_patch+(i1 )*d1+(i2 )*d2+(i3+1)*d3+1; tm.cd(5,elem) = first_vertex_of_patch+(i1+1)*d1+(i2 )*d2+(i3+1)*d3+1; tm.cd(6,elem) = first_vertex_of_patch+(i1+1)*d1+(i2+1)*d2+(i3+1)*d3+1; tm.cd(7,elem) = first_vertex_of_patch+(i1 )*d1+(i2+1)*d2+(i3+1)*d3+1; elem++; } break; } default: Assert (false, ExcNotImplemented()); } // finally update the number // of the first vertex of this patch first_vertex_of_patch += Utilities::fixed_power<dim>(n); } { int ierr = 0, num_nodes = static_cast<int>(n_nodes), num_cells = static_cast<int>(n_cells); char dot[2] = {'.', 0}; // Unfortunately, TECINI takes a // char *, but c_str() gives a // const char *. As we don't do // anything else with // tec_var_names following // const_cast is ok char *var_names=const_cast<char *> (tec_var_names.c_str()); ierr = TECINI (NULL, var_names, file_name, dot, &tec_debug, &is_double); Assert (ierr == 0, ExcErrorOpeningTecplotFile(file_name)); char FEBLOCK[] = {'F','E','B','L','O','C','K',0}; ierr = TECZNE (NULL, &num_nodes, &num_cells, &cell_type, FEBLOCK, NULL); Assert (ierr == 0, ExcTecplotAPIError()); int total = (vars_per_node*num_nodes); ierr = TECDAT (&total, &tm.nodalData[0], &is_double); Assert (ierr == 0, ExcTecplotAPIError()); ierr = TECNOD (&tm.connData[0]); Assert (ierr == 0, ExcTecplotAPIError()); ierr = TECEND (); Assert (ierr == 0, ExcTecplotAPIError()); } #endif } template <int dim, int spacedim> void write_vtk (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &vector_data_ranges, const VtkFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) return; #endif VtkStream vtk_out(out, flags); const unsigned int n_data_sets = data_names.size(); // check against # of data sets in // first patch. checks against all // other patches are made in // write_gmv_reorder_data_vectors Assert ((patches[0].data.n_rows() == n_data_sets && !patches[0].points_are_available) || (patches[0].data.n_rows() == n_data_sets+spacedim && patches[0].points_are_available), ExcDimensionMismatch (patches[0].points_are_available ? (n_data_sets + spacedim) : n_data_sets, patches[0].data.n_rows())); /////////////////////// // preamble { std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "# vtk DataFile Version 3.0" << '\n' << "#This file was generated by the deal.II library"; if (flags.print_date_and_time) out << " on " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << " at " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec; else out << "."; out << '\n' << "ASCII" << '\n'; // now output the data header out << "DATASET UNSTRUCTURED_GRID\n" << '\n'; } // if desired, output time and cycle of the simulation, following // the instructions at // http://www.visitusers.org/index.php?title=Time_and_Cycle_in_VTK_files { const unsigned int n_metadata = ((flags.cycle != std::numeric_limits<unsigned int>::min() ? 1 : 0) + (flags.time != std::numeric_limits<double>::min() ? 1 : 0)); if (n_metadata > 0) out << "FIELD FieldData " << n_metadata << "\n"; if (flags.cycle != std::numeric_limits<unsigned int>::min()) { out << "CYCLE 1 1 int\n" << flags.cycle << "\n"; } if (flags.time != std::numeric_limits<double>::min()) { out << "TIME 1 1 double\n" << flags.time << "\n"; } } // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim>(patches, n_nodes, n_cells); // in gmv format the vertex // coordinates and the data have an // order that is a bit unpleasant // (first all x coordinates, then // all y coordinate, ...; first all // data of variable 1, then // variable 2, etc), so we have to // copy the data vectors a bit around // // note that we copy vectors when // looping over the patches since we // have to write them one variable // at a time and don't want to use // more than one loop // // this copying of data vectors can // be done while we already output // the vertices, so do this on a // separate task and when wanting // to write out the data, we wait // for that task to finish Table<2,double> data_vectors (n_data_sets, n_nodes); void (*fun_ptr) (const std::vector<Patch<dim,spacedim> > &, Table<2,double> &) = &write_gmv_reorder_data_vectors<dim,spacedim>; Threads::Task<> reorder_task = Threads::new_task (fun_ptr, patches, data_vectors); /////////////////////////////// // first make up a list of used // vertices along with their // coordinates // // note that we have to print // d=1..3 dimensions out << "POINTS " << n_nodes << " double" << '\n'; write_nodes(patches, vtk_out); out << '\n'; ///////////////////////////////// // now for the cells out << "CELLS " << n_cells << ' ' << n_cells*(GeometryInfo<dim>::vertices_per_cell+1) << '\n'; write_cells(patches, vtk_out); out << '\n'; // next output the types of the // cells. since all cells are // the same, this is simple out << "CELL_TYPES " << n_cells << '\n'; for (unsigned int i=0; i<n_cells; ++i) out << ' ' << vtk_cell_type[dim]; out << '\n'; /////////////////////////////////////// // data output. // now write the data vectors to // @p{out} first make sure that all // data is in place reorder_task.join (); // then write data. the // 'POINT_DATA' means: node data // (as opposed to cell data, which // we do not support explicitly // here). all following data sets // are point data out << "POINT_DATA " << n_nodes << '\n'; // when writing, first write out // all vector data, then handle the // scalar data sets that have been // left over std::vector<bool> data_set_written (n_data_sets, false); for (unsigned int n_th_vector=0; n_th_vector<vector_data_ranges.size(); ++n_th_vector) { AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) >= std_cxx11::get<0>(vector_data_ranges[n_th_vector]), ExcLowerRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), std_cxx11::get<0>(vector_data_ranges[n_th_vector]))); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) < n_data_sets, ExcIndexRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), 0, n_data_sets)); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) + 1 - std_cxx11::get<0>(vector_data_ranges[n_th_vector]) <= 3, ExcMessage ("Can't declare a vector with more than 3 components " "in VTK")); // mark these components as already written: for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<=std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) data_set_written[i] = true; // write the // header. concatenate all the // component names with double // underscores unless a vector // name has been specified out << "VECTORS "; if (std_cxx11::get<2>(vector_data_ranges[n_th_vector]) != "") out << std_cxx11::get<2>(vector_data_ranges[n_th_vector]); else { for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) out << data_names[i] << "__"; out << data_names[std_cxx11::get<1>(vector_data_ranges[n_th_vector])]; } out << " double" << '\n'; // now write data. pad all // vectors to have three // components for (unsigned int n=0; n<n_nodes; ++n) { switch (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) - std_cxx11::get<0>(vector_data_ranges[n_th_vector])) { case 0: out << data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector]), n) << " 0 0" << '\n'; break; case 1: out << data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector]), n) << ' '<< data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector])+1, n) << " 0" << '\n'; break; case 2: out << data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector]), n) << ' '<< data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector])+1, n) << ' '<< data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector])+2, n) << '\n'; break; default: // VTK doesn't // support // anything else // than vectors // with 1, 2, or // 3 components Assert (false, ExcInternalError()); } } } // now do the left over scalar data sets for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) if (data_set_written[data_set] == false) { out << "SCALARS " << data_names[data_set] << " double 1" << '\n' << "LOOKUP_TABLE default" << '\n'; std::copy (data_vectors[data_set].begin(), data_vectors[data_set].end(), std::ostream_iterator<double>(out, " ")); out << '\n'; } // make sure everything now gets to // disk out.flush (); // assert the stream is still ok AssertThrow (out, ExcIO()); } void write_vtu_header (std::ostream &out, const VtkFlags &flags) { AssertThrow (out, ExcIO()); std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "<?xml version=\"1.0\" ?> \n"; out << "<!-- \n"; out << "# vtk DataFile Version 3.0" << '\n' << "#This file was generated by the deal.II library"; if (flags.print_date_and_time) out << " on " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << " at " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec; else out << "."; out << "\n-->\n"; out << "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\""; #ifdef DEAL_II_WITH_ZLIB out << " compressor=\"vtkZLibDataCompressor\""; #endif #ifdef DEAL_II_WORDS_BIGENDIAN out << " byte_order=\"BigEndian\""; #else out << " byte_order=\"LittleEndian\""; #endif out << ">"; out << '\n'; out << "<UnstructuredGrid>"; out << '\n'; } void write_vtu_footer (std::ostream &out) { AssertThrow (out, ExcIO()); out << " </UnstructuredGrid>\n"; out << "</VTKFile>\n"; } template <int dim, int spacedim> void write_vtu (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &vector_data_ranges, const VtkFlags &flags, std::ostream &out) { write_vtu_header(out, flags); write_vtu_main (patches, data_names, vector_data_ranges, flags, out); write_vtu_footer(out); out << std::flush; } template <int dim, int spacedim> void write_vtu_main (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &vector_data_ranges, const VtkFlags &flags, std::ostream &out) { AssertThrow (out, ExcIO()); #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #else if (patches.size() == 0) { // we still need to output a valid vtu file, because other CPUs // might output data. This is the minimal file that is accepted by paraview and visit. // if we remove the field definitions, visit is complaining. out << "<Piece NumberOfPoints=\"0\" NumberOfCells=\"0\" >\n" << "<Cells>\n" << "<DataArray type=\"UInt8\" Name=\"types\"></DataArray>\n" << "</Cells>\n" << " <PointData Scalars=\"scalars\">\n"; std::vector<bool> data_set_written (data_names.size(), false); for (unsigned int n_th_vector=0; n_th_vector<vector_data_ranges.size(); ++n_th_vector) { // mark these components as already // written: for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<=std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) data_set_written[i] = true; // write the // header. concatenate all the // component names with double // underscores unless a vector // name has been specified out << " <DataArray type=\"Float64\" Name=\""; if (std_cxx11::get<2>(vector_data_ranges[n_th_vector]) != "") out << std_cxx11::get<2>(vector_data_ranges[n_th_vector]); else { for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) out << data_names[i] << "__"; out << data_names[std_cxx11::get<1>(vector_data_ranges[n_th_vector])]; } out << "\" NumberOfComponents=\"3\"></DataArray>\n"; } for (unsigned int data_set=0; data_set<data_names.size(); ++data_set) if (data_set_written[data_set] == false) { out << " <DataArray type=\"Float64\" Name=\"" << data_names[data_set] << "\"></DataArray>\n"; } out << " </PointData>\n"; out << "</Piece>\n"; out << std::flush; return; } #endif // first up: metadata // // if desired, output time and cycle of the simulation, following // the instructions at // http://www.visitusers.org/index.php?title=Time_and_Cycle_in_VTK_files { const unsigned int n_metadata = ((flags.cycle != std::numeric_limits<unsigned int>::min() ? 1 : 0) + (flags.time != std::numeric_limits<double>::min() ? 1 : 0)); if (n_metadata > 0) out << "<FieldData>\n"; if (flags.cycle != std::numeric_limits<unsigned int>::min()) { out << "<DataArray type=\"Float32\" Name=\"CYCLE\" NumberOfTuples=\"1\" format=\"ascii\">" << flags.cycle << "</DataArray>\n"; } if (flags.time != std::numeric_limits<double>::min()) { out << "<DataArray type=\"Float32\" Name=\"TIME\" NumberOfTuples=\"1\" format=\"ascii\">" << flags.time << "</DataArray>\n"; } if (n_metadata > 0) out << "</FieldData>\n"; } VtuStream vtu_out(out, flags); const unsigned int n_data_sets = data_names.size(); // check against # of data sets in // first patch. checks against all // other patches are made in // write_gmv_reorder_data_vectors Assert ((patches[0].data.n_rows() == n_data_sets && !patches[0].points_are_available) || (patches[0].data.n_rows() == n_data_sets+spacedim && patches[0].points_are_available), ExcDimensionMismatch (patches[0].points_are_available ? (n_data_sets + spacedim) : n_data_sets, patches[0].data.n_rows())); #ifdef DEAL_II_WITH_ZLIB const char *ascii_or_binary = "binary"; #else const char *ascii_or_binary = "ascii"; #endif // first count the number of cells // and cells for later use unsigned int n_nodes; unsigned int n_cells; compute_sizes<dim,spacedim>(patches, n_nodes, n_cells); // in gmv format the vertex // coordinates and the data have an // order that is a bit unpleasant // (first all x coordinates, then // all y coordinate, ...; first all // data of variable 1, then // variable 2, etc), so we have to // copy the data vectors a bit around // // note that we copy vectors when // looping over the patches since we // have to write them one variable // at a time and don't want to use // more than one loop // // this copying of data vectors can // be done while we already output // the vertices, so do this on a // separate task and when wanting // to write out the data, we wait // for that task to finish Table<2,double> data_vectors (n_data_sets, n_nodes); void (*fun_ptr) (const std::vector<Patch<dim,spacedim> > &, Table<2,double> &) = &write_gmv_reorder_data_vectors<dim,spacedim>; Threads::Task<> reorder_task = Threads::new_task (fun_ptr, patches, data_vectors); /////////////////////////////// // first make up a list of used // vertices along with their // coordinates // // note that according to the standard, we // have to print d=1..3 dimensions, even if // we are in reality in 2d, for example out << "<Piece NumberOfPoints=\"" << n_nodes <<"\" NumberOfCells=\"" << n_cells << "\" >\n"; out << " <Points>\n"; out << " <DataArray type=\"Float64\" NumberOfComponents=\"3\" format=\"" << ascii_or_binary << "\">\n"; write_nodes(patches, vtu_out); out << " </DataArray>\n"; out << " </Points>\n\n"; ///////////////////////////////// // now for the cells out << " <Cells>\n"; out << " <DataArray type=\"Int32\" Name=\"connectivity\" format=\"" << ascii_or_binary << "\">\n"; write_cells(patches, vtu_out); out << " </DataArray>\n"; // XML VTU format uses offsets; this is // different than the VTK format, which // puts the number of nodes per cell in // front of the connectivity list. out << " <DataArray type=\"Int32\" Name=\"offsets\" format=\"" << ascii_or_binary << "\">\n"; std::vector<int32_t> offsets (n_cells); for (unsigned int i=0; i<n_cells; ++i) offsets[i] = (i+1)*GeometryInfo<dim>::vertices_per_cell; vtu_out << offsets; out << "\n"; out << " </DataArray>\n"; // next output the types of the // cells. since all cells are // the same, this is simple out << " <DataArray type=\"UInt8\" Name=\"types\" format=\"" << ascii_or_binary << "\">\n"; { // uint8_t might be a typedef to unsigned // char which is then not printed as // ascii integers #ifdef DEAL_II_WITH_ZLIB std::vector<uint8_t> cell_types (n_cells, static_cast<uint8_t>(vtk_cell_type[dim])); #else std::vector<unsigned int> cell_types (n_cells, vtk_cell_type[dim]); #endif // this should compress well :-) vtu_out << cell_types; } out << "\n"; out << " </DataArray>\n"; out << " </Cells>\n"; /////////////////////////////////////// // data output. // now write the data vectors to // @p{out} first make sure that all // data is in place reorder_task.join (); // then write data. the // 'POINT_DATA' means: node data // (as opposed to cell data, which // we do not support explicitly // here). all following data sets // are point data out << " <PointData Scalars=\"scalars\">\n"; // when writing, first write out // all vector data, then handle the // scalar data sets that have been // left over std::vector<bool> data_set_written (n_data_sets, false); for (unsigned int n_th_vector=0; n_th_vector<vector_data_ranges.size(); ++n_th_vector) { AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) >= std_cxx11::get<0>(vector_data_ranges[n_th_vector]), ExcLowerRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), std_cxx11::get<0>(vector_data_ranges[n_th_vector]))); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) < n_data_sets, ExcIndexRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), 0, n_data_sets)); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) + 1 - std_cxx11::get<0>(vector_data_ranges[n_th_vector]) <= 3, ExcMessage ("Can't declare a vector with more than 3 components " "in VTK")); // mark these components as already // written: for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<=std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) data_set_written[i] = true; // write the // header. concatenate all the // component names with double // underscores unless a vector // name has been specified out << " <DataArray type=\"Float64\" Name=\""; if (std_cxx11::get<2>(vector_data_ranges[n_th_vector]) != "") out << std_cxx11::get<2>(vector_data_ranges[n_th_vector]); else { for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) out << data_names[i] << "__"; out << data_names[std_cxx11::get<1>(vector_data_ranges[n_th_vector])]; } out << "\" NumberOfComponents=\"3\" format=\"" << ascii_or_binary << "\">\n"; // now write data. pad all // vectors to have three // components std::vector<double> data; data.reserve (n_nodes*dim); for (unsigned int n=0; n<n_nodes; ++n) { switch (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) - std_cxx11::get<0>(vector_data_ranges[n_th_vector])) { case 0: data.push_back (data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector]), n)); data.push_back (0); data.push_back (0); break; case 1: data.push_back (data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector]), n)); data.push_back (data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector])+1, n)); data.push_back (0); break; case 2: data.push_back (data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector]), n)); data.push_back (data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector])+1, n)); data.push_back (data_vectors(std_cxx11::get<0>(vector_data_ranges[n_th_vector])+2, n)); break; default: // VTK doesn't // support // anything else // than vectors // with 1, 2, or // 3 components Assert (false, ExcInternalError()); } } vtu_out << data; out << " </DataArray>\n"; } // now do the left over scalar data sets for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) if (data_set_written[data_set] == false) { out << " <DataArray type=\"Float64\" Name=\"" << data_names[data_set] << "\" format=\"" << ascii_or_binary << "\">\n"; std::vector<double> data (data_vectors[data_set].begin(), data_vectors[data_set].end()); vtu_out << data; out << " </DataArray>\n"; } out << " </PointData>\n"; // Finish up writing a valid XML file out << " </Piece>\n"; // make sure everything now gets to // disk out.flush (); // assert the stream is still ok AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void write_svg (const std::vector<Patch<dim,spacedim> > &, const std::vector<std::string> &, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &, const SvgFlags &, std::ostream &) { Assert (false, ExcNotImplemented()); } template <int spacedim> void write_svg (const std::vector<Patch<2,spacedim> > &patches, const std::vector<std::string> &/*data_names*/, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &/*vector_data_ranges*/, const SvgFlags &flags, std::ostream &out) { const int dim = 2; const unsigned int height = flags.height; unsigned int width = flags.width; // margin around the plotted area unsigned int margin_in_percent = 0; if (flags.margin) margin_in_percent = 5; // determine the bounding box in the model space double x_dimension, y_dimension, z_dimension; typename std::vector<Patch<dim,spacedim> >::const_iterator patch = patches.begin(); unsigned int n_subdivisions = patch->n_subdivisions; unsigned int n = n_subdivisions + 1; const unsigned int d1 = 1; const unsigned int d2 = n; Point<spacedim> projected_point; Point<spacedim> projected_points[4]; Point<2> projection_decomposition; Point<2> projection_decompositions[4]; compute_node(projected_point, &*patch, 0, 0, 0, n_subdivisions); Assert ((flags.height_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.height_vector, 0, patch->data.n_rows())); double x_min = projected_point[0]; double x_max = x_min; double y_min = projected_point[1]; double y_max = y_min; double z_min = patch->data.n_rows() != 0 ? patch->data(flags.height_vector,0) : 0; double z_max = z_min; // iterate over the patches for (; patch != patches.end(); ++patch) { n_subdivisions = patch->n_subdivisions; n = n_subdivisions + 1; for (unsigned int i2 = 0; i2 < n_subdivisions; ++i2) { for (unsigned int i1 = 0; i1 < n_subdivisions; ++i1) { compute_node(projected_points[0], &*patch, i1, i2, 0, n_subdivisions); compute_node(projected_points[1], &*patch, i1+1, i2, 0, n_subdivisions); compute_node(projected_points[2], &*patch, i1, i2+1, 0, n_subdivisions); compute_node(projected_points[3], &*patch, i1+1, i2+1, 0, n_subdivisions); x_min = std::min(x_min, (double)projected_points[0][0]); x_min = std::min(x_min, (double)projected_points[1][0]); x_min = std::min(x_min, (double)projected_points[2][0]); x_min = std::min(x_min, (double)projected_points[3][0]); x_max = std::max(x_max, (double)projected_points[0][0]); x_max = std::max(x_max, (double)projected_points[1][0]); x_max = std::max(x_max, (double)projected_points[2][0]); x_max = std::max(x_max, (double)projected_points[3][0]); y_min = std::min(y_min, (double)projected_points[0][1]); y_min = std::min(y_min, (double)projected_points[1][1]); y_min = std::min(y_min, (double)projected_points[2][1]); y_min = std::min(y_min, (double)projected_points[3][1]); y_max = std::max(y_max, (double)projected_points[0][1]); y_max = std::max(y_max, (double)projected_points[1][1]); y_max = std::max(y_max, (double)projected_points[2][1]); y_max = std::max(y_max, (double)projected_points[3][1]); Assert ((flags.height_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.height_vector, 0, patch->data.n_rows())); z_min = std::min(z_min, (double)patch->data(flags.height_vector, i1*d1 + i2*d2)); z_min = std::min(z_min, (double)patch->data(flags.height_vector, (i1+1)*d1 + i2*d2)); z_min = std::min(z_min, (double)patch->data(flags.height_vector, i1*d1 + (i2+1)*d2)); z_min = std::min(z_min, (double)patch->data(flags.height_vector, (i1+1)*d1 + (i2+1)*d2)); z_max = std::max(z_max, (double)patch->data(flags.height_vector, i1*d1 + i2*d2)); z_max = std::max(z_max, (double)patch->data(flags.height_vector, (i1+1)*d1 + i2*d2)); z_max = std::max(z_max, (double)patch->data(flags.height_vector, i1*d1 + (i2+1)*d2)); z_max = std::max(z_max, (double)patch->data(flags.height_vector, (i1+1)*d1 + (i2+1)*d2)); } } } x_dimension = x_max - x_min; y_dimension = y_max - y_min; z_dimension = z_max - z_min; // set initial camera position Point<3> camera_position(true); Point<3> camera_direction(true); Point<3> camera_horizontal(true); float camera_focus = 0; // translate camera from the origin to the initial position camera_position[0] = 0.; camera_position[1] = 0.; camera_position[2] = z_min + 2. * z_dimension; camera_direction[0] = 0.; camera_direction[1] = 0.; camera_direction[2] = - 1.; camera_horizontal[0] = 1.; camera_horizontal[1] = 0.; camera_horizontal[2] = 0.; camera_focus = .5 * z_dimension; Point<3> camera_position_temp; Point<3> camera_direction_temp; Point<3> camera_horizontal_temp; const float angle_factor = 3.14159265 / 180.; // (I) rotate the camera to the chosen polar angle camera_position_temp[1] = cos(angle_factor * flags.polar_angle) * camera_position[1] - sin(angle_factor * flags.polar_angle) * camera_position[2]; camera_position_temp[2] = sin(angle_factor * flags.polar_angle) * camera_position[1] + cos(angle_factor * flags.polar_angle) * camera_position[2]; camera_direction_temp[1] = cos(angle_factor * flags.polar_angle) * camera_direction[1] - sin(angle_factor * flags.polar_angle) * camera_direction[2]; camera_direction_temp[2] = sin(angle_factor * flags.polar_angle) * camera_direction[1] + cos(angle_factor * flags.polar_angle) * camera_direction[2]; camera_horizontal_temp[1] = cos(angle_factor * flags.polar_angle) * camera_horizontal[1] - sin(angle_factor * flags.polar_angle) * camera_horizontal[2]; camera_horizontal_temp[2] = sin(angle_factor * flags.polar_angle) * camera_horizontal[1] + cos(angle_factor * flags.polar_angle) * camera_horizontal[2]; camera_position[1] = camera_position_temp[1]; camera_position[2] = camera_position_temp[2]; camera_direction[1] = camera_direction_temp[1]; camera_direction[2] = camera_direction_temp[2]; camera_horizontal[1] = camera_horizontal_temp[1]; camera_horizontal[2] = camera_horizontal_temp[2]; // (II) rotate the camera to the chosen azimuth angle camera_position_temp[0] = cos(angle_factor * flags.azimuth_angle) * camera_position[0] - sin(angle_factor * flags.azimuth_angle) * camera_position[1]; camera_position_temp[1] = sin(angle_factor * flags.azimuth_angle) * camera_position[0] + cos(angle_factor * flags.azimuth_angle) * camera_position[1]; camera_direction_temp[0] = cos(angle_factor * flags.azimuth_angle) * camera_direction[0] - sin(angle_factor * flags.azimuth_angle) * camera_direction[1]; camera_direction_temp[1] = sin(angle_factor * flags.azimuth_angle) * camera_direction[0] + cos(angle_factor * flags.azimuth_angle) * camera_direction[1]; camera_horizontal_temp[0] = cos(angle_factor * flags.azimuth_angle) * camera_horizontal[0] - sin(angle_factor * flags.azimuth_angle) * camera_horizontal[1]; camera_horizontal_temp[1] = sin(angle_factor * flags.azimuth_angle) * camera_horizontal[0] + cos(angle_factor * flags.azimuth_angle) * camera_horizontal[1]; camera_position[0] = camera_position_temp[0]; camera_position[1] = camera_position_temp[1]; camera_direction[0] = camera_direction_temp[0]; camera_direction[1] = camera_direction_temp[1]; camera_horizontal[0] = camera_horizontal_temp[0]; camera_horizontal[1] = camera_horizontal_temp[1]; // (III) translate the camera camera_position[0] = x_min + .5 * x_dimension; camera_position[1] = y_min + .5 * y_dimension; camera_position[0] += (z_min + 2. * z_dimension) * sin(angle_factor * flags.polar_angle) * sin(angle_factor * flags.azimuth_angle); camera_position[1] -= (z_min + 2. * z_dimension) * sin(angle_factor * flags.polar_angle) * cos(angle_factor * flags.azimuth_angle); // determine the bounding box on the projection plane double x_min_perspective, y_min_perspective; double x_max_perspective, y_max_perspective; double x_dimension_perspective, y_dimension_perspective; patch = patches.begin(); n_subdivisions = patch->n_subdivisions; n = n_subdivisions + 1; Point<3> point(true); compute_node(projected_point, &*patch, 0, 0, 0, n_subdivisions); Assert ((flags.height_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.height_vector, 0, patch->data.n_rows())); point[0] = projected_point[0]; point[1] = projected_point[1]; point[2] = patch->data.n_rows() != 0 ? patch->data(flags.height_vector, 0) : 0; projection_decomposition = svg_project_point(point, camera_position, camera_direction, camera_horizontal, camera_focus); x_min_perspective = projection_decomposition[0]; x_max_perspective = projection_decomposition[0]; y_min_perspective = projection_decomposition[1]; y_max_perspective = projection_decomposition[1]; // iterate over the patches for (; patch != patches.end(); ++patch) { n_subdivisions = patch->n_subdivisions; n = n_subdivisions + 1; for (unsigned int i2 = 0; i2 < n_subdivisions; ++i2) { for (unsigned int i1 = 0; i1 < n_subdivisions; ++i1) { Point<spacedim> projected_vertices[4]; Point<3> vertices[4]; compute_node(projected_vertices[0], &*patch, i1, i2, 0, n_subdivisions); compute_node(projected_vertices[1], &*patch, i1+1, i2, 0, n_subdivisions); compute_node(projected_vertices[2], &*patch, i1, i2+1, 0, n_subdivisions); compute_node(projected_vertices[3], &*patch, i1+1, i2+1, 0, n_subdivisions); Assert ((flags.height_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.height_vector, 0, patch->data.n_rows())); vertices[0][0] = projected_vertices[0][0]; vertices[0][1] = projected_vertices[0][1]; vertices[0][2] = patch->data.n_rows() != 0 ? patch->data(0,i1*d1 + i2*d2) : 0; vertices[1][0] = projected_vertices[1][0]; vertices[1][1] = projected_vertices[1][1]; vertices[1][2] = patch->data.n_rows() != 0 ? patch->data(0,(i1+1)*d1 + i2*d2) : 0; vertices[2][0] = projected_vertices[2][0]; vertices[2][1] = projected_vertices[2][1]; vertices[2][2] = patch->data.n_rows() != 0 ? patch->data(0,i1*d1 + (i2+1)*d2) : 0; vertices[3][0] = projected_vertices[3][0]; vertices[3][1] = projected_vertices[3][1]; vertices[3][2] = patch->data.n_rows() != 0 ? patch->data(0,(i1+1)*d1 + (i2+1)*d2) : 0; projection_decompositions[0] = svg_project_point(vertices[0], camera_position, camera_direction, camera_horizontal, camera_focus); projection_decompositions[1] = svg_project_point(vertices[1], camera_position, camera_direction, camera_horizontal, camera_focus); projection_decompositions[2] = svg_project_point(vertices[2], camera_position, camera_direction, camera_horizontal, camera_focus); projection_decompositions[3] = svg_project_point(vertices[3], camera_position, camera_direction, camera_horizontal, camera_focus); x_min_perspective = std::min(x_min_perspective, (double)projection_decompositions[0][0]); x_min_perspective = std::min(x_min_perspective, (double)projection_decompositions[1][0]); x_min_perspective = std::min(x_min_perspective, (double)projection_decompositions[2][0]); x_min_perspective = std::min(x_min_perspective, (double)projection_decompositions[3][0]); x_max_perspective = std::max(x_max_perspective, (double)projection_decompositions[0][0]); x_max_perspective = std::max(x_max_perspective, (double)projection_decompositions[1][0]); x_max_perspective = std::max(x_max_perspective, (double)projection_decompositions[2][0]); x_max_perspective = std::max(x_max_perspective, (double)projection_decompositions[3][0]); y_min_perspective = std::min(y_min_perspective, (double)projection_decompositions[0][1]); y_min_perspective = std::min(y_min_perspective, (double)projection_decompositions[1][1]); y_min_perspective = std::min(y_min_perspective, (double)projection_decompositions[2][1]); y_min_perspective = std::min(y_min_perspective, (double)projection_decompositions[3][1]); y_max_perspective = std::max(y_max_perspective, (double)projection_decompositions[0][1]); y_max_perspective = std::max(y_max_perspective, (double)projection_decompositions[1][1]); y_max_perspective = std::max(y_max_perspective, (double)projection_decompositions[2][1]); y_max_perspective = std::max(y_max_perspective, (double)projection_decompositions[3][1]); } } } x_dimension_perspective = x_max_perspective - x_min_perspective; y_dimension_perspective = y_max_perspective - y_min_perspective; std::multiset<SvgCell> cells; // iterate over the patches for (patch = patches.begin(); patch != patches.end(); ++patch) { n_subdivisions = patch->n_subdivisions; n = n_subdivisions + 1; for (unsigned int i2 = 0; i2 < n_subdivisions; ++i2) { for (unsigned int i1 = 0; i1 < n_subdivisions; ++i1) { Point<spacedim> projected_vertices[4]; SvgCell cell; compute_node(projected_vertices[0], &*patch, i1, i2, 0, n_subdivisions); compute_node(projected_vertices[1], &*patch, i1+1, i2, 0, n_subdivisions); compute_node(projected_vertices[2], &*patch, i1, i2+1, 0, n_subdivisions); compute_node(projected_vertices[3], &*patch, i1+1, i2+1, 0, n_subdivisions); Assert ((flags.height_vector < patch->data.n_rows()) || patch->data.n_rows() == 0, ExcIndexRange (flags.height_vector, 0, patch->data.n_rows())); cell.vertices[0][0] = projected_vertices[0][0]; cell.vertices[0][1] = projected_vertices[0][1]; cell.vertices[0][2] = patch->data.n_rows() != 0 ? patch->data(0,i1*d1 + i2*d2) : 0; cell.vertices[1][0] = projected_vertices[1][0]; cell.vertices[1][1] = projected_vertices[1][1]; cell.vertices[1][2] = patch->data.n_rows() != 0 ? patch->data(0,(i1+1)*d1 + i2*d2) : 0; cell.vertices[2][0] = projected_vertices[2][0]; cell.vertices[2][1] = projected_vertices[2][1]; cell.vertices[2][2] = patch->data.n_rows() != 0 ? patch->data(0,i1*d1 + (i2+1)*d2) : 0; cell.vertices[3][0] = projected_vertices[3][0]; cell.vertices[3][1] = projected_vertices[3][1]; cell.vertices[3][2] = patch->data.n_rows() != 0 ? patch->data(0,(i1+1)*d1 + (i2+1)*d2) : 0; cell.projected_vertices[0] = svg_project_point(cell.vertices[0], camera_position, camera_direction, camera_horizontal, camera_focus); cell.projected_vertices[1] = svg_project_point(cell.vertices[1], camera_position, camera_direction, camera_horizontal, camera_focus); cell.projected_vertices[2] = svg_project_point(cell.vertices[2], camera_position, camera_direction, camera_horizontal, camera_focus); cell.projected_vertices[3] = svg_project_point(cell.vertices[3], camera_position, camera_direction, camera_horizontal, camera_focus); cell.center = .25 * (cell.vertices[0] + cell.vertices[1] + cell.vertices[2] + cell.vertices[3]); cell.projected_center = svg_project_point(cell.center, camera_position, camera_direction, camera_horizontal, camera_focus); cell.depth = cell.center.distance(camera_position); cells.insert(cell); } } } // write the svg file if (width==0) width = static_cast<unsigned int>(.5 + height * (x_dimension_perspective / y_dimension_perspective)); unsigned int additional_width = 0; if (flags.draw_colorbar) additional_width = static_cast<unsigned int>(.5 + height * .3); // additional width for colorbar // basic svg header and background rectangle out << "<svg width=\"" << width + additional_width << "\" height=\"" << height << "\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">" << '\n' << " <rect width=\"" << width + additional_width << "\" height=\"" << height << "\" style=\"fill:white\"/>" << '\n' << '\n'; unsigned int triangle_counter = 0; // write the cells in the correct order for (typename std::multiset<SvgCell>::const_iterator cell = cells.begin(); cell != cells.end(); ++cell) { Point<3> points3d_triangle[3]; for (unsigned int triangle_index = 0; triangle_index < 4; triangle_index++) { switch (triangle_index) { case 0: points3d_triangle[0] = cell->vertices[0], points3d_triangle[1] = cell->vertices[1], points3d_triangle[2] = cell->center; break; case 1: points3d_triangle[0] = cell->vertices[1], points3d_triangle[1] = cell->vertices[3], points3d_triangle[2] = cell->center; break; case 2: points3d_triangle[0] = cell->vertices[3], points3d_triangle[1] = cell->vertices[2], points3d_triangle[2] = cell->center; break; case 3: points3d_triangle[0] = cell->vertices[2], points3d_triangle[1] = cell->vertices[0], points3d_triangle[2] = cell->center; break; default: break; } Point<6> gradient_param = svg_get_gradient_parameters(points3d_triangle); double start_h = .667 - ((gradient_param[4] - z_min) / z_dimension) * .667; double stop_h = .667 - ((gradient_param[5] - z_min) / z_dimension) * .667; unsigned int start_r = 0; unsigned int start_g = 0; unsigned int start_b = 0; unsigned int stop_r = 0; unsigned int stop_g = 0; unsigned int stop_b = 0; unsigned int start_i = static_cast<unsigned int>(start_h * 6.); unsigned int stop_i = static_cast<unsigned int>(stop_h * 6.); double start_f = start_h * 6. - start_i; double start_q = 1. - start_f; double stop_f = stop_h * 6. - stop_i; double stop_q = 1. - stop_f; switch (start_i % 6) { case 0: start_r = 255, start_g = static_cast<unsigned int>(.5 + 255. * start_f); break; case 1: start_r = static_cast<unsigned int>(.5 + 255. * start_q), start_g = 255; break; case 2: start_g = 255, start_b = static_cast<unsigned int>(.5 + 255. * start_f); break; case 3: start_g = static_cast<unsigned int>(.5 + 255. * start_q), start_b = 255; break; case 4: start_r = static_cast<unsigned int>(.5 + 255. * start_f), start_b = 255; break; case 5: start_r = 255, start_b = static_cast<unsigned int>(.5 + 255. * start_q); break; default: break; } switch (stop_i % 6) { case 0: stop_r = 255, stop_g = static_cast<unsigned int>(.5 + 255. * stop_f); break; case 1: stop_r = static_cast<unsigned int>(.5 + 255. * stop_q), stop_g = 255; break; case 2: stop_g = 255, stop_b = static_cast<unsigned int>(.5 + 255. * stop_f); break; case 3: stop_g = static_cast<unsigned int>(.5 + 255. * stop_q), stop_b = 255; break; case 4: stop_r = static_cast<unsigned int>(.5 + 255. * stop_f), stop_b = 255; break; case 5: stop_r = 255, stop_b = static_cast<unsigned int>(.5 + 255. * stop_q); break; default: break; } Point<3> gradient_start_point_3d, gradient_stop_point_3d; gradient_start_point_3d[0] = gradient_param[0]; gradient_start_point_3d[1] = gradient_param[1]; gradient_start_point_3d[2] = gradient_param[4]; gradient_stop_point_3d[0] = gradient_param[2]; gradient_stop_point_3d[1] = gradient_param[3]; gradient_stop_point_3d[2] = gradient_param[5]; Point<2> gradient_start_point = svg_project_point(gradient_start_point_3d, camera_position, camera_direction, camera_horizontal, camera_focus); Point<2> gradient_stop_point = svg_project_point(gradient_stop_point_3d, camera_position, camera_direction, camera_horizontal, camera_focus); // define linear gradient out << " <linearGradient id=\"" << triangle_counter << "\" gradientUnits=\"userSpaceOnUse\" " << "x1=\"" << static_cast<unsigned int>(.5 + ((gradient_start_point[0] - x_min_perspective) / x_dimension_perspective) * (width - (width/100.) * 2. * margin_in_percent) + ((width/100.) * margin_in_percent)) << "\" " << "y1=\"" << static_cast<unsigned int>(.5 + height - (height/100.) * margin_in_percent - ((gradient_start_point[1] - y_min_perspective) / y_dimension_perspective) * (height - (height/100.) * 2. * margin_in_percent)) << "\" " << "x2=\"" << static_cast<unsigned int>(.5 + ((gradient_stop_point[0] - x_min_perspective) / x_dimension_perspective) * (width - (width/100.) * 2. * margin_in_percent) + ((width/100.) * margin_in_percent)) << "\" " << "y2=\"" << static_cast<unsigned int>(.5 + height - (height/100.) * margin_in_percent - ((gradient_stop_point[1] - y_min_perspective) / y_dimension_perspective) * (height - (height/100.) * 2. * margin_in_percent)) << "\"" << ">" << '\n' << " <stop offset=\"0\" style=\"stop-color:rgb(" << start_r << "," << start_g << "," << start_b << ")\"/>" << '\n' << " <stop offset=\"1\" style=\"stop-color:rgb(" << stop_r << "," << stop_g << "," << stop_b << ")\"/>" << '\n' << " </linearGradient>" << '\n'; // draw current triangle double x1 = 0, y1 = 0, x2 = 0, y2 = 0; double x3 = cell->projected_center[0]; double y3 = cell->projected_center[1]; switch (triangle_index) { case 0: x1 = cell->projected_vertices[0][0], y1 = cell->projected_vertices[0][1], x2 = cell->projected_vertices[1][0], y2 = cell->projected_vertices[1][1]; break; case 1: x1 = cell->projected_vertices[1][0], y1 = cell->projected_vertices[1][1], x2 = cell->projected_vertices[3][0], y2 = cell->projected_vertices[3][1]; break; case 2: x1 = cell->projected_vertices[3][0], y1 = cell->projected_vertices[3][1], x2 = cell->projected_vertices[2][0], y2 = cell->projected_vertices[2][1]; break; case 3: x1 = cell->projected_vertices[2][0], y1 = cell->projected_vertices[2][1], x2 = cell->projected_vertices[0][0], y2 = cell->projected_vertices[0][1]; break; default: break; } out << " <path d=\"M " << static_cast<unsigned int>(.5 + ((x1 - x_min_perspective) / x_dimension_perspective) * (width - (width/100.) * 2. * margin_in_percent) + ((width/100.) * margin_in_percent)) << ' ' << static_cast<unsigned int>(.5 + height - (height/100.) * margin_in_percent - ((y1 - y_min_perspective) / y_dimension_perspective) * (height - (height/100.) * 2. * margin_in_percent)) << " L " << static_cast<unsigned int>(.5 + ((x2 - x_min_perspective) / x_dimension_perspective) * (width - (width/100.) * 2. * margin_in_percent) + ((width/100.) * margin_in_percent)) << ' ' << static_cast<unsigned int>(.5 + height - (height/100.) * margin_in_percent - ((y2 - y_min_perspective) / y_dimension_perspective) * (height - (height/100.) * 2. * margin_in_percent)) << " L " << static_cast<unsigned int>(.5 + ((x3 - x_min_perspective) / x_dimension_perspective) * (width - (width/100.) * 2. * margin_in_percent) + ((width/100.) * margin_in_percent)) << ' ' << static_cast<unsigned int>(.5 + height - (height/100.) * margin_in_percent - ((y3 - y_min_perspective) / y_dimension_perspective) * (height - (height/100.) * 2. * margin_in_percent)) << " L " << static_cast<unsigned int>(.5 + ((x1 - x_min_perspective) / x_dimension_perspective) * (width - (width/100.) * 2. * margin_in_percent) + ((width/100.) * margin_in_percent)) << ' ' << static_cast<unsigned int>(.5 + height - (height/100.) * margin_in_percent - ((y1 - y_min_perspective) / y_dimension_perspective) * (height - (height/100.) * 2. * margin_in_percent)) << "\" style=\"stroke:black; fill:url(#" << triangle_counter << "); stroke-width:" << flags.line_thickness << "\"/>" << '\n'; triangle_counter++; } } // draw the colorbar if (flags.draw_colorbar) { out << '\n' << " <!-- colorbar -->" << '\n'; unsigned int element_height = static_cast<unsigned int>(((height/100.) * (71. - 2.*margin_in_percent)) / 4); unsigned int element_width = static_cast<unsigned int>(.5 + (height/100.) * 2.5); additional_width = 0; if (!flags.margin) additional_width = static_cast<unsigned int>(.5 + (height/100.) * 2.5); for (unsigned int index = 0; index < 4; index++) { double start_h = .667 - ((index+1) / 4.) * .667; double stop_h = .667 - (index / 4.) * .667; unsigned int start_r = 0; unsigned int start_g = 0; unsigned int start_b = 0; unsigned int stop_r = 0; unsigned int stop_g = 0; unsigned int stop_b = 0; unsigned int start_i = static_cast<unsigned int>(start_h * 6.); unsigned int stop_i = static_cast<unsigned int>(stop_h * 6.); double start_f = start_h * 6. - start_i; double start_q = 1. - start_f; double stop_f = stop_h * 6. - stop_i; double stop_q = 1. - stop_f; switch (start_i % 6) { case 0: start_r = 255, start_g = static_cast<unsigned int>(.5 + 255. * start_f); break; case 1: start_r = static_cast<unsigned int>(.5 + 255. * start_q), start_g = 255; break; case 2: start_g = 255, start_b = static_cast<unsigned int>(.5 + 255. * start_f); break; case 3: start_g = static_cast<unsigned int>(.5 + 255. * start_q), start_b = 255; break; case 4: start_r = static_cast<unsigned int>(.5 + 255. * start_f), start_b = 255; break; case 5: start_r = 255, start_b = static_cast<unsigned int>(.5 + 255. * start_q); break; default: break; } switch (stop_i % 6) { case 0: stop_r = 255, stop_g = static_cast<unsigned int>(.5 + 255. * stop_f); break; case 1: stop_r = static_cast<unsigned int>(.5 + 255. * stop_q), stop_g = 255; break; case 2: stop_g = 255, stop_b = static_cast<unsigned int>(.5 + 255. * stop_f); break; case 3: stop_g = static_cast<unsigned int>(.5 + 255. * stop_q), stop_b = 255; break; case 4: stop_r = static_cast<unsigned int>(.5 + 255. * stop_f), stop_b = 255; break; case 5: stop_r = 255, stop_b = static_cast<unsigned int>(.5 + 255. * stop_q); break; default: break; } // define gradient out << " <linearGradient id=\"colorbar_" << index << "\" gradientUnits=\"userSpaceOnUse\" " << "x1=\"" << width + additional_width << "\" " << "y1=\"" << static_cast<unsigned int>(.5 + (height/100.) * (margin_in_percent + 29)) + (3-index) * element_height << "\" " << "x2=\"" << width + additional_width << "\" " << "y2=\"" << static_cast<unsigned int>(.5 + (height/100.) * (margin_in_percent + 29)) + (4-index) * element_height << "\"" << ">" << '\n' << " <stop offset=\"0\" style=\"stop-color:rgb(" << start_r << "," << start_g << "," << start_b << ")\"/>" << '\n' << " <stop offset=\"1\" style=\"stop-color:rgb(" << stop_r << "," << stop_g << "," << stop_b << ")\"/>" << '\n' << " </linearGradient>" << '\n'; // draw box corresponding to the gradient above out << " <rect" << " x=\"" << width + additional_width << "\" y=\"" << static_cast<unsigned int>(.5 + (height/100.) * (margin_in_percent + 29)) + (3-index) * element_height << "\" width=\"" << element_width << "\" height=\"" << element_height << "\" style=\"stroke:black; stroke-width:2; fill:url(#colorbar_" << index << ")\"/>" << '\n'; } for (unsigned int index = 0; index < 5; index++) { out << " <text x=\"" << width + additional_width + static_cast<unsigned int>(1.5 * element_width) << "\" y=\"" << static_cast<unsigned int>(.5 + (height/100.) * (margin_in_percent + 29) + (4.-index) * element_height + 30.) << "\"" << " style=\"text-anchor:start; font-size:80; font-family:Helvetica"; if (index == 0 || index == 4) out << "; font-weight:bold"; out << "\">" << (float)(((int)((z_min + index * (z_dimension / 4.))*10000))/10000.); if (index == 4) out << " max"; if (index == 0) out << " min"; out << "</text>" << '\n'; } } // finalize the svg file out << '\n' << "</svg>"; out.flush(); } template <int dim, int spacedim> void write_deal_II_intermediate (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &vector_data_ranges, const Deal_II_IntermediateFlags &/*flags*/, std::ostream &out) { AssertThrow (out, ExcIO()); // first write tokens indicating the // template parameters. we need this in // here because we may want to read in data // again even if we don't know in advance // the template parameters, see step-19 out << dim << ' ' << spacedim << '\n'; // then write a header out << "[deal.II intermediate format graphics data]" << '\n' << "[written by " << DEAL_II_PACKAGE_NAME << " " << DEAL_II_PACKAGE_VERSION << "]" << '\n' << "[Version: " << Deal_II_IntermediateFlags::format_version << "]" << '\n'; out << data_names.size() << '\n'; for (unsigned int i=0; i<data_names.size(); ++i) out << data_names[i] << '\n'; out << patches.size() << '\n'; for (unsigned int i=0; i<patches.size(); ++i) out << patches[i] << '\n'; out << vector_data_ranges.size() << '\n'; for (unsigned int i=0; i<vector_data_ranges.size(); ++i) out << std_cxx11::get<0>(vector_data_ranges[i]) << ' ' << std_cxx11::get<1>(vector_data_ranges[i]) << '\n' << std_cxx11::get<2>(vector_data_ranges[i]) << '\n'; out << '\n'; // make sure everything now gets to // disk out.flush (); } std::pair<unsigned int, unsigned int> determine_intermediate_format_dimensions (std::istream &input) { AssertThrow (input, ExcIO()); unsigned int dim, spacedim; input >> dim >> spacedim; return std::make_pair (dim, spacedim); } } // namespace DataOutBase /* --------------------------- class DataOutInterface ---------------------- */ template <int dim, int spacedim> DataOutInterface<dim,spacedim>::DataOutInterface () : default_subdivisions(1) {} template <int dim, int spacedim> DataOutInterface<dim,spacedim>::~DataOutInterface () {} template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_dx (std::ostream &out) const { DataOutBase::write_dx (get_patches(), get_dataset_names(), get_vector_data_ranges(), dx_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_ucd (std::ostream &out) const { DataOutBase::write_ucd (get_patches(), get_dataset_names(), get_vector_data_ranges(), ucd_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_gnuplot (std::ostream &out) const { DataOutBase::write_gnuplot (get_patches(), get_dataset_names(), get_vector_data_ranges(), gnuplot_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_povray (std::ostream &out) const { DataOutBase::write_povray (get_patches(), get_dataset_names(), get_vector_data_ranges(), povray_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_eps (std::ostream &out) const { DataOutBase::write_eps (get_patches(), get_dataset_names(), get_vector_data_ranges(), eps_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_gmv (std::ostream &out) const { DataOutBase::write_gmv (get_patches(), get_dataset_names(), get_vector_data_ranges(), gmv_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_tecplot (std::ostream &out) const { DataOutBase::write_tecplot (get_patches(), get_dataset_names(), get_vector_data_ranges(), tecplot_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_tecplot_binary (std::ostream &out) const { DataOutBase::write_tecplot_binary (get_patches(), get_dataset_names(), get_vector_data_ranges(), tecplot_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_vtk (std::ostream &out) const { DataOutBase::write_vtk (get_patches(), get_dataset_names(), get_vector_data_ranges(), vtk_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_vtu (std::ostream &out) const { DataOutBase::write_vtu (get_patches(), get_dataset_names(), get_vector_data_ranges(), vtk_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_svg (std::ostream &out) const { DataOutBase::write_svg (get_patches(), get_dataset_names(), get_vector_data_ranges(), svg_flags, out); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_vtu_in_parallel (const char *filename, MPI_Comm comm) const { #ifndef DEAL_II_WITH_MPI //without MPI fall back to the normal way to write a vtu file: (void)comm; std::ofstream f(filename); write_vtu (f); #else int myrank, nproc, err; MPI_Comm_rank(comm, &myrank); MPI_Comm_size(comm, &nproc); MPI_Info info; MPI_Info_create(&info); MPI_File fh; err = MPI_File_open(comm, const_cast<char *>(filename), MPI_MODE_CREATE | MPI_MODE_WRONLY, info, &fh); AssertThrow(err==0, ExcMessage("Unable to open file with MPI_File_open!")); MPI_File_set_size(fh, 0); // delete the file contents // this barrier is necessary, because otherwise others might already // write while one core is still setting the size to zero. MPI_Barrier(comm); MPI_Info_free(&info); unsigned int header_size; //write header if (myrank==0) { std::stringstream ss; DataOutBase::write_vtu_header(ss, vtk_flags); header_size = ss.str().size(); MPI_File_write(fh, const_cast<char *>(ss.str().c_str()), header_size, MPI_CHAR, MPI_STATUS_IGNORE); } MPI_Bcast(&header_size, 1, MPI_INT, 0, comm); MPI_File_seek_shared( fh, header_size, MPI_SEEK_SET ); { std::stringstream ss; DataOutBase::write_vtu_main (get_patches(), get_dataset_names(), get_vector_data_ranges(), vtk_flags, ss); MPI_File_write_ordered(fh, const_cast<char *>(ss.str().c_str()), ss.str().size(), MPI_CHAR, MPI_STATUS_IGNORE); } //write footer if (myrank==0) { std::stringstream ss; DataOutBase::write_vtu_footer(ss); unsigned int footer_size = ss.str().size(); MPI_File_write_shared(fh, const_cast<char *>(ss.str().c_str()), footer_size, MPI_CHAR, MPI_STATUS_IGNORE); } MPI_File_close( &fh ); #endif } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>:: write_pvd_record (std::ostream &out, const std::vector<std::pair<double,std::string> > &times_and_names) const { AssertThrow (out, ExcIO()); out << "<?xml version=\"1.0\"?>\n"; std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "<!--\n"; out << "#This file was generated by the deal.II library on " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << " at " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << "\n-->\n"; out << "<VTKFile type=\"Collection\" version=\"0.1\" ByteOrder=\"LittleEndian\">\n"; out << " <Collection>\n"; for (unsigned int i=0; i<times_and_names.size(); ++i) out << " <DataSet timestep=\"" << times_and_names[i].first << "\" group=\"\" part=\"0\" file=\"" << times_and_names[i].second << "\"/>\n"; out << " </Collection>\n"; out << "</VTKFile>\n"; out.flush(); AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_pvtu_record (std::ostream &out, const std::vector<std::string> &piece_names) const { AssertThrow (out, ExcIO()); const std::vector<std::string> data_names = get_dataset_names(); const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > vector_data_ranges = get_vector_data_ranges(); const unsigned int n_data_sets = data_names.size(); out << "<?xml version=\"1.0\"?>\n"; std::time_t time1= std::time (0); std::tm *time = std::localtime(&time1); out << "<!--\n"; out << "#This file was generated by the deal.II library on " << time->tm_year+1900 << "/" << time->tm_mon+1 << "/" << time->tm_mday << " at " << time->tm_hour << ":" << std::setw(2) << time->tm_min << ":" << std::setw(2) << time->tm_sec << "\n-->\n"; out << "<VTKFile type=\"PUnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n"; out << " <PUnstructuredGrid GhostLevel=\"0\">\n"; out << " <PPointData Scalars=\"scalars\">\n"; // We need to output in the same order as // the write_vtu function does: std::vector<bool> data_set_written (n_data_sets, false); for (unsigned int n_th_vector=0; n_th_vector<vector_data_ranges.size(); ++n_th_vector) { AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) >= std_cxx11::get<0>(vector_data_ranges[n_th_vector]), ExcLowerRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), std_cxx11::get<0>(vector_data_ranges[n_th_vector]))); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) < n_data_sets, ExcIndexRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), 0, n_data_sets)); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) + 1 - std_cxx11::get<0>(vector_data_ranges[n_th_vector]) <= 3, ExcMessage ("Can't declare a vector with more than 3 components " "in VTK")); // mark these components as already // written: for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<=std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) data_set_written[i] = true; // write the // header. concatenate all the // component names with double // underscores unless a vector // name has been specified out << " <PDataArray type=\"Float64\" Name=\""; if (std_cxx11::get<2>(vector_data_ranges[n_th_vector]) != "") out << std_cxx11::get<2>(vector_data_ranges[n_th_vector]); else { for (unsigned int i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) out << data_names[i] << "__"; out << data_names[std_cxx11::get<1>(vector_data_ranges[n_th_vector])]; } out << "\" NumberOfComponents=\"3\" format=\"ascii\"/>\n"; } for (unsigned int data_set=0; data_set<n_data_sets; ++data_set) if (data_set_written[data_set] == false) { out << " <PDataArray type=\"Float64\" Name=\"" << data_names[data_set] << "\" format=\"ascii\"/>\n"; } out << " </PPointData>\n"; out << " <PPoints>\n"; out << " <PDataArray type=\"Float64\" NumberOfComponents=\"3\"/>\n"; out << " </PPoints>\n"; for (unsigned int i=0; i<piece_names.size(); ++i) out << " <Piece Source=\"" << piece_names[i] << "\"/>\n"; out << " </PUnstructuredGrid>\n"; out << "</VTKFile>\n"; out.flush(); // assert the stream is still ok AssertThrow (out, ExcIO()); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_visit_record (std::ostream &out, const std::vector<std::string> &piece_names) const { out << "!NBLOCKS " << piece_names.size() << '\n'; for (unsigned int i=0; i<piece_names.size(); ++i) out << piece_names[i] << '\n'; out << std::flush; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write_visit_record (std::ostream &out, const std::vector<std::vector<std::string> > &piece_names) const { AssertThrow (out, ExcIO()); if (piece_names.size() == 0) return; const double nblocks = piece_names[0].size(); Assert(nblocks > 0, ExcMessage("piece_names should be a vector of nonempty vectors.") ) out << "!NBLOCKS " << nblocks << '\n'; for (std::vector<std::vector<std::string> >::const_iterator domain = piece_names.begin(); domain != piece_names.end(); ++domain) { Assert(domain->size() == nblocks, ExcMessage("piece_names should be a vector of equal sized vectors.") ) for (std::vector<std::string>::const_iterator subdomain = domain->begin(); subdomain != domain->end(); ++subdomain) out << *subdomain << '\n'; } out << std::flush; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>:: write_deal_II_intermediate (std::ostream &out) const { DataOutBase::write_deal_II_intermediate (get_patches(), get_dataset_names(), get_vector_data_ranges(), deal_II_intermediate_flags, out); } template <int dim, int spacedim> XDMFEntry DataOutInterface<dim,spacedim>:: create_xdmf_entry (const DataOutBase::DataOutFilter &data_filter, const std::string &h5_filename, const double cur_time, MPI_Comm comm) const { return create_xdmf_entry(data_filter, h5_filename, h5_filename, cur_time, comm); } template <int dim, int spacedim> XDMFEntry DataOutInterface<dim,spacedim>:: create_xdmf_entry (const DataOutBase::DataOutFilter &data_filter, const std::string &h5_mesh_filename, const std::string &h5_solution_filename, const double cur_time, MPI_Comm comm) const { unsigned int local_node_cell_count[2], global_node_cell_count[2]; int myrank; #ifndef DEAL_II_WITH_HDF5 // throw an exception, but first make // sure the compiler does not warn about // the now unused function arguments (void)data_filter; (void)h5_mesh_filename; (void)h5_solution_filename; (void)cur_time; (void)comm; AssertThrow(false, ExcMessage ("XDMF support requires HDF5 to be turned on.")); #endif AssertThrow(dim == 2 || dim == 3, ExcMessage ("XDMF only supports 2 or 3 dimensions.")); local_node_cell_count[0] = data_filter.n_nodes(); local_node_cell_count[1] = data_filter.n_cells(); // And compute the global total #ifdef DEAL_II_WITH_MPI MPI_Comm_rank(comm, &myrank); MPI_Allreduce(local_node_cell_count, global_node_cell_count, 2, MPI_UNSIGNED, MPI_SUM, comm); #else myrank = 0; global_node_cell_count[0] = local_node_cell_count[0]; global_node_cell_count[1] = local_node_cell_count[1]; #endif // Output the XDMF file only on the root process if (myrank == 0) { XDMFEntry entry(h5_mesh_filename, h5_solution_filename, cur_time, global_node_cell_count[0], global_node_cell_count[1], dim); unsigned int n_data_sets = data_filter.n_data_sets(); // The vector names generated here must match those generated in the HDF5 file unsigned int i; for (i=0; i<n_data_sets; ++i) { entry.add_attribute(data_filter.get_data_set_name(i), data_filter.get_data_set_dim(i)); } return entry; } else { return XDMFEntry(); } } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>:: write_xdmf_file (const std::vector<XDMFEntry> &entries, const std::string &filename, MPI_Comm comm) const { int myrank; #ifdef DEAL_II_WITH_MPI MPI_Comm_rank(comm, &myrank); #else (void)comm; myrank = 0; #endif // Only rank 0 process writes the XDMF file if (myrank == 0) { std::ofstream xdmf_file(filename.c_str()); std::vector<XDMFEntry>::const_iterator it; xdmf_file << "<?xml version=\"1.0\" ?>\n"; xdmf_file << "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>\n"; xdmf_file << "<Xdmf Version=\"2.0\">\n"; xdmf_file << " <Domain>\n"; xdmf_file << " <Grid Name=\"CellTime\" GridType=\"Collection\" CollectionType=\"Temporal\">\n"; // Write out all the entries indented for (it=entries.begin(); it!=entries.end(); ++it) xdmf_file << it->get_xdmf_content(3); xdmf_file << " </Grid>\n"; xdmf_file << " </Domain>\n"; xdmf_file << "</Xdmf>\n"; xdmf_file.close(); } } /* * Get the XDMF content associated with this entry. * If the entry is not valid, this returns an empty string. */ std::string XDMFEntry::get_xdmf_content(const unsigned int indent_level) const { std::stringstream ss; std::map<std::string, unsigned int>::const_iterator it; if (!valid) return ""; ss << indent(indent_level+0) << "<Grid Name=\"mesh\" GridType=\"Uniform\">\n"; ss << indent(indent_level+1) << "<Time Value=\"" << entry_time << "\"/>\n"; ss << indent(indent_level+1) << "<Geometry GeometryType=\"" << (dimension == 2 ? "XY" : "XYZ" ) << "\">\n"; ss << indent(indent_level+2) << "<DataItem Dimensions=\"" << num_nodes << " " << dimension << "\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n"; ss << indent(indent_level+3) << h5_mesh_filename << ":/nodes\n"; ss << indent(indent_level+2) << "</DataItem>\n"; ss << indent(indent_level+1) << "</Geometry>\n"; // If we have cells defined, use a quadrilateral (2D) or hexahedron (3D) topology if (num_cells > 0) { ss << indent(indent_level+1) << "<Topology TopologyType=\"" << (dimension == 2 ? "Quadrilateral" : "Hexahedron") << "\" NumberOfElements=\"" << num_cells << "\">\n"; ss << indent(indent_level+2) << "<DataItem Dimensions=\"" << num_cells << " " << (2 << (dimension-1)) << "\" NumberType=\"UInt\" Format=\"HDF\">\n"; ss << indent(indent_level+3) << h5_mesh_filename << ":/cells\n"; ss << indent(indent_level+2) << "</DataItem>\n"; ss << indent(indent_level+1) << "</Topology>\n"; } else { // Otherwise, we assume the points are isolated in space and use a Polyvertex topology ss << indent(indent_level+1) << "<Topology TopologyType=\"Polyvertex\" NumberOfElements=\"" << num_nodes << "\">\n"; ss << indent(indent_level+1) << "</Topology>\n"; } for (it=attribute_dims.begin(); it!=attribute_dims.end(); ++it) { ss << indent(indent_level+1) << "<Attribute Name=\"" << it->first << "\" AttributeType=\"" << (it->second > 1 ? "Vector" : "Scalar") << "\" Center=\"Node\">\n"; // Vectors must have 3 elements even for 2D models ss << indent(indent_level+2) << "<DataItem Dimensions=\"" << num_nodes << " " << (it->second > 1 ? 3 : 1) << "\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n"; ss << indent(indent_level+3) << h5_sol_filename << ":/" << it->first << "\n"; ss << indent(indent_level+2) << "</DataItem>\n"; ss << indent(indent_level+1) << "</Attribute>\n"; } ss << indent(indent_level+0) << "</Grid>\n"; return ss.str(); } /* * Write the data in this DataOutInterface to a DataOutFilter object. * Filtering is performed based on the DataOutFilter flags. */ template <int dim, int spacedim> void DataOutInterface<dim,spacedim>:: write_filtered_data (DataOutBase::DataOutFilter &filtered_data) const { DataOutBase::write_filtered_data(get_patches(), get_dataset_names(), get_vector_data_ranges(), filtered_data); } template <int dim, int spacedim> void DataOutBase::write_filtered_data (const std::vector<Patch<dim,spacedim> > &patches, const std::vector<std::string> &data_names, const std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > &vector_data_ranges, DataOutBase::DataOutFilter &filtered_data) { const unsigned int n_data_sets = data_names.size(); unsigned int n_node, n_cell; Table<2,double> data_vectors; Threads::Task<> reorder_task; #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (patches.size() > 0, ExcNoPatches()); #endif compute_sizes<dim,spacedim>(patches, n_node, n_cell); data_vectors = Table<2,double> (n_data_sets, n_node); void (*fun_ptr) (const std::vector<Patch<dim,spacedim> > &, Table<2,double> &) = &DataOutBase::template write_gmv_reorder_data_vectors<dim,spacedim>; reorder_task = Threads::new_task (fun_ptr, patches, data_vectors); // Write the nodes/cells to the DataOutFilter object. write_nodes(patches, filtered_data); write_cells(patches, filtered_data); // Ensure reordering is done before we output data set values reorder_task.join (); // when writing, first write out // all vector data, then handle the // scalar data sets that have been // left over unsigned int i, n_th_vector, data_set, pt_data_vector_dim; std::string vector_name; for (n_th_vector=0,data_set=0; data_set<n_data_sets;) { // Advance n_th_vector to at least the current data set we are on while (n_th_vector < vector_data_ranges.size() && std_cxx11::get<0>(vector_data_ranges[n_th_vector]) < data_set) n_th_vector++; // Determine the dimension of this data if (n_th_vector < vector_data_ranges.size() && std_cxx11::get<0>(vector_data_ranges[n_th_vector]) == data_set) { // Multiple dimensions pt_data_vector_dim = std_cxx11::get<1>(vector_data_ranges[n_th_vector]) - std_cxx11::get<0>(vector_data_ranges[n_th_vector])+1; // Ensure the dimensionality of the data is correct AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) >= std_cxx11::get<0>(vector_data_ranges[n_th_vector]), ExcLowerRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), std_cxx11::get<0>(vector_data_ranges[n_th_vector]))); AssertThrow (std_cxx11::get<1>(vector_data_ranges[n_th_vector]) < n_data_sets, ExcIndexRange (std_cxx11::get<1>(vector_data_ranges[n_th_vector]), 0, n_data_sets)); // Determine the vector name // Concatenate all the // component names with double // underscores unless a vector // name has been specified if (std_cxx11::get<2>(vector_data_ranges[n_th_vector]) != "") { vector_name = std_cxx11::get<2>(vector_data_ranges[n_th_vector]); } else { vector_name = ""; for (i=std_cxx11::get<0>(vector_data_ranges[n_th_vector]); i<std_cxx11::get<1>(vector_data_ranges[n_th_vector]); ++i) vector_name += data_names[i] + "__"; vector_name += data_names[std_cxx11::get<1>(vector_data_ranges[n_th_vector])]; } } else { // One dimension pt_data_vector_dim = 1; vector_name = data_names[data_set]; } // Write data to the filter object filtered_data.write_data_set(vector_name, pt_data_vector_dim, data_set, data_vectors); // Advance the current data set data_set += pt_data_vector_dim; } } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>:: write_hdf5_parallel (const DataOutBase::DataOutFilter &data_filter, const std::string &filename, MPI_Comm comm) const { DataOutBase::write_hdf5_parallel(get_patches(), data_filter, filename, comm); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>:: write_hdf5_parallel (const DataOutBase::DataOutFilter &data_filter, const bool write_mesh_file, const std::string &mesh_filename, const std::string &solution_filename, MPI_Comm comm) const { DataOutBase::write_hdf5_parallel(get_patches(), data_filter, write_mesh_file, mesh_filename, solution_filename, comm); } template <int dim, int spacedim> void DataOutBase::write_hdf5_parallel (const std::vector<Patch<dim,spacedim> > &patches, const DataOutBase::DataOutFilter &data_filter, const std::string &filename, MPI_Comm comm) { write_hdf5_parallel(patches, data_filter, true, filename, filename, comm); } template <int dim, int spacedim> void DataOutBase::write_hdf5_parallel (const std::vector<Patch<dim,spacedim> > &/*patches*/, const DataOutBase::DataOutFilter &data_filter, const bool write_mesh_file, const std::string &mesh_filename, const std::string &solution_filename, MPI_Comm comm) { #ifndef DEAL_II_WITH_HDF5 // throw an exception, but first make // sure the compiler does not warn about // the now unused function arguments (void)data_filter; (void)write_mesh_file; (void)mesh_filename; (void)solution_filename; (void)comm; AssertThrow(false, ExcMessage ("HDF5 support is disabled.")); #else #ifndef DEAL_II_WITH_MPI // verify that there are indeed // patches to be written out. most // of the times, people just forget // to call build_patches when there // are no patches, so a warning is // in order. that said, the // assertion is disabled if we // support MPI since then it can // happen that on the coarsest // mesh, a processor simply has no // cells it actually owns, and in // that case it is legit if there // are no patches Assert (data_filter.n_nodes() > 0, ExcNoPatches()); #else hid_t h5_mesh_file_id=-1, h5_solution_file_id, file_plist_id, plist_id; hid_t node_dataspace, node_dataset, node_file_dataspace, node_memory_dataspace; hid_t cell_dataspace, cell_dataset, cell_file_dataspace, cell_memory_dataspace; hid_t pt_data_dataspace, pt_data_dataset, pt_data_file_dataspace, pt_data_memory_dataspace; herr_t status; unsigned int local_node_cell_count[2], global_node_cell_count[2], global_node_cell_offsets[2]; hsize_t count[2], offset[2], node_ds_dim[2], cell_ds_dim[2]; std::vector<double> node_data_vec; std::vector<unsigned int> cell_data_vec; // If HDF5 is not parallel and we're using multiple processes, abort #ifndef H5_HAVE_PARALLEL # ifdef DEAL_II_WITH_MPI int world_size; MPI_Comm_size(comm, &world_size); AssertThrow (world_size <= 1, ExcMessage ("Serial HDF5 output on multiple processes is not yet supported.")); # endif #endif local_node_cell_count[0] = data_filter.n_nodes(); local_node_cell_count[1] = data_filter.n_cells(); // Create file access properties file_plist_id = H5Pcreate(H5P_FILE_ACCESS); AssertThrow(file_plist_id != -1, ExcIO()); // If MPI is enabled *and* HDF5 is parallel, we can do parallel output #ifdef DEAL_II_WITH_MPI #ifdef H5_HAVE_PARALLEL // Set the access to use the specified MPI_Comm object status = H5Pset_fapl_mpio(file_plist_id, comm, MPI_INFO_NULL); AssertThrow(status >= 0, ExcIO()); #endif #endif // Compute the global total number of nodes/cells // And determine the offset of the data for this process #ifdef DEAL_II_WITH_MPI MPI_Allreduce(local_node_cell_count, global_node_cell_count, 2, MPI_UNSIGNED, MPI_SUM, comm); MPI_Scan(local_node_cell_count, global_node_cell_offsets, 2, MPI_UNSIGNED, MPI_SUM, comm); global_node_cell_offsets[0] -= local_node_cell_count[0]; global_node_cell_offsets[1] -= local_node_cell_count[1]; #else global_node_cell_offsets[0] = global_node_cell_offsets[1] = 0; #endif // Create the property list for a collective write plist_id = H5Pcreate(H5P_DATASET_XFER); AssertThrow(plist_id >= 0, ExcIO()); #ifdef DEAL_II_WITH_MPI #ifdef H5_HAVE_PARALLEL status = H5Pset_dxpl_mpio(plist_id, H5FD_MPIO_COLLECTIVE); AssertThrow(status >= 0, ExcIO()); #endif #endif if (write_mesh_file) { // Overwrite any existing files (change this to an option?) h5_mesh_file_id = H5Fcreate(mesh_filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, file_plist_id); AssertThrow(h5_mesh_file_id >= 0, ExcIO()); // Create the dataspace for the nodes and cells node_ds_dim[0] = global_node_cell_count[0]; node_ds_dim[1] = dim; node_dataspace = H5Screate_simple(2, node_ds_dim, NULL); AssertThrow(node_dataspace >= 0, ExcIO()); cell_ds_dim[0] = global_node_cell_count[1]; cell_ds_dim[1] = GeometryInfo<dim>::vertices_per_cell; cell_dataspace = H5Screate_simple(2, cell_ds_dim, NULL); AssertThrow(cell_dataspace >= 0, ExcIO()); // Create the dataset for the nodes and cells #if H5Gcreate_vers == 1 node_dataset = H5Dcreate(h5_mesh_file_id, "nodes", H5T_NATIVE_DOUBLE, node_dataspace, H5P_DEFAULT); #else node_dataset = H5Dcreate(h5_mesh_file_id, "nodes", H5T_NATIVE_DOUBLE, node_dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif AssertThrow(node_dataset >= 0, ExcIO()); #if H5Gcreate_vers == 1 cell_dataset = H5Dcreate(h5_mesh_file_id, "cells", H5T_NATIVE_UINT, cell_dataspace, H5P_DEFAULT); #else cell_dataset = H5Dcreate(h5_mesh_file_id, "cells", H5T_NATIVE_UINT, cell_dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif AssertThrow(cell_dataset >= 0, ExcIO()); // Close the node and cell dataspaces since we're done with them status = H5Sclose(node_dataspace); AssertThrow(status >= 0, ExcIO()); status = H5Sclose(cell_dataspace); AssertThrow(status >= 0, ExcIO()); // Create the data subset we'll use to read from memory count[0] = local_node_cell_count[0]; count[1] = dim; offset[0] = global_node_cell_offsets[0]; offset[1] = 0; node_memory_dataspace = H5Screate_simple(2, count, NULL); AssertThrow(node_memory_dataspace >= 0, ExcIO()); // Select the hyperslab in the file node_file_dataspace = H5Dget_space(node_dataset); AssertThrow(node_file_dataspace >= 0, ExcIO()); status = H5Sselect_hyperslab(node_file_dataspace, H5S_SELECT_SET, offset, NULL, count, NULL); AssertThrow(status >= 0, ExcIO()); // And repeat for cells count[0] = local_node_cell_count[1]; count[1] = GeometryInfo<dim>::vertices_per_cell; offset[0] = global_node_cell_offsets[1]; offset[1] = 0; cell_memory_dataspace = H5Screate_simple(2, count, NULL); AssertThrow(cell_memory_dataspace >= 0, ExcIO()); cell_file_dataspace = H5Dget_space(cell_dataset); AssertThrow(cell_file_dataspace >= 0, ExcIO()); status = H5Sselect_hyperslab(cell_file_dataspace, H5S_SELECT_SET, offset, NULL, count, NULL); AssertThrow(status >= 0, ExcIO()); // And finally, write the node data data_filter.fill_node_data(node_data_vec); status = H5Dwrite(node_dataset, H5T_NATIVE_DOUBLE, node_memory_dataspace, node_file_dataspace, plist_id, &node_data_vec[0]); AssertThrow(status >= 0, ExcIO()); node_data_vec.clear(); // And the cell data data_filter.fill_cell_data(global_node_cell_offsets[0], cell_data_vec); status = H5Dwrite(cell_dataset, H5T_NATIVE_UINT, cell_memory_dataspace, cell_file_dataspace, plist_id, &cell_data_vec[0]); AssertThrow(status >= 0, ExcIO()); cell_data_vec.clear(); // Close the file dataspaces status = H5Sclose(node_file_dataspace); AssertThrow(status >= 0, ExcIO()); status = H5Sclose(cell_file_dataspace); AssertThrow(status >= 0, ExcIO()); // Close the memory dataspaces status = H5Sclose(node_memory_dataspace); AssertThrow(status >= 0, ExcIO()); status = H5Sclose(cell_memory_dataspace); AssertThrow(status >= 0, ExcIO()); // Close the datasets status = H5Dclose(node_dataset); AssertThrow(status >= 0, ExcIO()); status = H5Dclose(cell_dataset); AssertThrow(status >= 0, ExcIO()); // If the filenames are different, we need to close the mesh file if (mesh_filename != solution_filename) { status = H5Fclose(h5_mesh_file_id); AssertThrow(status >= 0, ExcIO()); } } // If the filenames are identical, continue with the same file if (mesh_filename == solution_filename && write_mesh_file) { h5_solution_file_id = h5_mesh_file_id; } else { // Otherwise we need to open a new file h5_solution_file_id = H5Fcreate(solution_filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, file_plist_id); AssertThrow(h5_solution_file_id >= 0, ExcIO()); } // when writing, first write out // all vector data, then handle the // scalar data sets that have been // left over unsigned int i, pt_data_vector_dim; std::string vector_name; for (i=0; i<data_filter.n_data_sets(); ++i) { // Allocate space for the point data // Must be either 1D or 3D pt_data_vector_dim = data_filter.get_data_set_dim(i); vector_name = data_filter.get_data_set_name(i); // Create the dataspace for the point data node_ds_dim[0] = global_node_cell_count[0]; node_ds_dim[1] = pt_data_vector_dim; pt_data_dataspace = H5Screate_simple(2, node_ds_dim, NULL); AssertThrow(pt_data_dataspace >= 0, ExcIO()); #if H5Gcreate_vers == 1 pt_data_dataset = H5Dcreate(h5_solution_file_id, vector_name.c_str(), H5T_NATIVE_DOUBLE, pt_data_dataspace, H5P_DEFAULT); #else pt_data_dataset = H5Dcreate(h5_solution_file_id, vector_name.c_str(), H5T_NATIVE_DOUBLE, pt_data_dataspace, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif AssertThrow(pt_data_dataset >= 0, ExcIO()); // Create the data subset we'll use to read from memory count[0] = local_node_cell_count[0]; count[1] = pt_data_vector_dim; offset[0] = global_node_cell_offsets[0]; offset[1] = 0; pt_data_memory_dataspace = H5Screate_simple(2, count, NULL); AssertThrow(pt_data_memory_dataspace >= 0, ExcIO()); // Select the hyperslab in the file pt_data_file_dataspace = H5Dget_space(pt_data_dataset); AssertThrow(pt_data_file_dataspace >= 0, ExcIO()); status = H5Sselect_hyperslab(pt_data_file_dataspace, H5S_SELECT_SET, offset, NULL, count, NULL); AssertThrow(status >= 0, ExcIO()); // And finally, write the data status = H5Dwrite(pt_data_dataset, H5T_NATIVE_DOUBLE, pt_data_memory_dataspace, pt_data_file_dataspace, plist_id, data_filter.get_data_set(i)); AssertThrow(status >= 0, ExcIO()); // Close the dataspaces status = H5Sclose(pt_data_dataspace); AssertThrow(status >= 0, ExcIO()); status = H5Sclose(pt_data_memory_dataspace); AssertThrow(status >= 0, ExcIO()); status = H5Sclose(pt_data_file_dataspace); AssertThrow(status >= 0, ExcIO()); // Close the dataset status = H5Dclose(pt_data_dataset); AssertThrow(status >= 0, ExcIO()); } // Close the file property list status = H5Pclose(file_plist_id); AssertThrow(status >= 0, ExcIO()); // Close the parallel access status = H5Pclose(plist_id); AssertThrow(status >= 0, ExcIO()); // Close the file status = H5Fclose(h5_solution_file_id); AssertThrow(status >= 0, ExcIO()); #endif #endif } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::write (std::ostream &out, const DataOutBase::OutputFormat output_format_) const { DataOutBase::OutputFormat output_format = output_format_; if (output_format == DataOutBase::default_format) output_format = default_fmt; switch (output_format) { case DataOutBase::none: break; case DataOutBase::dx: write_dx (out); break; case DataOutBase::ucd: write_ucd (out); break; case DataOutBase::gnuplot: write_gnuplot (out); break; case DataOutBase::povray: write_povray (out); break; case DataOutBase::eps: write_eps (out); break; case DataOutBase::gmv: write_gmv (out); break; case DataOutBase::tecplot: write_tecplot (out); break; case DataOutBase::tecplot_binary: write_tecplot_binary (out); break; case DataOutBase::vtk: write_vtk (out); break; case DataOutBase::vtu: write_vtu (out); break; case DataOutBase::svg: write_svg (out); break; case DataOutBase::deal_II_intermediate: write_deal_II_intermediate (out); break; default: Assert (false, ExcNotImplemented()); } } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_default_format(const DataOutBase::OutputFormat fmt) { Assert (fmt != DataOutBase::default_format, ExcNotImplemented()); default_fmt = fmt; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::DXFlags &flags) { dx_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::UcdFlags &flags) { ucd_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::GnuplotFlags &flags) { gnuplot_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::PovrayFlags &flags) { povray_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::EpsFlags &flags) { eps_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::GmvFlags &flags) { gmv_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::TecplotFlags &flags) { tecplot_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::VtkFlags &flags) { vtk_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::SvgFlags &flags) { svg_flags = flags; } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::set_flags (const DataOutBase::Deal_II_IntermediateFlags &flags) { deal_II_intermediate_flags = flags; } template <int dim, int spacedim> std::string DataOutInterface<dim,spacedim>:: default_suffix (const DataOutBase::OutputFormat output_format) const { if (output_format == DataOutBase::default_format) return DataOutBase::default_suffix (default_fmt); else return DataOutBase::default_suffix (output_format); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::declare_parameters (ParameterHandler &prm) { prm.declare_entry ("Output format", "gnuplot", Patterns::Selection (DataOutBase::get_output_format_names ()), "A name for the output format to be used"); prm.declare_entry("Subdivisions", "1", Patterns::Integer(), "Number of subdivisions of each mesh cell"); prm.enter_subsection ("DX output parameters"); DataOutBase::DXFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("UCD output parameters"); DataOutBase::UcdFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Gnuplot output parameters"); DataOutBase::GnuplotFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Povray output parameters"); DataOutBase::PovrayFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Eps output parameters"); DataOutBase::EpsFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Gmv output parameters"); DataOutBase::GmvFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Tecplot output parameters"); DataOutBase::TecplotFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Vtk output parameters"); DataOutBase::VtkFlags::declare_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("deal.II intermediate output parameters"); DataOutBase::Deal_II_IntermediateFlags::declare_parameters (prm); prm.leave_subsection (); } template <int dim, int spacedim> void DataOutInterface<dim,spacedim>::parse_parameters (ParameterHandler &prm) { const std::string &output_name = prm.get ("Output format"); default_fmt = DataOutBase::parse_output_format (output_name); default_subdivisions = prm.get_integer ("Subdivisions"); prm.enter_subsection ("DX output parameters"); dx_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("UCD output parameters"); ucd_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Gnuplot output parameters"); gnuplot_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Povray output parameters"); povray_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Eps output parameters"); eps_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Gmv output parameters"); gmv_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Tecplot output parameters"); tecplot_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("Vtk output parameters"); vtk_flags.parse_parameters (prm); prm.leave_subsection (); prm.enter_subsection ("deal.II intermediate output parameters"); deal_II_intermediate_flags.parse_parameters (prm); prm.leave_subsection (); } template <int dim, int spacedim> std::size_t DataOutInterface<dim,spacedim>::memory_consumption () const { return (sizeof (default_fmt) + MemoryConsumption::memory_consumption (dx_flags) + MemoryConsumption::memory_consumption (ucd_flags) + MemoryConsumption::memory_consumption (gnuplot_flags) + MemoryConsumption::memory_consumption (povray_flags) + MemoryConsumption::memory_consumption (eps_flags) + MemoryConsumption::memory_consumption (gmv_flags) + MemoryConsumption::memory_consumption (tecplot_flags) + MemoryConsumption::memory_consumption (vtk_flags) + MemoryConsumption::memory_consumption (svg_flags) + MemoryConsumption::memory_consumption (deal_II_intermediate_flags)); } template <int dim, int spacedim> std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > DataOutInterface<dim,spacedim>::get_vector_data_ranges () const { return std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> >(); } // ---------------------------------------------- DataOutReader ---------- template <int dim, int spacedim> void DataOutReader<dim,spacedim>::read (std::istream &in) { AssertThrow (in, ExcIO()); // first empty previous content { std::vector<typename dealii::DataOutBase::Patch<dim,spacedim> > tmp; tmp.swap (patches); } { std::vector<std::string> tmp; tmp.swap (dataset_names); } { std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > tmp; tmp.swap (vector_data_ranges); } // then check that we have the // correct header of this // file. both the first and second // real lines have to match, as // well as the dimension // information written before that // and the Version information // written in the third line { std::pair<unsigned int, unsigned int> dimension_info = DataOutBase::determine_intermediate_format_dimensions (in); AssertThrow ((dimension_info.first == dim) && (dimension_info.second == spacedim), ExcIncompatibleDimensions (dimension_info.first, dim, dimension_info.second, spacedim)); // read to the end of the line std::string tmp; getline (in, tmp); } { std::string header; getline (in, header); std::ostringstream s; s << "[deal.II intermediate format graphics data]"; Assert (header == s.str(), ExcUnexpectedInput(s.str(),header)); } { std::string header; getline (in, header); std::ostringstream s; s << "[written by " << DEAL_II_PACKAGE_NAME << " " << DEAL_II_PACKAGE_VERSION << "]"; Assert (header == s.str(), ExcUnexpectedInput(s.str(),header)); } { std::string header; getline (in, header); std::ostringstream s; s << "[Version: " << dealii::DataOutBase::Deal_II_IntermediateFlags::format_version << "]"; Assert (header == s.str(), ExcMessage("Invalid or incompatible file format. Intermediate format " "files can only be read by the same deal.II version as they " "are written by.")); } // then read the rest of the data unsigned int n_datasets; in >> n_datasets; dataset_names.resize (n_datasets); for (unsigned int i=0; i<n_datasets; ++i) in >> dataset_names[i]; unsigned int n_patches; in >> n_patches; patches.resize (n_patches); for (unsigned int i=0; i<n_patches; ++i) in >> patches[i]; unsigned int n_vector_data_ranges; in >> n_vector_data_ranges; vector_data_ranges.resize (n_vector_data_ranges); for (unsigned int i=0; i<n_vector_data_ranges; ++i) { in >> std_cxx11::get<0>(vector_data_ranges[i]) >> std_cxx11::get<1>(vector_data_ranges[i]); // read in the name of that vector // range. because it is on a separate // line, we first need to read to the // end of the previous line (nothing // should be there any more after we've // read the previous two integers) and // then read the entire next line for // the name std::string name; getline(in, name); getline(in, name); std_cxx11::get<2>(vector_data_ranges[i]) = name; } AssertThrow (in, ExcIO()); } template <int dim, int spacedim> void DataOutReader<dim,spacedim>:: merge (const DataOutReader<dim,spacedim> &source) { typedef typename dealii::DataOutBase::Patch<dim,spacedim> Patch; const std::vector<Patch> source_patches = source.get_patches (); Assert (patches.size () != 0, ExcNoPatches ()); Assert (source_patches.size () != 0, ExcNoPatches ()); // check equality of component // names Assert (get_dataset_names() == source.get_dataset_names(), ExcIncompatibleDatasetNames()); // check equality of the vector data // specifications Assert (get_vector_data_ranges().size() == source.get_vector_data_ranges().size(), ExcMessage ("Both sources need to declare the same components " "as vectors.")); for (unsigned int i=0; i<get_vector_data_ranges().size(); ++i) { Assert (std_cxx11::get<0>(get_vector_data_ranges()[i]) == std_cxx11::get<0>(source.get_vector_data_ranges()[i]), ExcMessage ("Both sources need to declare the same components " "as vectors.")); Assert (std_cxx11::get<1>(get_vector_data_ranges()[i]) == std_cxx11::get<1>(source.get_vector_data_ranges()[i]), ExcMessage ("Both sources need to declare the same components " "as vectors.")); Assert (std_cxx11::get<2>(get_vector_data_ranges()[i]) == std_cxx11::get<2>(source.get_vector_data_ranges()[i]), ExcMessage ("Both sources need to declare the same components " "as vectors.")); } // make sure patches are compatible Assert (patches[0].n_subdivisions == source_patches[0].n_subdivisions, ExcIncompatiblePatchLists()); Assert (patches[0].data.n_rows() == source_patches[0].data.n_rows(), ExcIncompatiblePatchLists()); Assert (patches[0].data.n_cols() == source_patches[0].data.n_cols(), ExcIncompatiblePatchLists()); // merge patches. store old number // of elements, since we need to // adjust patch numbers, etc // afterwards const unsigned int old_n_patches = patches.size(); patches.insert (patches.end(), source_patches.begin(), source_patches.end()); // adjust patch numbers for (unsigned int i=old_n_patches; i<patches.size(); ++i) patches[i].patch_index += old_n_patches; // adjust patch neighbors for (unsigned int i=old_n_patches; i<patches.size(); ++i) for (unsigned int n=0; n<GeometryInfo<dim>::faces_per_cell; ++n) if (patches[i].neighbors[n] != dealii::DataOutBase::Patch<dim,spacedim>::no_neighbor) patches[i].neighbors[n] += old_n_patches; } template <int dim, int spacedim> const std::vector<typename dealii::DataOutBase::Patch<dim,spacedim> > & DataOutReader<dim,spacedim>::get_patches () const { return patches; } template <int dim, int spacedim> std::vector<std::string> DataOutReader<dim,spacedim>::get_dataset_names () const { return dataset_names; } template <int dim, int spacedim> std::vector<std_cxx11::tuple<unsigned int, unsigned int, std::string> > DataOutReader<dim,spacedim>::get_vector_data_ranges () const { return vector_data_ranges; } namespace DataOutBase { template <int dim, int spacedim> std::ostream & operator << (std::ostream &out, const Patch<dim,spacedim> &patch) { // write a header line out << "[deal.II intermediate Patch<" << dim << ',' << spacedim << ">]" << '\n'; // then write all the data that is // in this patch for (unsigned int i=0; i<GeometryInfo<dim>::vertices_per_cell; ++i) out << patch.vertices[GeometryInfo<dim>::ucd_to_deal[i]] << ' '; out << '\n'; for (unsigned int i=0; i<GeometryInfo<dim>::faces_per_cell; ++i) out << patch.neighbors[i] << ' '; out << '\n'; out << patch.patch_index << ' ' << patch.n_subdivisions << '\n'; out << patch.points_are_available<<'\n'; out << patch.data.n_rows() << ' ' << patch.data.n_cols() << '\n'; for (unsigned int i=0; i<patch.data.n_rows(); ++i) for (unsigned int j=0; j<patch.data.n_cols(); ++j) out << patch.data[i][j] << ' '; out << '\n'; out << '\n'; return out; } template <int dim, int spacedim> std::istream & operator >> (std::istream &in, Patch<dim,spacedim> &patch) { AssertThrow (in, ExcIO()); // read a header line and compare // it to what we usually // write. skip all lines that // contain only blanks at the start { std::string header; do { getline (in, header); while ((header.size() != 0) && (header[header.size()-1] == ' ')) header.erase(header.size()-1); } while ((header == "") && in); std::ostringstream s; s << "[deal.II intermediate Patch<" << dim << ',' << spacedim << ">]"; Assert (header == s.str(), ExcUnexpectedInput(s.str(),header)); } // then read all the data that is // in this patch for (unsigned int i=0; i<GeometryInfo<dim>::vertices_per_cell; ++i) in >> patch.vertices[GeometryInfo<dim>::ucd_to_deal[i]]; for (unsigned int i=0; i<GeometryInfo<dim>::faces_per_cell; ++i) in >> patch.neighbors[i]; in >> patch.patch_index >> patch.n_subdivisions; in >> patch.points_are_available; unsigned int n_rows, n_cols; in >> n_rows >> n_cols; patch.data.reinit (n_rows, n_cols); for (unsigned int i=0; i<patch.data.n_rows(); ++i) for (unsigned int j=0; j<patch.data.n_cols(); ++j) in >> patch.data[i][j]; AssertThrow (in, ExcIO()); return in; } } // explicit instantiations #include "data_out_base.inst" DEAL_II_NAMESPACE_CLOSE
mtezzele/dealii
source/base/data_out_base.cc
C++
lgpl-2.1
265,443
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "subdirsprojectwizard.h" #include "subdirsprojectwizarddialog.h" #include <projectexplorer/projectexplorerconstants.h> #include <coreplugin/icore.h> #include <QIcon> namespace Qt4ProjectManager { namespace Internal { SubdirsProjectWizard::SubdirsProjectWizard() : QtWizard(QLatin1String("U.Qt4Subdirs"), QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY), QLatin1String(ProjectExplorer::Constants::QT_PROJECT_WIZARD_CATEGORY_DISPLAY), tr("Subdirs Project"), tr("Creates a qmake-based subdirs project. This allows you to group " "your projects in a tree structure."), QIcon(QLatin1String(":/wizards/images/gui.png"))) { } QWizard *SubdirsProjectWizard::createWizardDialog(QWidget *parent, const Core::WizardDialogParameters &wizardDialogParameters) const { SubdirsProjectWizardDialog *dialog = new SubdirsProjectWizardDialog(displayName(), icon(), parent, wizardDialogParameters); dialog->setProjectName(SubdirsProjectWizardDialog::uniqueProjectName(wizardDialogParameters.defaultPath())); const QString buttonText = dialog->wizardStyle() == QWizard::MacStyle ? tr("Done && Add Subproject") : tr("Finish && Add Subproject"); dialog->setButtonText(QWizard::FinishButton, buttonText); return dialog; } Core::GeneratedFiles SubdirsProjectWizard::generateFiles(const QWizard *w, QString * /*errorMessage*/) const { const SubdirsProjectWizardDialog *wizard = qobject_cast< const SubdirsProjectWizardDialog *>(w); const QtProjectParameters params = wizard->parameters(); const QString projectPath = params.projectPath(); const QString profileName = Core::BaseFileWizard::buildFileName(projectPath, params.fileName, profileSuffix()); Core::GeneratedFile profile(profileName); profile.setAttributes(Core::GeneratedFile::OpenProjectAttribute | Core::GeneratedFile::OpenEditorAttribute); profile.setContents(QLatin1String("TEMPLATE = subdirs\n")); return Core::GeneratedFiles() << profile; } bool SubdirsProjectWizard::postGenerateFiles(const QWizard *w, const Core::GeneratedFiles &files, QString *errorMessage) { const SubdirsProjectWizardDialog *wizard = qobject_cast< const SubdirsProjectWizardDialog *>(w); if (QtWizard::qt4ProjectPostGenerateFiles(wizard, files, errorMessage)) { const QtProjectParameters params = wizard->parameters(); const QString projectPath = params.projectPath(); const QString profileName = Core::BaseFileWizard::buildFileName(projectPath, params.fileName, profileSuffix()); QVariantMap map; map.insert(QLatin1String(ProjectExplorer::Constants::PREFERED_PROJECT_NODE), profileName); map.insert(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS), QVariant::fromValue(wizard->selectedKits())); Core::ICore::showNewItemDialog(tr("New Subproject", "Title of dialog"), Core::IWizard::wizardsOfKind(Core::IWizard::ProjectWizard), wizard->parameters().projectPath(), map); } else { return false; } return true; } Core::FeatureSet SubdirsProjectWizard::requiredFeatures() const { return Core::FeatureSet(); } } // namespace Internal } // namespace Qt4ProjectManager
mornelon/QtCreator_compliments
src/plugins/qt4projectmanager/wizards/subdirsprojectwizard.cpp
C++
lgpl-2.1
4,911
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Designer of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdesigner_formwindow.h" #include "qdesigner_workbench.h" #include "formwindowbase_p.h" // sdk #include <QtDesigner/QDesignerFormWindowInterface> #include <QtDesigner/QDesignerFormEditorInterface> #include <QtDesigner/QDesignerPropertySheetExtension> #include <QtDesigner/QDesignerPropertyEditorInterface> #include <QtDesigner/QDesignerFormWindowManagerInterface> #include <QtDesigner/QDesignerTaskMenuExtension> #include <QtDesigner/QExtensionManager> #include <QtCore/QEvent> #include <QtCore/QFile> #include <QtGui/QAction> #include <QtGui/QCloseEvent> #include <QtGui/QFileDialog> #include <QtGui/QMessageBox> #include <QtGui/QPushButton> #include <QtGui/QVBoxLayout> #include <QtGui/QUndoCommand> #include <QtGui/QWindowStateChangeEvent> QT_BEGIN_NAMESPACE QDesignerFormWindow::QDesignerFormWindow(QDesignerFormWindowInterface *editor, QDesignerWorkbench *workbench, QWidget *parent, Qt::WindowFlags flags) : QWidget(parent, flags), m_editor(editor), m_workbench(workbench), m_action(new QAction(this)), m_initialized(false), m_windowTitleInitialized(false) { Q_ASSERT(workbench); setMaximumSize(0xFFF, 0xFFF); QDesignerFormEditorInterface *core = workbench->core(); if (m_editor) { m_editor->setParent(this); } else { m_editor = core->formWindowManager()->createFormWindow(this); } QVBoxLayout *l = new QVBoxLayout(this); l->setMargin(0); l->addWidget(m_editor); m_action->setCheckable(true); connect(m_editor->commandHistory(), SIGNAL(indexChanged(int)), this, SLOT(updateChanged())); connect(m_editor, SIGNAL(geometryChanged()), this, SLOT(geometryChanged())); qdesigner_internal::FormWindowBase::setupDefaultAction(m_editor); } QDesignerFormWindow::~QDesignerFormWindow() { if (workbench()) workbench()->removeFormWindow(this); } QAction *QDesignerFormWindow::action() const { return m_action; } void QDesignerFormWindow::changeEvent(QEvent *e) { switch (e->type()) { case QEvent::WindowTitleChange: m_action->setText(windowTitle().remove(QLatin1String("[*]"))); break; case QEvent::WindowIconChange: m_action->setIcon(windowIcon()); break; case QEvent::WindowStateChange: { const QWindowStateChangeEvent *wsce = static_cast<const QWindowStateChangeEvent *>(e); const bool wasMinimized = Qt::WindowMinimized & wsce->oldState(); const bool isMinimizedNow = isMinimized(); if (wasMinimized != isMinimizedNow ) emit minimizationStateChanged(m_editor, isMinimizedNow); } break; default: break; } QWidget::changeEvent(e); } QRect QDesignerFormWindow::geometryHint() const { const QPoint point(0, 0); // If we have a container, we want to be just as big. // QMdiSubWindow attempts to resize its children to sizeHint() when switching user interface modes. if (QWidget *mainContainer = m_editor->mainContainer()) return QRect(point, mainContainer->size()); return QRect(point, sizeHint()); } QDesignerFormWindowInterface *QDesignerFormWindow::editor() const { return m_editor; } QDesignerWorkbench *QDesignerFormWindow::workbench() const { return m_workbench; } void QDesignerFormWindow::firstShow() { // Set up handling of file name changes and set initial title. if (!m_windowTitleInitialized) { m_windowTitleInitialized = true; if (m_editor) { connect(m_editor, SIGNAL(fileNameChanged(QString)), this, SLOT(updateWindowTitle(QString))); updateWindowTitle(m_editor->fileName()); } } show(); } int QDesignerFormWindow::getNumberOfUntitledWindows() const { const int totalWindows = m_workbench->formWindowCount(); if (!totalWindows) return 0; int maxUntitled = 0; // Find the number of untitled windows excluding ourselves. // Do not fall for 'untitled.ui', match with modified place holder. // This will cause some problems with i18n, but for now I need the string to be "static" QRegExp rx(QLatin1String("untitled( (\\d+))?\\[\\*\\]")); for (int i = 0; i < totalWindows; ++i) { QDesignerFormWindow *fw = m_workbench->formWindow(i); if (fw != this) { const QString title = m_workbench->formWindow(i)->windowTitle(); if (rx.indexIn(title) != -1) { if (maxUntitled == 0) ++maxUntitled; if (rx.captureCount() > 1) { const QString numberCapture = rx.cap(2); if (!numberCapture.isEmpty()) maxUntitled = qMax(numberCapture.toInt(), maxUntitled); } } } } return maxUntitled; } void QDesignerFormWindow::updateWindowTitle(const QString &fileName) { if (!m_windowTitleInitialized) { m_windowTitleInitialized = true; if (m_editor) connect(m_editor, SIGNAL(fileNameChanged(QString)), this, SLOT(updateWindowTitle(QString))); } QString fileNameTitle; if (fileName.isEmpty()) { fileNameTitle = QLatin1String("untitled"); if (const int maxUntitled = getNumberOfUntitledWindows()) { fileNameTitle += QLatin1Char(' '); fileNameTitle += QString::number(maxUntitled + 1); } } else { fileNameTitle = QFileInfo(fileName).fileName(); } if (const QWidget *mc = m_editor->mainContainer()) { setWindowIcon(mc->windowIcon()); setWindowTitle(tr("%1 - %2[*]").arg(mc->windowTitle()).arg(fileNameTitle)); } else { setWindowTitle(fileNameTitle); } } void QDesignerFormWindow::closeEvent(QCloseEvent *ev) { if (m_editor->isDirty()) { raise(); QMessageBox box(QMessageBox::Information, tr("Save Form?"), tr("Do you want to save the changes to this document before closing?"), QMessageBox::Discard | QMessageBox::Cancel | QMessageBox::Save, m_editor); box.setInformativeText(tr("If you don't save, your changes will be lost.")); box.setWindowModality(Qt::WindowModal); static_cast<QPushButton *>(box.button(QMessageBox::Save))->setDefault(true); switch (box.exec()) { case QMessageBox::Save: { bool ok = workbench()->saveForm(m_editor); ev->setAccepted(ok); m_editor->setDirty(!ok); break; } case QMessageBox::Discard: m_editor->setDirty(false); // Not really necessary, but stops problems if we get close again. ev->accept(); break; case QMessageBox::Cancel: ev->ignore(); break; } } } void QDesignerFormWindow::updateChanged() { // Sometimes called after form window destruction. if (m_editor) { setWindowModified(m_editor->isDirty()); updateWindowTitle(m_editor->fileName()); } } void QDesignerFormWindow::resizeEvent(QResizeEvent *rev) { if(m_initialized) { m_editor->setDirty(true); setWindowModified(true); } m_initialized = true; QWidget::resizeEvent(rev); } void QDesignerFormWindow::geometryChanged() { // If the form window changes, re-update the geometry of the current widget in the property editor. // Note that in the case of layouts, non-maincontainer widgets must also be updated, // so, do not do it for the main container only const QDesignerFormEditorInterface *core = m_editor->core(); QObject *object = core->propertyEditor()->object(); if (object == 0 || !object->isWidgetType()) return; static const QString geometryProperty = QLatin1String("geometry"); const QDesignerPropertySheetExtension *sheet = qt_extension<QDesignerPropertySheetExtension*>(core->extensionManager(), object); const int geometryIndex = sheet->indexOf(geometryProperty); if (geometryIndex == -1) return; core->propertyEditor()->setPropertyValue(geometryProperty, sheet->property(geometryIndex)); } QT_END_NAMESPACE
igor-sfdc/qt-wk
tools/designer/src/designer/qdesigner_formwindow.cpp
C++
lgpl-2.1
9,680
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <boost/python.hpp> #include <mapnik/datasource_cache.hpp> namespace { using namespace boost::python; boost::shared_ptr<mapnik::datasource> create_datasource(const dict& d) { bool bind=true; mapnik::parameters params; boost::python::list keys=d.keys(); for (int i=0; i<len(keys); ++i) { std::string key = extract<std::string>(keys[i]); object obj = d[key]; if (key == "bind") { bind = extract<bool>(obj)(); continue; } extract<std::string> ex0(obj); extract<int> ex1(obj); extract<double> ex2(obj); if (ex0.check()) { params[key] = ex0(); } else if (ex1.check()) { params[key] = ex1(); } else if (ex2.check()) { params[key] = ex2(); } } return mapnik::datasource_cache::instance().create(params, bind); } void register_datasources(std::string const& path) { mapnik::datasource_cache::instance().register_datasources(path); } std::vector<std::string> plugin_names() { return mapnik::datasource_cache::instance().plugin_names(); } std::string plugin_directories() { return mapnik::datasource_cache::instance().plugin_directories(); } } void export_datasource_cache() { using mapnik::datasource_cache; class_<datasource_cache, boost::noncopyable>("DatasourceCache",no_init) .def("create",&create_datasource) .staticmethod("create") .def("register_datasources",&register_datasources) .staticmethod("register_datasources") .def("plugin_names",&plugin_names) .staticmethod("plugin_names") .def("plugin_directories",&plugin_directories) .staticmethod("plugin_directories") ; }
ake-koomsin/mapnik_nvpr
bindings/python/mapnik_datasource_cache.cpp
C++
lgpl-2.1
2,838
// // Miscellaneous small items related to message sinks // using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Loyc { /// <summary>This interface allows an object to declare its "location".</summary> /// <remarks>For example, <see cref="Loyc.Syntax.LNode"/> implements this /// interface so that when a compiler error refers to a source code construct, /// the error message contains the location of that source code rather than the /// code itself. /// <para/> /// Given a context object that may or may not implement this interface, it's /// handy to use <see cref="MessageSink.ContextToString"/> to convert the /// "context" of a message into a string, or <see cref="MessageSink.LocationOf(object)"/> /// to unwrap objects that implement IHasLocation. /// </remarks> public interface IHasLocation { object Location { get; } } /// <summary>This is the method signature of <c>IMessageSink.Write()</c>. You /// can convert from one of these delegates to <see cref="IMessageSink"/> by /// calling <see cref="MessageSink.FromDelegate"/>.</summary> /// <param name="type">Severity or importance of the message; widely-used /// types include Error, Warning, Note, Debug, and Verbose. The special /// type Detail is intended to provide more information about a previous /// message.</param> /// <param name="context">An object that represents the location that the /// message applies to, a string that indicates what the program was doing /// when the message was generated, or any other relevant context information. /// See also <see cref="MessageSink.ContextToString"/>().</param> /// <param name="format">A message to display. If there are additional /// arguments, placeholders such as {0} and {1} refer to these arguments.</param> /// <param name="args">Optional arguments to fill in placeholders in the format /// string.</param> public delegate void WriteMessageFn(Severity type, object context, string format, params object[] args); /// <summary>An exception that includes a "context" object as part of a /// <see cref="LogMessage"/> structure, typically used to indicate where an /// error occurred.</summary> public class LogException : Exception { public LogException(object context, string format, params object[] args) : this(Severity.Error, context, format, args) {} public LogException(Severity severity, object context, string format, params object[] args) : this(new LogMessage(severity, context, format, args)) {} public LogException(LogMessage msg) { Msg = msg; try { Data["Severity"] = msg.Severity; // Disabled because members of the Data dictionary must be serializable, // but msg.Context might not be. We could convert to string, but is it // worth the performance cost? Loyc code isn't really using Data anyway. //Data["Context"] = msg.Context; } catch { } } /// <summary>Contains additional information about the error that occurred.</summary> public LogMessage Msg { get; private set; } public override string Message { get { return Msg.Formatted; } } } }
loycnet/ecsharp
Core/Loyc.Essentials/MessageSinks/Misc.cs
C#
lgpl-2.1
3,135
namespace("JSTools.Event"); /// <class> /// Provides an interface for attaching and detaching Observer objects. Any number of /// Observer objects may observe a subject. /// </class> JSTools.Event.Subject = function() { //------------------------------------------------------------------------ // Declarations //------------------------------------------------------------------------ this.InitType(arguments, "JSTools.Event.Subject"); var _this = this; var _observers = null; //------------------------------------------------------------------------ // Constructor //------------------------------------------------------------------------ /// <constructor> /// Creates a new JSTools.Event.Subject instance. /// </constructor> function Init() { _this.Clear(); } //------------------------------------------------------------------------ // Methods //------------------------------------------------------------------------ /// <method> /// Removes all registered observer object. /// </method> function Clear() { _observers = [ ]; } this.Clear = Clear; /// <method> /// Attaches the given observer function to this subject. /// </method> /// <param name="objIObserver" type="JSTools.Event.IObserver">Observer to attach.</param> /// <returns type="Integer">Returns the index, at which the observer object has been added. /// Returns -1 if the given observer object is invalid and not added.</returns> function Attach(objIObserver) { if (objIObserver && typeof(objIObserver) == 'object' && objIObserver.IsTypeOf(JSTools.Event.IObserver)) { _observers.Add(objIObserver); return _observers.length - 1; } return -1; } this.Attach = Attach; /// <method> /// Detaches the given observer object from this subject. /// </method> /// <param name="objIObserverToDetach" type="JSTools.Event.IObserver">Observer to detach.</param> function Detach(objIObserverToDetach) { _observers.Remove(objIObserverToDetach); } this.Detach = Detach; /// <method> /// Detaches an observer at the given index from this subject. /// </method> /// <param name="intIndex" type="Integer">Index to detach.</param> function DetachByIndex(intIndex) { _observers.RemoveAt(intIndex); } this.DetachByIndex = DetachByIndex; /// <method> /// Notifies the observer about an update. /// </method> /// <param name="objEvent" type="Object">An object instance, which represents the event argument.</param> function Notify(objEvent) { for (var i = 0; i < _observers.length; ++i) { _observers[i].Update(objEvent); } } this.Notify = Notify; Init(); }
sgeh/JSTools.net
Branches/JSTools 0.41/JSTools.JavaScript/JSTools/Event/Subject.js
JavaScript
lgpl-2.1
2,624
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2016, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------- * Effect3D.java * ------------- * (C) Copyright 2002-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 05-Nov-2002 : Version 1 (DG); * 14-Nov-2002 : Modified to have independent x and y offsets (DG); * */ package org.jfree.chart; /** * An interface that should be implemented by renderers that use a 3D effect. * This allows the axes to mirror the same effect by querying the renderer. */ public interface Effect3D { /** * Returns the x-offset (in Java2D units) for the 3D effect. * * @return The offset. */ public double getXOffset(); /** * Returns the y-offset (in Java2D units) for the 3D effect. * * @return The offset. */ public double getYOffset(); }
simon04/jfreechart
src/main/java/org/jfree/chart/Effect3D.java
Java
lgpl-2.1
2,135
// // NotificationQueue.cpp // // $Id: //poco/1.4/Foundation/src/NotificationQueue.cpp#1 $ // // Library: Foundation // Package: Notifications // Module: NotificationQueue // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "Poco/NotificationQueue.h" #include "Poco/NotificationCenter.h" #include "Poco/Notification.h" #include "Poco/SingletonHolder.h" namespace Poco { NotificationQueue::NotificationQueue() { } NotificationQueue::~NotificationQueue() { clear(); } void NotificationQueue::enqueueNotification(Notification::Ptr pNotification) { poco_check_ptr (pNotification); FastMutex::ScopedLock lock(_mutex); if (_waitQueue.empty()) { _nfQueue.push_back(pNotification); } else { WaitInfo* pWI = _waitQueue.front(); _waitQueue.pop_front(); pWI->pNf = pNotification; pWI->nfAvailable.set(); } } void NotificationQueue::enqueueUrgentNotification(Notification::Ptr pNotification) { poco_check_ptr (pNotification); FastMutex::ScopedLock lock(_mutex); if (_waitQueue.empty()) { _nfQueue.push_front(pNotification); } else { WaitInfo* pWI = _waitQueue.front(); _waitQueue.pop_front(); pWI->pNf = pNotification; pWI->nfAvailable.set(); } } Notification* NotificationQueue::dequeueNotification() { FastMutex::ScopedLock lock(_mutex); return dequeueOne().duplicate(); } Notification* NotificationQueue::waitDequeueNotification() { Notification::Ptr pNf; WaitInfo* pWI = 0; { FastMutex::ScopedLock lock(_mutex); pNf = dequeueOne(); if (pNf) return pNf.duplicate(); pWI = new WaitInfo; _waitQueue.push_back(pWI); } pWI->nfAvailable.wait(); pNf = pWI->pNf; delete pWI; return pNf.duplicate(); } Notification* NotificationQueue::waitDequeueNotification(long milliseconds) { Notification::Ptr pNf; WaitInfo* pWI = 0; { FastMutex::ScopedLock lock(_mutex); pNf = dequeueOne(); if (pNf) return pNf.duplicate(); pWI = new WaitInfo; _waitQueue.push_back(pWI); } if (pWI->nfAvailable.tryWait(milliseconds)) { pNf = pWI->pNf; } else { FastMutex::ScopedLock lock(_mutex); pNf = pWI->pNf; for (WaitQueue::iterator it = _waitQueue.begin(); it != _waitQueue.end(); ++it) { if (*it == pWI) { _waitQueue.erase(it); break; } } } delete pWI; return pNf.duplicate(); } void NotificationQueue::dispatch(NotificationCenter& notificationCenter) { FastMutex::ScopedLock lock(_mutex); Notification::Ptr pNf = dequeueOne(); while (pNf) { notificationCenter.postNotification(pNf); pNf = dequeueOne(); } } void NotificationQueue::wakeUpAll() { FastMutex::ScopedLock lock(_mutex); for (WaitQueue::iterator it = _waitQueue.begin(); it != _waitQueue.end(); ++it) { (*it)->nfAvailable.set(); } _waitQueue.clear(); } bool NotificationQueue::empty() const { FastMutex::ScopedLock lock(_mutex); return _nfQueue.empty(); } int NotificationQueue::size() const { FastMutex::ScopedLock lock(_mutex); return static_cast<int>(_nfQueue.size()); } void NotificationQueue::clear() { FastMutex::ScopedLock lock(_mutex); _nfQueue.clear(); } bool NotificationQueue::hasIdleThreads() const { FastMutex::ScopedLock lock(_mutex); return !_waitQueue.empty(); } Notification::Ptr NotificationQueue::dequeueOne() { Notification::Ptr pNf; if (!_nfQueue.empty()) { pNf = _nfQueue.front(); _nfQueue.pop_front(); } return pNf; } namespace { static SingletonHolder<NotificationQueue> sh_nfq; } NotificationQueue& NotificationQueue::defaultQueue() { return *sh_nfq.get(); } } // namespace Poco
tjizep/treestore1
src/poco-1.4.6p1-all/Foundation/src/NotificationQueue.cpp
C++
lgpl-2.1
5,144
/* * Created on 17-dic-2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package org.herac.tuxguitar.app.actions.layout; import org.herac.tuxguitar.app.actions.Action; import org.herac.tuxguitar.app.actions.ActionData; import org.herac.tuxguitar.graphics.control.TGLayout; /** * @author julian * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class SetTablatureEnabledAction extends Action{ public static final String NAME = "action.view.layout-set-tablature-enabled"; public SetTablatureEnabledAction() { super(NAME, AUTO_LOCK | AUTO_UNLOCK | AUTO_UPDATE | KEY_BINDING_AVAILABLE); } protected int execute(ActionData actionData){ TGLayout layout = getEditor().getTablature().getViewLayout(); layout.setStyle( ( layout.getStyle() ^ TGLayout.DISPLAY_TABLATURE ) ); if((layout.getStyle() & TGLayout.DISPLAY_TABLATURE) == 0 && (layout.getStyle() & TGLayout.DISPLAY_SCORE) == 0 ){ layout.setStyle( ( layout.getStyle() ^ TGLayout.DISPLAY_SCORE ) ); } updateTablature(); return 0; } }
yuan39/TuxGuitar
TuxGuitar/src/org/herac/tuxguitar/app/actions/layout/SetTablatureEnabledAction.java
Java
lgpl-2.1
1,189
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsystemlibrary_p.h" #include <QtCore/qvarlengtharray.h> #include <QtCore/qstringlist.h> #include <QtCore/qfileinfo.h> /*! \internal \class QSystemLibrary The purpose of this class is to load only libraries that are located in well-known and trusted locations on the filesystem. It does not suffer from the security problem that QLibrary has, therefore it will never search in the current directory. The search order is the same as the order in DLL Safe search mode Windows, except that we don't search: * The current directory * The 16-bit system directory. (normally c:\windows\system) * The Windows directory. (normally c:\windows) This means that the effective search order is: 1. Application path. 2. System libraries path. 3. Trying all paths inside the PATH environment variable. Note, when onlySystemDirectory is true it will skip 1) and 3). DLL Safe search mode is documented in the "Dynamic-Link Library Search Order" document on MSDN. Since library loading code is sometimes shared between Windows and WinCE, this class can also be used on WinCE. However, its implementation just calls the LoadLibrary() function. This is ok since it is documented as not loading from the current directory on WinCE. This behaviour is documented in the documentation for LoadLibrary for Windows CE at MSDN. (http://msdn.microsoft.com/en-us/library/ms886736.aspx) */ QT_BEGIN_NAMESPACE #if defined(Q_OS_WINCE) HINSTANCE QSystemLibrary::load(const wchar_t *libraryName, bool onlySystemDirectory /* = true */) { return ::LoadLibrary(libraryName); } #else #if !defined(QT_BOOTSTRAPPED) extern QString qAppFileName(); #endif static QString qSystemDirectory() { QVarLengthArray<wchar_t, MAX_PATH> fullPath; UINT retLen = ::GetSystemDirectory(fullPath.data(), MAX_PATH); if (retLen > MAX_PATH) { fullPath.resize(retLen); retLen = ::GetSystemDirectory(fullPath.data(), retLen); } // in some rare cases retLen might be 0 return QString::fromWCharArray(fullPath.constData(), int(retLen)); } HINSTANCE QSystemLibrary::load(const wchar_t *libraryName, bool onlySystemDirectory /* = true */) { QStringList searchOrder; #if !defined(QT_BOOTSTRAPPED) if (!onlySystemDirectory) searchOrder << QFileInfo(qAppFileName()).path(); #endif searchOrder << qSystemDirectory(); if (!onlySystemDirectory) { const QString PATH(QLatin1String(qgetenv("PATH").constData())); searchOrder << PATH.split(QLatin1Char(';'), QString::SkipEmptyParts); } QString fileName = QString::fromWCharArray(libraryName); fileName.append(QLatin1String(".dll")); // Start looking in the order specified for (int i = 0; i < searchOrder.count(); ++i) { QString fullPathAttempt = searchOrder.at(i); if (!fullPathAttempt.endsWith(QLatin1Char('\\'))) { fullPathAttempt.append(QLatin1Char('\\')); } fullPathAttempt.append(fileName); HINSTANCE inst = ::LoadLibrary((const wchar_t *)fullPathAttempt.utf16()); if (inst != 0) return inst; } return 0; } #endif //Q_OS_WINCE QT_END_NAMESPACE
prapin/qmake-iphone
src/corelib/plugin/qsystemlibrary.cpp
C++
lgpl-2.1
5,180
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ */ import { getElementFromPosition } from '../caret/CaretUtils'; import NodeType from '../dom/NodeType'; import { CaretPosition } from '../caret/CaretPosition'; import { Insert, Element } from '@ephox/sugar'; import { Option, Fun } from '@ephox/katamari'; const insertTextAtPosition = (text: string, pos: CaretPosition): Option<CaretPosition> => { const container = pos.container(); const offset = pos.offset(); if (NodeType.isText(container)) { container.insertData(offset, text); return Option.some(CaretPosition(container, offset + text.length)); } else { return getElementFromPosition(pos).map((elm) => { const textNode = Element.fromText(text); if (pos.isAtEnd()) { Insert.after(elm, textNode); } else { Insert.before(elm, textNode); } return CaretPosition(textNode.dom(), text.length); }); } }; const insertNbspAtPosition = Fun.curry(insertTextAtPosition, '\u00a0'); const insertSpaceAtPosition = Fun.curry(insertTextAtPosition, ' '); export { insertTextAtPosition, insertNbspAtPosition, insertSpaceAtPosition };
danielpunkass/tinymce
src/core/main/ts/caret/InsertText.ts
TypeScript
lgpl-2.1
1,351
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2015 the original author or authors. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.coding; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * Restricts the number of statements per line to one. * <p> * Rationale: It's very difficult to read multiple statements on one line. * </p> * <p> * In the Java programming language, statements are the fundamental unit of * execution. All statements except blocks are terminated by a semicolon. * Blocks are denoted by open and close curly braces. * </p> * <p> * OneStatementPerLineCheck checks the following types of statements: * variable declaration statements, empty statements, assignment statements, * expression statements, increment statements, object creation statements, * 'for loop' statements, 'break' statements, 'continue' statements, * 'return' statements, import statements. * </p> * <p> * The following examples will be flagged as a violation: * </p> * <pre> * //Each line causes violation: * int var1; int var2; * var1 = 1; var2 = 2; * int var1 = 1; int var2 = 2; * var1++; var2++; * Object obj1 = new Object(); Object obj2 = new Object(); * import java.io.EOFException; import java.io.BufferedReader; * ;; //two empty statements on the same line. * * //Multi-line statements: * int var1 = 1 * ; var2 = 2; //violation here * int o = 1, p = 2, * r = 5; int t; //violation here * </pre> * * @author Alexander Jesse * @author Oliver Burn * @author Andrei Selkin */ public final class OneStatementPerLineCheck extends Check { /** * A key is pointing to the warning message text in "messages.properties" * file. */ public static final String MSG_KEY = "multiple.statements.line"; /** * Hold the line-number where the last statement ended. */ private int lastStatementEnd = -1; /** * Hold the line-number where the last 'for-loop' statement ended. */ private int forStatementEnd = -1; /** * The for-header usually has 3 statements on one line, but THIS IS OK. */ private boolean inForHeader; @Override public int[] getDefaultTokens() { return getAcceptableTokens(); } @Override public int[] getAcceptableTokens() { return new int[]{ TokenTypes.SEMI, TokenTypes.FOR_INIT, TokenTypes.FOR_ITERATOR, }; } @Override public int[] getRequiredTokens() { return getAcceptableTokens(); } @Override public void beginTree(DetailAST rootAST) { inForHeader = false; lastStatementEnd = -1; forStatementEnd = -1; } @Override public void visitToken(DetailAST ast) { switch (ast.getType()) { case TokenTypes.SEMI: DetailAST currentStatement = ast; if (isMultilineStatement(currentStatement)) { currentStatement = ast.getPreviousSibling(); } if (isOnTheSameLine(currentStatement, lastStatementEnd, forStatementEnd) && !inForHeader) { log(ast, MSG_KEY); } break; case TokenTypes.FOR_ITERATOR: forStatementEnd = ast.getLineNo(); break; default: inForHeader = true; break; } } @Override public void leaveToken(DetailAST ast) { switch (ast.getType()) { case TokenTypes.SEMI: lastStatementEnd = ast.getLineNo(); forStatementEnd = -1; break; case TokenTypes.FOR_ITERATOR: inForHeader = false; break; default: break; } } /** * Checks whether two statements are on the same line. * @param ast token for the current statement. * @param lastStatementEnd the line-number where the last statement ended. * @param forStatementEnd the line-number where the last 'for-loop' * statement ended. * @return true if two statements are on the same line. */ private static boolean isOnTheSameLine(DetailAST ast, int lastStatementEnd, int forStatementEnd) { return lastStatementEnd == ast.getLineNo() && forStatementEnd != ast.getLineNo(); } /** * Checks whether statement is multiline. * @param ast token for the current statement. * @return true if one statement is distributed over two or more lines. */ private static boolean isMultilineStatement(DetailAST ast) { final boolean multiline; if (ast.getPreviousSibling() == null) { multiline = false; } else { final DetailAST prevSibling = ast.getPreviousSibling(); multiline = prevSibling.getLineNo() != ast.getLineNo() && ast.getParent() != null; } return multiline; } }
jasonchaffee/checkstyle
src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheck.java
Java
lgpl-2.1
6,201
#!/usr/bin/env python import pygtk pygtk.require('2.0') import pynotify import sys if __name__ == '__main__': if not pynotify.init("XY"): sys.exit(1) n = pynotify.Notification("X, Y Test", "This notification should point to 150, 10") n.set_hint("x", 150) n.set_hint("y", 10) if not n.show(): print "Failed to send notification" sys.exit(1)
Distrotech/notify-python
tests/test-xy.py
Python
lgpl-2.1
418
<?php // (c) Copyright 2002-2012 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: wikiplugin_titlesearch.php 41425 2012-05-11 02:02:22Z lindonb $ require_once "lib/wiki/pluginslib.php"; function wikiplugin_titlesearch_info() { return array( 'name' => tra('Title Search'), 'documentation' => 'PluginTitleSearch', 'description' => tra('Search pages by title'), 'prefs' => array( 'feature_wiki', 'wikiplugin_titlesearch' ), 'icon' => 'img/icons/page_find.png', 'params' => array( 'search' => array( 'required' => true, 'name' => tra('Search Criteria'), 'description' => tra('Portion of a page name.'), 'default' => '', ), 'info' => array( 'required' => false, 'name' => tra('Information'), 'description' => tra('Also show page hits or user'), 'default' => '', 'options' => array( array('text' => '', 'value' => ''), array('text' => tra('Hits'), 'value' => 'hits'), array('text' => tra('User'), 'value' => 'user') ) ), 'exclude' => array( 'required' => false, 'name' => tra('Exclude'), 'description' => tra('Pipe-separated list of page names to exclude from results.'), 'default' => '', ), 'noheader' => array( 'required' => false, 'name' => tra('No Header'), 'description' => tra('Set to 1 (Yes) to have no header for the search results.'), 'default' => 0, 'options' => array( array('text' => '', 'value' => ''), array('text' => tra('Yes'), 'value' => 1), array('text' => tra('No'), 'value' => 0) ) ), ), ); } class WikiPluginTitleSearch extends PluginsLib { var $expanded_params = array("exclude", "info"); function getDescription() { return wikiplugin_titlesearch_help(); } function getDefaultArguments() { return array('exclude' => '' , 'noheader' => 0, 'info' => false, 'search' => false, 'style' => 'table' ); } function getName() { return "TitleSearch"; } function getVersion() { return preg_replace("/[Revision: $]/", '', "\$Revision: 1.25 $"); } function run ($data, $params) { global $wikilib; include_once('lib/wiki/wikilib.php'); global $tikilib; $aInfoPreset = array_keys($this->aInfoPresetNames); $params = $this->getParams($params, true); extract($params, EXTR_SKIP); if (!$search) { return $this->error("You have to define a search"); } // no additional infos in list output if (isset($style) && $style == 'list') $info = false; // ///////////////////////////////// // Create a valid list for $info ///////////////////////////////// // if ($info) { $info_temp = array(); foreach ($info as $sInfo) { if (in_array(trim($sInfo), $aInfoPreset)) { $info_temp[] = trim($sInfo); } $info = $info_temp?$info_temp: false; } } else { $info = false; } // ///////////////////////////////// // Process pages ///////////////////////////////// // $sOutput = ""; $aPages = $tikilib->list_pages(0, -1, 'pageName_desc', $search, null, false); foreach ($aPages["data"] as $idPage => $aPage) { if (in_array($aPage["pageName"], $exclude)) { unset($aPages["data"][$idPage]); $aPages["cant"]--; } } // ///////////////////////////////// // Start of Output ///////////////////////////////// // if (isset($noheader) && !$noheader) { // Create header $count = $aPages["cant"]; if (!$count) { $sOutput .= tra("No pages found for title search")." '__".$search."__'"; } elseif ($count == 1) { $sOutput .= tra("One page found for title search")." '__".$search."__'"; } else { $sOutput = "$count ".tra("pages found for title search")." '__".$search."__'"; } $sOutput .= "\n"; } if (isset($style) && $style == 'list') { $sOutput.=PluginsLibUtil::createList($aPages["data"]); } else { $sOutput.=PluginsLibUtil::createTable($aPages["data"], $info); } return $sOutput; } } function wikiplugin_titlesearch($data, $params) { $plugin = new WikiPluginTitleSearch(); return $plugin->run($data, $params); }
railfuture/tiki-website
lib/wiki-plugins/wikiplugin_titlesearch.php
PHP
lgpl-2.1
4,226
/* * (C) Copyright 2014 Kurento (http://kurento.org/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * */ package org.kurento.tutorial.player; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.kurento.client.EndOfStreamEvent; import org.kurento.client.EventListener; import org.kurento.client.FaceOverlayFilter; import org.kurento.client.HttpGetEndpoint; import org.kurento.client.MediaPipeline; import org.kurento.client.PlayerEndpoint; import org.kurento.client.KurentoClient; /** * HTTP Player with Kurento; the media pipeline is composed by a PlayerEndpoint * connected to a filter (FaceOverlay) and an HttpGetEnpoint; the default * desktop web browser is launched to play the video. * * @author Micael Gallego (micael.gallego@gmail.com) * @author Boni Garcia (bgarcia@gsyc.es) * @since 5.0.0 */ public class KurentoHttpPlayer { public static void main(String[] args) throws IOException, URISyntaxException, InterruptedException { // Connecting to Kurento Server KurentoClient kurento = KurentoClient .create("ws://localhost:8888/kurento"); // Creating media pipeline MediaPipeline pipeline = kurento.createMediaPipeline(); // Creating media elements PlayerEndpoint player = new PlayerEndpoint.Builder(pipeline, "http://files.kurento.org/video/fiwarecut.mp4").build(); FaceOverlayFilter filter = new FaceOverlayFilter.Builder(pipeline) .build(); filter.setOverlayedImage( "http://files.kurento.org/imgs/mario-wings.png", -0.2F, -1.1F, 1.6F, 1.6F); HttpGetEndpoint http = new HttpGetEndpoint.Builder(pipeline).build(); // Connecting media elements player.connect(filter); filter.connect(http); // Reacting to events player.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() { @Override public void onEvent(EndOfStreamEvent event) { System.out.println("The playing has finished"); System.exit(0); } }); // Playing media and opening the default desktop browser player.play(); String videoUrl = http.getUrl(); Desktop.getDesktop().browse(new URI(videoUrl)); // Setting a delay to wait the EndOfStream event, previously subscribed Thread.sleep(60000); } }
oclab/howto-callme
kurento-http-player/src/main/java/org/kurento/tutorial/player/KurentoHttpPlayer.java
Java
lgpl-2.1
2,724
// --------------------------------------------------------------------- // // Copyright (C) 2007 - 2013 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #include <deal.II/numerics/fe_field_function.templates.h> #include <deal.II/multigrid/mg_dof_handler.h> #include <deal.II/dofs/dof_handler.h> #include <deal.II/dofs/dof_accessor.h> #include <deal.II/hp/dof_handler.h> #include <deal.II/lac/vector.h> #include <deal.II/lac/block_vector.h> #include <deal.II/lac/parallel_vector.h> #include <deal.II/lac/parallel_block_vector.h> #include <deal.II/lac/petsc_vector.h> #include <deal.II/lac/petsc_block_vector.h> #include <deal.II/lac/trilinos_vector.h> #include <deal.II/lac/trilinos_block_vector.h> DEAL_II_NAMESPACE_OPEN namespace Functions { # include "fe_field_function.inst" } DEAL_II_NAMESPACE_CLOSE
flow123d/dealii
source/numerics/fe_field_function.cc
C++
lgpl-2.1
1,304
<?php // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: mod-func-breadcrumbs.php 44444 2013-01-05 21:24:24Z changi67 $ //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) { header("location: index.php"); exit; } /** * @return array */ function module_breadcrumbs_info() { return array( 'name' => tra('Breadcrumbs'), 'description' => tra('A hierarchy of where you are. Ex.: Home > Section1 > Subsection C.'), 'prefs' => array('feature_breadcrumbs'), 'params' => array( 'label' => array( 'name' => tra('Label'), 'description' => tra('Label preceding the crumbs.'), 'filter' => 'text', 'default' => 'Location : ', ), 'menuId' => array( 'name' => tra('Menu Id'), 'description' => tra('Menu to take the crumb trail from.'), 'filter' => 'int', 'default' => 0, ), 'menuStartLevel' => array( 'name' => tra('Menu Start Level'), 'description' => tra('Lowest level of the menu to display.'), 'filter' => 'int', 'default' => null, ), 'menuStopLevel' => array( 'name' => tra('Menu Stop Level'), 'description' => tra('Highest level of the menu to display.'), 'filter' => 'int', 'default' => null, ), 'showFirst' => array( 'name' => tra('Show Site Crumb'), 'description' => tra('Display the first crumb, usually the site, when using menu crumbs.'), 'filter' => 'alpha', 'default' => 'y', ), 'showLast' => array( 'name' => tra('Show Page Crumb'), 'description' => tra('Display the last crumb, usually the page, when using menu crumbs.'), 'filter' => 'alpha', 'default' => 'y', ), 'showLinks' => array( 'name' => tra('Show Crumb Links'), 'description' => tra('Display links on the crumbs.'), 'filter' => 'alpha', 'default' => 'y', ), ), ); } /** * @param $mod_reference * @param $module_params */ function module_breadcrumbs($mod_reference, $module_params) { global $prefs, $smarty, $crumbs; if (!isset($module_params['label'])) { if ($prefs['feature_siteloclabel'] === 'y') { $module_params['label'] = 'Location : '; } } $binfo = module_breadcrumbs_info(); $defaults = array(); foreach ($binfo['params'] as $k => $v) { $defaults[$k] = $v['default']; } $module_params = array_merge($defaults, $module_params); if (!empty($module_params['menuId'])) { include_once('lib/breadcrumblib.php'); $newCrumbs = breadcrumb_buildMenuCrumbs($crumbs, $module_params['menuId'], $module_params['menuStartLevel'], $module_params['menuStopLevel']); if ($newCrumbs !== $crumbs) { $crumbs = $newCrumbs; } } if ($module_params['showFirst'] === 'n') { $crumbs[0]->hidden = true; } if ($module_params['showLast'] === 'n' && ($module_params['showFirst'] === 'n' || count($crumbs) > 1)) { $crumbs[count($crumbs) - 1]->hidden = true; } $hide = true; foreach ($crumbs as $crumb) { if (!$crumb->hidden) { $hide = false; } } $smarty->assign('crumbs_all_hidden', $hide); $smarty->assign_by_ref('trail', $crumbs); $smarty->assign('module_params', $module_params); }
arildb/tiki-azure
modules/mod-func-breadcrumbs.php
PHP
lgpl-2.1
3,358
module IB module SimpleStop extend OrderPrototype class << self def defaults super.merge order_type: :stop end def aliases super.merge aux_price: :price end def requirements super.merge aux_price: 'Price where the action is triggert. Aliased as :price' end def summary <<-HERE A Stop order is an instruction to submit a buy or sell market order if and when the user-specified stop trigger price is attained or penetrated. A Stop order is not guaranteed a specific execution price and may execute significantly away from its stop price. A Sell Stop order is always placed below the current market price and is typically used to limit a loss or protect a profit on a long stock position. A Buy Stop order is always placed above the current market price. It is typically used to limit a loss or help protect a profit on a short sale. HERE end end end module StopLimit extend OrderPrototype class << self def defaults super.merge order_type: :stop_limit end def aliases Limit.aliases.merge aux_price: :stop_price end def requirements Limit.requirements.merge aux_price: 'Price where the action is triggert. Aliased as :stop_price' end def summary <<-HERE A Stop-Limit order is an instruction to submit a buy or sell limit order when the user-specified stop trigger price is attained or penetrated. The order has two basic components: the stop price and the limit price. When a trade has occurred at or through the stop price, the order becomes executable and enters the market as a limit order, which is an order to buy or sell at a specified price or better. HERE end end end module StopProtected extend OrderPrototype class << self def defaults super.merge order_type: :stop_protected end def aliases SimpleStop.aliases end def requirements SimpleStop.requirements end def summary <<-HERE US-Futures only ---------------------------- A Stop with Protection order combines the functionality of a stop limit order with a market with protection order. The order is set to trigger at a specified stop price. When the stop price is penetrated, the order is triggered as a market with protection order, which means that it will fill within a specified protected price range equal to the trigger price +/- the exchange-defined protection point range. Any portion of the order that does not fill within this protected range is submitted as a limit order at the exchange-defined trigger price +/- the protection points. HERE end end end # module OrderPrototype module TrailingStop extend OrderPrototype class << self def defaults super.merge order_type: :trailing_stop , tif: :day end def aliases super.merge trail_stop_price: :price, aux_price: :trailing_amount end def requirements ## usualy the trail_stop_price is the market-price minus(plus) the trailing_amount super.merge trail_stop_price: 'Price to trigger the action, aliased as :price' end def alternative_parameters { aux_price: 'Trailing distance in absolute terms, aliased as :trailing_amount', trailing_percent: 'Trailing distance in relative terms'} end def summary <<-HERE A "Sell" trailing stop order sets the stop price at a fixed amount below the market price with an attached "trailing" amount. As the market price rises, the stop price rises by the trail amount, but if the stock price falls, the stop loss price doesn't change, and a market order is submitted when the stop price is hit. This technique is designed to allow an investor to specify a limit on the maximum possible loss, without setting a limit on the maximum possible gain. "Buy" trailing stop orders are the mirror image of sell trailing stop orders, and are most appropriate for use in falling markets. Note that Trailing Stop orders can have the trailing amount specified as a percent, or as an absolute amount which is specified in the auxPrice field. HERE end # summary end # class self end # module module TrailingStopLimit extend OrderPrototype class << self def defaults super.merge order_type: :trailing_limit , tif: :day end def aliases Limit.aliases end def requirements super.merge trail_stop_price: 'Price to trigger the action', limit_price_offset: 'a pRICE' end def alternative_parameters { aux_price: 'Trailing distance in absolute terms', trailing_percent: 'Trailing distance in relative terms'} end def summary <<-HERE A trailing stop limit order is designed to allow an investor to specify a limit on the maximum possible loss, without setting a limit on the maximum possible gain. A SELL trailing stop limit moves with the market price, and continually recalculates the stop trigger price at a fixed amount below the market price, based on the user-defined "trailing" amount. The limit order price is also continually recalculated based on the limit offset. As the market price rises, both the stop price and the limit price rise by the trail amount and limit offset respectively, but if the stock price falls, the stop price remains unchanged, and when the stop price is hit a limit order is submitted at the last calculated limit price. A "Buy" trailing stop limit order is the mirror image of a sell trailing stop limit, and is generally used in falling markets. Products: BOND, CFD, CASH, FUT, FOP, OPT, STK, WAR HERE end end # def TrailingStopLimit(action:str, quantity:float, lmtPriceOffset:float, # trailingAmount:float, trailStopPrice:float): # # # ! [trailingstoplimit] # order = Order() # order.action = action # order.orderType = "TRAIL LIMIT" # order.totalQuantity = quantity # order.trailStopPrice = trailStopPrice # order.lmtPriceOffset = lmtPriceOffset # order.auxPrice = trailingAmount # # ! [trailingstoplimit] # return order # # end end
ib-ruby/ib-ruby
lib/ib/order_prototypes/stop.rb
Ruby
lgpl-2.1
6,301
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2016, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ----------------------------- * MeanAndStandardDeviation.java * ----------------------------- * (C) Copyright 2003-2008, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 05-Feb-2002 : Version 1 (DG); * 05-Feb-2005 : Added equals() method and implemented Serializable (DG); * 02-Oct-2007 : Added getMeanValue() and getStandardDeviationValue() methods * for convenience, and toString() method for debugging (DG); * */ package org.jfree.data.statistics; import java.io.Serializable; import org.jfree.util.ObjectUtilities; /** * A simple data structure that holds a mean value and a standard deviation * value. This is used in the * {@link org.jfree.data.statistics.DefaultStatisticalCategoryDataset} class. */ public class MeanAndStandardDeviation implements Serializable { /** For serialization. */ private static final long serialVersionUID = 7413468697315721515L; /** The mean. */ private Number mean; /** The standard deviation. */ private Number standardDeviation; /** * Creates a new mean and standard deviation record. * * @param mean the mean. * @param standardDeviation the standard deviation. */ public MeanAndStandardDeviation(double mean, double standardDeviation) { this(new Double(mean), new Double(standardDeviation)); } /** * Creates a new mean and standard deviation record. * * @param mean the mean ({@code null} permitted). * @param standardDeviation the standard deviation ({@code null} * permitted. */ public MeanAndStandardDeviation(Number mean, Number standardDeviation) { this.mean = mean; this.standardDeviation = standardDeviation; } /** * Returns the mean. * * @return The mean. */ public Number getMean() { return this.mean; } /** * Returns the mean as a double primitive. If the underlying mean is * {@code null}, this method will return {@code Double.NaN}. * * @return The mean. * * @see #getMean() * * @since 1.0.7 */ public double getMeanValue() { double result = Double.NaN; if (this.mean != null) { result = this.mean.doubleValue(); } return result; } /** * Returns the standard deviation. * * @return The standard deviation. */ public Number getStandardDeviation() { return this.standardDeviation; } /** * Returns the standard deviation as a double primitive. If the underlying * standard deviation is {@code null}, this method will return * {@code Double.NaN}. * * @return The standard deviation. * * @since 1.0.7 */ public double getStandardDeviationValue() { double result = Double.NaN; if (this.standardDeviation != null) { result = this.standardDeviation.doubleValue(); } return result; } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object ({@code null} permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof MeanAndStandardDeviation)) { return false; } MeanAndStandardDeviation that = (MeanAndStandardDeviation) obj; if (!ObjectUtilities.equal(this.mean, that.mean)) { return false; } if (!ObjectUtilities.equal( this.standardDeviation, that.standardDeviation) ) { return false; } return true; } /** * Returns a string representing this instance. * * @return A string. * * @since 1.0.7 */ @Override public String toString() { return "[" + this.mean + ", " + this.standardDeviation + "]"; } }
simon04/jfreechart
src/main/java/org/jfree/data/statistics/MeanAndStandardDeviation.java
Java
lgpl-2.1
5,489
/** * Phoebe DOM Implementation. * * This is a C++ approximation of the W3C DOM model, which follows * fairly closely the specifications in the various .idl files, copies of * which are provided for reference. Most important is this one: * * http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/idl-definitions.html * * Authors: * Bob Jamison * * Copyright (C) 2005-2008 Bob Jamison * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * ======================================================================= * NOTES * * */ #include "svgreader.h" #include "dom/cssreader.h" #include "dom/ucd.h" #include "xmlreader.h" #include <stdarg.h> namespace org { namespace w3c { namespace dom { namespace svg { //######################################################################### //# M E S S A G E S //######################################################################### /** * */ void SVGReader::error(char const *fmt, ...) { va_list args; fprintf(stderr, "SVGReader:error: "); va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args) ; fprintf(stderr, "\n"); } /** * */ void SVGReader::trace(char const *fmt, ...) { va_list args; fprintf(stdout, "SVGReader: "); va_start(args, fmt); vfprintf(stdout, fmt, args); va_end(args) ; fprintf(stdout, "\n"); } //######################################################################### //# P A R S I N G //######################################################################### /** * Get the character at the position and record the fact */ XMLCh SVGReader::get(int p) { if (p >= parselen) return 0; XMLCh ch = parsebuf[p]; //printf("%c", ch); lastPosition = p; return ch; } /** * Test if the given substring exists at the given position * in parsebuf. Use get() in case of out-of-bounds */ bool SVGReader::match(int pos, char const *str) { while (*str) { if (get(pos++) != (XMLCh) *str++) return false; } return true; } /** * */ int SVGReader::skipwhite(int p) { while (p < parselen) { //# XML COMMENT if (match(p, "<!--")) { p+=4; bool done=false; while (p<parselen) { if (match(p, "-->")) { p+=3; done=true; break; } p++; } lastPosition = p; if (!done) { error("unterminated <!-- .. --> comment"); return -1; } } //# C comment else if (match(p, "/*")) { p+=2; bool done=false; while (p<parselen) { if (match(p, "*/")) { p+=2; done=true; break; } p++; } lastPosition = p; if (!done) { error("unterminated /* .. */ comment"); return -1; } } else if (!uni_is_space(get(p))) break; else p++; } lastPosition = p; return p; } /** * get a word from the buffer */ int SVGReader::getWord(int p, DOMString &result) { XMLCh ch = get(p); if (!uni_is_letter(ch)) return p; DOMString str; str.push_back(ch); p++; while (p < parselen) { ch = get(p); if (uni_is_letter_or_digit(ch) || ch=='-' || ch=='_') { str.push_back(ch); p++; } else if (ch == '\\') { p+=2; } else break; } result = str; return p; } # if 0 /** * get a word from the buffer */ int SVGReader::getNumber(int p0, double &result) { int p=p0; DOMString str; //allow sign if (get(p) == '-') { p++; } while (p < parselen) { XMLCh ch = get(p); if (ch<'0' || ch>'9') break; str.push_back(ch); p++; } if (get(p) == '.' && get(p+1)>='0' && get(p+1)<='9') { p++; str.push_back('.'); while (p < parselen) { XMLCh ch = get(p); if (ch<'0' || ch>'9') break; str.push_back(ch); p++; } } if (p>p0) { char *start = (char *)str.c_str(); char *end = NULL; double val = strtod(start, &end); if (end > start) { result = val; return p; } } //not a number return p0; } #endif /** * get a word from the buffer */ int SVGReader::getNumber(int p0, double &result) { int p=p0; char buf[64]; int i; for (i=0 ; i<63 && p<parselen ; i++) { buf[i] = (char) get(p++); } buf[i] = '\0'; char *start = buf; char *end = NULL; double val = strtod(start, &end); if (end > start) { result = val; int count = (int)(end - start); p = p0 + count; return p; } //not a number return p0; } bool SVGReader::parseTransform(const DOMString &str) { parsebuf = str; parselen = str.size(); //printf("transform:%s\n", str.c_str()); SVGTransformList transformList; int p = 0; while (p < parselen) { p = skipwhite(p); DOMString name; int p2 = getWord(p, name); if (p2<0) return false; if (p2<=p) { error("transform: need transform name"); //return false; break; } p = p2; //printf("transform name:%s\n", name.c_str()); //######### MATRIX if (name == "matrix") { p = skipwhite(p); if (get(p++) != '(') { error("matrix transform needs opening '('"); return false; } int nrVals = 0; double vals[6]; bool seenBrace = false; while (p < parselen && nrVals < 6) { p = skipwhite(p); double val = 0.0; p2 = getNumber(p, val); if (p2<0) return false; if (p2<=p) { error("matrix() expected number"); return false; } vals[nrVals++] = val; p = skipwhite(p2); XMLCh ch = get(p); if (ch == ',') { p++; p = skipwhite(p); ch = get(p); } if (ch == ')') { seenBrace = true; p++; break; } } if (!seenBrace) { error("matrix() needs closing brace"); return false; } if (nrVals != 6) { error("matrix() requires exactly 6 arguments"); return false; } //We got our arguments //printf("translate: %f %f %f %f %f %f\n", // vals[0], vals[1], vals[2], vals[3], vals[4], vals[5]); SVGMatrix matrix(vals[0], vals[1], vals[2], vals[3], vals[4], vals[5]); SVGTransform transform; transform.setMatrix(matrix); transformList.appendItem(transform); } //######### TRANSLATE else if (name == "translate") { p = skipwhite(p); if (get(p++) != '(') { error("matrix transform needs opening '('"); return false; } p = skipwhite(p); double x = 0.0; p2 = getNumber(p, x); if (p2<0) return false; if (p2<=p) { error("translate() expected 'x' value"); return false; } p = skipwhite(p2); if (get(p) == ',') { p++; p = skipwhite(p); } double y = 0.0; p2 = getNumber(p, y); if (p2<0) return false; if (p2<=p) //no y specified. use default y = 0.0; p = skipwhite(p2); if (get(p++) != ')') { error("translate() needs closing ')'"); return false; } //printf("translate: %f %f\n", x, y); SVGTransform transform; transform.setTranslate(x, y); transformList.appendItem(transform); } //######### SCALE else if (name == "scale") { p = skipwhite(p); if (get(p++) != '(') { error("scale transform needs opening '('"); return false; } p = skipwhite(p); double x = 0.0; p2 = getNumber(p, x); if (p2<0) return false; if (p2<=p) { error("scale() expected 'x' value"); return false; } p = skipwhite(p2); if (get(p) == ',') { p++; p = skipwhite(p); } double y = 0.0; p2 = getNumber(p, y); if (p2<0) return false; if (p2<=p) //no y specified. use default y = x; // y is same as x. uniform scaling p = skipwhite(p2); if (get(p++) != ')') { error("scale() needs closing ')'"); return false; } //printf("scale: %f %f\n", x, y); SVGTransform transform; transform.setScale(x, y); transformList.appendItem(transform); } //######### ROTATE else if (name == "rotate") { p = skipwhite(p); if (get(p++) != '(') { error("rotate transform needs opening '('"); return false; } p = skipwhite(p); double angle = 0.0; p2 = getNumber(p, angle); if (p2<0) return false; if (p2<=p) { error("rotate() expected 'angle' value"); return false; } p = skipwhite(p2); if (get(p) == ',') { p++; p = skipwhite(p); } double cx = 0.0; double cy = 0.0; p2 = getNumber(p, cx); if (p2>p) { p = skipwhite(p2); if (get(p) == ',') { p++; p = skipwhite(p); } p2 = getNumber(p, cy); if (p2<0) return false; if (p2<=p) { error("rotate() arguments should be either rotate(angle) or rotate(angle, cx, cy)"); return false; } p = skipwhite(p2); } if (get(p++) != ')') { error("rotate() needs closing ')'"); return false; } //printf("rotate: %f %f %f\n", angle, cx, cy); SVGTransform transform; transform.setRotate(angle, cx, cy); transformList.appendItem(transform); } //######### SKEWX else if (name == "skewX") { p = skipwhite(p); if (get(p++) != '(') { error("skewX transform needs opening '('"); return false; } p = skipwhite(p); double x = 0.0; p2 = getNumber(p, x); if (p2<0) return false; if (p2<=p) { error("skewX() expected 'x' value"); return false; } p = skipwhite(p2); if (get(p++) != ')') { error("skewX() needs closing ')'"); return false; } //printf("skewX: %f\n", x); SVGTransform transform; transform.setSkewX(x); transformList.appendItem(transform); } //######### SKEWY else if (name == "skewY") { p = skipwhite(p); if (get(p++) != '(') { error("skewY transform needs opening '('"); return false; } p = skipwhite(p); double y = 0.0; p2 = getNumber(p, y); if (p2<0) return false; if (p2<=p) { error("skewY() expected 'y' value"); return false; } p = skipwhite(p2); if (get(p++) != ')') { error("skewY() needs closing ')'"); return false; } //printf("skewY: %f\n", y); SVGTransform transform; transform.setSkewY(y); transformList.appendItem(transform); } //### NONE OF THE ABOVE else { error("unknown transform type:'%s'", name.c_str()); } p = skipwhite(p); XMLCh ch = get(p); if (ch == ',') { p++; p = skipwhite(p); } }//WHILE p<parselen return true; } /** * */ bool SVGReader::parseElement(SVGElementImplPtr parent, ElementImplPtr sourceElem) { if (!parent) { error("NULL dest element"); return false; } if (!sourceElem) { error("NULL source element"); return false; } DOMString namespaceURI = sourceElem->getNamespaceURI(); //printf("namespaceURI:%s\n", namespaceURI.c_str()); DOMString tagName = sourceElem->getTagName(); printf("tag name:%s\n", tagName.c_str()); ElementPtr newElement = doc->createElementNS(namespaceURI, tagName); if (!newElement) { return false; } NamedNodeMap &attrs = sourceElem->getAttributes(); for (unsigned int i=0 ; i<attrs.getLength() ; i++) { NodePtr n = attrs.item(i); newElement->setAttribute(n->getNodeName(), n->getNodeValue());//should be exception here } parent->appendChild(newElement); NodeList children = sourceElem->getChildNodes(); int nodeCount = children.getLength(); for (int i=0 ; i<nodeCount ; i++) { NodePtr child = children.item(i); int typ = child->getNodeType(); if (typ == Node::TEXT_NODE) { NodePtr newNode = doc->createTextNode(child->getNodeValue()); parent->appendChild(newNode); } else if (typ == Node::CDATA_SECTION_NODE) { NodePtr newNode = doc->createCDATASection(child->getNodeValue()); parent->appendChild(newNode); } else if (newElement.get() && typ == Node::ELEMENT_NODE) { //ElementImplPtr childElement = dynamic_cast<ElementImpl *>(child.get()); //parseElement(newElement, childElement); } } return true; } /** * */ SVGDocumentPtr SVGReader::parse(const DocumentPtr src) { if (!src) { error("NULL source document"); return NULL; } DOMImplementationImpl impl; doc = new SVGDocumentImpl(&impl, SVG_NAMESPACE, "svg" , NULL); SVGElementImplPtr destElem = dynamic_pointer_cast<SVGElementImpl, SVGElement>(doc->getRootElement()); ElementImplPtr srcElem = dynamic_pointer_cast<ElementImpl, Element>(src->getDocumentElement()); if (!parseElement(destElem, srcElem)) { return NULL; } return doc; } /** * */ SVGDocumentPtr SVGReader::parse(const DOMString &buf) { /* remember, smartptrs are null-testable*/ SVGDocumentPtr svgdoc; XmlReader parser; DocumentPtr doc = parser.parse(buf); if (!doc) { return svgdoc; } svgdoc = parse(doc); return svgdoc; } /** * */ SVGDocumentPtr SVGReader::parseFile(const DOMString &fileName) { /* remember, smartptrs are null-testable*/ SVGDocumentPtr svgdoc; XmlReader parser; DocumentPtr doc = parser.parseFile(fileName); if (!doc) { error("Could not load xml doc"); return svgdoc; } svgdoc = parse(doc); return svgdoc; } } //namespace svg } //namespace dom } //namespace w3c } //namespace org /*######################################################################### ## E N D O F F I L E #########################################################################*/
step21/inkscape-osx-packaging-native
src/dom/svgreader.cpp
C++
lgpl-2.1
18,248
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtDeclarative module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "private/qdeclarativestate_p_p.h" #include "private/qdeclarativestate_p.h" #include "private/qdeclarativetransition_p.h" #include "private/qdeclarativestategroup_p.h" #include "private/qdeclarativestateoperations_p.h" #include "private/qdeclarativeanimation_p.h" #include "private/qdeclarativeanimation_p_p.h" #include <qdeclarativebinding_p.h> #include <qdeclarativeglobal_p.h> #include <QtCore/qdebug.h> QT_BEGIN_NAMESPACE DEFINE_BOOL_CONFIG_OPTION(stateChangeDebug, STATECHANGE_DEBUG); QDeclarativeAction::QDeclarativeAction() : restore(true), actionDone(false), reverseEvent(false), deletableToBinding(false), fromBinding(0), event(0), specifiedObject(0) { } QDeclarativeAction::QDeclarativeAction(QObject *target, const QString &propertyName, const QVariant &value) : restore(true), actionDone(false), reverseEvent(false), deletableToBinding(false), property(target, propertyName, qmlEngine(target)), toValue(value), fromBinding(0), event(0), specifiedObject(target), specifiedProperty(propertyName) { if (property.isValid()) fromValue = property.read(); } QDeclarativeAction::QDeclarativeAction(QObject *target, const QString &propertyName, QDeclarativeContext *context, const QVariant &value) : restore(true), actionDone(false), reverseEvent(false), deletableToBinding(false), property(target, propertyName, context), toValue(value), fromBinding(0), event(0), specifiedObject(target), specifiedProperty(propertyName) { if (property.isValid()) fromValue = property.read(); } QDeclarativeActionEvent::~QDeclarativeActionEvent() { } QString QDeclarativeActionEvent::typeName() const { return QString(); } void QDeclarativeActionEvent::execute(Reason) { } bool QDeclarativeActionEvent::isReversable() { return false; } void QDeclarativeActionEvent::reverse(Reason) { } bool QDeclarativeActionEvent::changesBindings() { return false; } void QDeclarativeActionEvent::clearBindings() { } bool QDeclarativeActionEvent::override(QDeclarativeActionEvent *other) { Q_UNUSED(other); return false; } QDeclarativeStateOperation::QDeclarativeStateOperation(QObjectPrivate &dd, QObject *parent) : QObject(dd, parent) { } /*! \qmlclass State QDeclarativeState \ingroup qml-state-elements \since 4.7 \brief The State element defines configurations of objects and properties. A \e state is a set of batched changes from the default configuration. All items have a default state that defines the default configuration of objects and property values. New states can be defined by adding State items to the \l {Item::states}{states} property to allow items to switch between different configurations. These configurations can, for example, be used to apply different sets of property values or execute different scripts. The following example displays a single \l Rectangle. In the default state, the rectangle is colored black. In the "clicked" state, a PropertyChanges element changes the rectangle's color to red. Clicking within the MouseArea toggles the rectangle's state between the default state and the "clicked" state, thus toggling the color of the rectangle between black and red. \snippet doc/src/snippets/declarative/state.qml 0 Notice the default state is referred to using an empty string (""). States are commonly used together with \l{QML Animation and Transitions}{Transitions} to provide animations when state changes occur. \note Setting the state of an object from within another state of the same object is not allowed. \sa {declarative/animation/states}{states example}, {qmlstates}{States}, {QML Animation and Transitions}{Transitions}, QtDeclarative */ QDeclarativeState::QDeclarativeState(QObject *parent) : QObject(*(new QDeclarativeStatePrivate), parent) { Q_D(QDeclarativeState); d->transitionManager.setState(this); } QDeclarativeState::~QDeclarativeState() { Q_D(QDeclarativeState); if (d->group) d->group->removeState(this); /* destroying an active state does not return us to the base state, so we need to clean up our revert list to prevent leaks. In the future we may want to redconsider this overall architecture. */ for (int i = 0; i < d->revertList.count(); ++i) { if (d->revertList.at(i).binding()) { d->revertList.at(i).binding()->destroy(); } } } /*! \qmlproperty string State::name This property holds the name of the state. Each state should have a unique name within its item. */ QString QDeclarativeState::name() const { Q_D(const QDeclarativeState); return d->name; } void QDeclarativeState::setName(const QString &n) { Q_D(QDeclarativeState); d->name = n; d->named = true; } bool QDeclarativeState::isNamed() const { Q_D(const QDeclarativeState); return d->named; } bool QDeclarativeState::isWhenKnown() const { Q_D(const QDeclarativeState); return d->when != 0; } /*! \qmlproperty bool State::when This property holds when the state should be applied. This should be set to an expression that evaluates to \c true when you want the state to be applied. For example, the following \l Rectangle changes in and out of the "hidden" state when the \l MouseArea is pressed: \snippet doc/src/snippets/declarative/state-when.qml 0 If multiple states in a group have \c when clauses that evaluate to \c true at the same time, the first matching state will be applied. For example, in the following snippet \c state1 will always be selected rather than \c state2 when sharedCondition becomes \c true. \qml Item { states: [ State { name: "state1"; when: sharedCondition }, State { name: "state2"; when: sharedCondition } ] // ... } \endqml */ QDeclarativeBinding *QDeclarativeState::when() const { Q_D(const QDeclarativeState); return d->when; } void QDeclarativeState::setWhen(QDeclarativeBinding *when) { Q_D(QDeclarativeState); d->when = when; if (d->group) d->group->updateAutoState(); } /*! \qmlproperty string State::extend This property holds the state that this state extends. When a state extends another state, it inherits all the changes of that state. The state being extended is treated as the base state in regards to the changes specified by the extending state. */ QString QDeclarativeState::extends() const { Q_D(const QDeclarativeState); return d->extends; } void QDeclarativeState::setExtends(const QString &extends) { Q_D(QDeclarativeState); d->extends = extends; } /*! \qmlproperty list<Change> State::changes This property holds the changes to apply for this state \default By default these changes are applied against the default state. If the state extends another state, then the changes are applied against the state being extended. */ QDeclarativeListProperty<QDeclarativeStateOperation> QDeclarativeState::changes() { Q_D(QDeclarativeState); return QDeclarativeListProperty<QDeclarativeStateOperation>(this, &d->operations, QDeclarativeStatePrivate::operations_append, QDeclarativeStatePrivate::operations_count, QDeclarativeStatePrivate::operations_at, QDeclarativeStatePrivate::operations_clear); } int QDeclarativeState::operationCount() const { Q_D(const QDeclarativeState); return d->operations.count(); } QDeclarativeStateOperation *QDeclarativeState::operationAt(int index) const { Q_D(const QDeclarativeState); return d->operations.at(index); } QDeclarativeState &QDeclarativeState::operator<<(QDeclarativeStateOperation *op) { Q_D(QDeclarativeState); d->operations.append(QDeclarativeStatePrivate::OperationGuard(op, &d->operations)); return *this; } void QDeclarativeStatePrivate::complete() { Q_Q(QDeclarativeState); for (int ii = 0; ii < reverting.count(); ++ii) { for (int jj = 0; jj < revertList.count(); ++jj) { if (revertList.at(jj).property() == reverting.at(ii)) { revertList.removeAt(jj); break; } } } reverting.clear(); emit q->completed(); } // Generate a list of actions for this state. This includes coelescing state // actions that this state "extends" QDeclarativeStateOperation::ActionList QDeclarativeStatePrivate::generateActionList(QDeclarativeStateGroup *group) const { QDeclarativeStateOperation::ActionList applyList; if (inState) return applyList; // Prevent "extends" recursion inState = true; if (!extends.isEmpty()) { QList<QDeclarativeState *> states = group->states(); for (int ii = 0; ii < states.count(); ++ii) if (states.at(ii)->name() == extends) { qmlExecuteDeferred(states.at(ii)); applyList = static_cast<QDeclarativeStatePrivate*>(states.at(ii)->d_func())->generateActionList(group); } } foreach(QDeclarativeStateOperation *op, operations) applyList << op->actions(); inState = false; return applyList; } QDeclarativeStateGroup *QDeclarativeState::stateGroup() const { Q_D(const QDeclarativeState); return d->group; } void QDeclarativeState::setStateGroup(QDeclarativeStateGroup *group) { Q_D(QDeclarativeState); d->group = group; } void QDeclarativeState::cancel() { Q_D(QDeclarativeState); d->transitionManager.cancel(); } void QDeclarativeAction::deleteFromBinding() { if (fromBinding) { QDeclarativePropertyPrivate::setBinding(property, 0); fromBinding->destroy(); fromBinding = 0; } } bool QDeclarativeState::containsPropertyInRevertList(QObject *target, const QString &name) const { Q_D(const QDeclarativeState); if (isStateActive()) { QListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList); while (revertListIterator.hasNext()) { const QDeclarativeSimpleAction &simpleAction = revertListIterator.next(); if (simpleAction.specifiedObject() == target && simpleAction.specifiedProperty() == name) return true; } } return false; } bool QDeclarativeState::changeValueInRevertList(QObject *target, const QString &name, const QVariant &revertValue) { Q_D(QDeclarativeState); if (isStateActive()) { QMutableListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList); while (revertListIterator.hasNext()) { QDeclarativeSimpleAction &simpleAction = revertListIterator.next(); if (simpleAction.specifiedObject() == target && simpleAction.specifiedProperty() == name) { simpleAction.setValue(revertValue); return true; } } } return false; } bool QDeclarativeState::changeBindingInRevertList(QObject *target, const QString &name, QDeclarativeAbstractBinding *binding) { Q_D(QDeclarativeState); if (isStateActive()) { QMutableListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList); while (revertListIterator.hasNext()) { QDeclarativeSimpleAction &simpleAction = revertListIterator.next(); if (simpleAction.specifiedObject() == target && simpleAction.specifiedProperty() == name) { if (simpleAction.binding()) simpleAction.binding()->destroy(); simpleAction.setBinding(binding); return true; } } } return false; } bool QDeclarativeState::removeEntryFromRevertList(QObject *target, const QString &name) { Q_D(QDeclarativeState); if (isStateActive()) { QMutableListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList); while (revertListIterator.hasNext()) { QDeclarativeSimpleAction &simpleAction = revertListIterator.next(); if (simpleAction.property().object() == target && simpleAction.property().name() == name) { QDeclarativeAbstractBinding *oldBinding = QDeclarativePropertyPrivate::binding(simpleAction.property()); if (oldBinding) { QDeclarativePropertyPrivate::setBinding(simpleAction.property(), 0); oldBinding->destroy(); } simpleAction.property().write(simpleAction.value()); if (simpleAction.binding()) QDeclarativePropertyPrivate::setBinding(simpleAction.property(), simpleAction.binding()); revertListIterator.remove(); return true; } } } return false; } void QDeclarativeState::addEntryToRevertList(const QDeclarativeAction &action) { Q_D(QDeclarativeState); QDeclarativeSimpleAction simpleAction(action); d->revertList.append(simpleAction); } void QDeclarativeState::removeAllEntriesFromRevertList(QObject *target) { Q_D(QDeclarativeState); if (isStateActive()) { QMutableListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList); while (revertListIterator.hasNext()) { QDeclarativeSimpleAction &simpleAction = revertListIterator.next(); if (simpleAction.property().object() == target) { QDeclarativeAbstractBinding *oldBinding = QDeclarativePropertyPrivate::binding(simpleAction.property()); if (oldBinding) { QDeclarativePropertyPrivate::setBinding(simpleAction.property(), 0); oldBinding->destroy(); } simpleAction.property().write(simpleAction.value()); if (simpleAction.binding()) QDeclarativePropertyPrivate::setBinding(simpleAction.property(), simpleAction.binding()); revertListIterator.remove(); } } } } void QDeclarativeState::addEntriesToRevertList(const QList<QDeclarativeAction> &actionList) { Q_D(QDeclarativeState); if (isStateActive()) { QList<QDeclarativeSimpleAction> simpleActionList; QListIterator<QDeclarativeAction> actionListIterator(actionList); while(actionListIterator.hasNext()) { const QDeclarativeAction &action = actionListIterator.next(); QDeclarativeSimpleAction simpleAction(action); action.property.write(action.toValue); if (!action.toBinding.isNull()) { QDeclarativeAbstractBinding *oldBinding = QDeclarativePropertyPrivate::binding(simpleAction.property()); if (oldBinding) QDeclarativePropertyPrivate::setBinding(simpleAction.property(), 0); QDeclarativePropertyPrivate::setBinding(simpleAction.property(), action.toBinding.data(), QDeclarativePropertyPrivate::DontRemoveBinding); } simpleActionList.append(simpleAction); } d->revertList.append(simpleActionList); } } QVariant QDeclarativeState::valueInRevertList(QObject *target, const QString &name) const { Q_D(const QDeclarativeState); if (isStateActive()) { QListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList); while (revertListIterator.hasNext()) { const QDeclarativeSimpleAction &simpleAction = revertListIterator.next(); if (simpleAction.specifiedObject() == target && simpleAction.specifiedProperty() == name) return simpleAction.value(); } } return QVariant(); } QDeclarativeAbstractBinding *QDeclarativeState::bindingInRevertList(QObject *target, const QString &name) const { Q_D(const QDeclarativeState); if (isStateActive()) { QListIterator<QDeclarativeSimpleAction> revertListIterator(d->revertList); while (revertListIterator.hasNext()) { const QDeclarativeSimpleAction &simpleAction = revertListIterator.next(); if (simpleAction.specifiedObject() == target && simpleAction.specifiedProperty() == name) return simpleAction.binding(); } } return 0; } bool QDeclarativeState::isStateActive() const { return stateGroup() && stateGroup()->state() == name(); } void QDeclarativeState::apply(QDeclarativeStateGroup *group, QDeclarativeTransition *trans, QDeclarativeState *revert) { Q_D(QDeclarativeState); qmlExecuteDeferred(this); cancel(); if (revert) revert->cancel(); d->revertList.clear(); d->reverting.clear(); if (revert) { QDeclarativeStatePrivate *revertPrivate = static_cast<QDeclarativeStatePrivate*>(revert->d_func()); d->revertList = revertPrivate->revertList; revertPrivate->revertList.clear(); } // List of actions caused by this state QDeclarativeStateOperation::ActionList applyList = d->generateActionList(group); // List of actions that need to be reverted to roll back (just) this state QDeclarativeStatePrivate::SimpleActionList additionalReverts; // First add the reverse of all the applyList actions for (int ii = 0; ii < applyList.count(); ++ii) { QDeclarativeAction &action = applyList[ii]; if (action.event) { if (!action.event->isReversable()) continue; bool found = false; for (int jj = 0; jj < d->revertList.count(); ++jj) { QDeclarativeActionEvent *event = d->revertList.at(jj).event(); if (event && event->typeName() == action.event->typeName()) { if (action.event->override(event)) { found = true; if (action.event != d->revertList.at(jj).event() && action.event->needsCopy()) { action.event->copyOriginals(d->revertList.at(jj).event()); QDeclarativeSimpleAction r(action); additionalReverts << r; d->revertList.removeAt(jj); --jj; } else if (action.event->isRewindable()) //###why needed? action.event->saveCurrentValues(); break; } } } if (!found) { action.event->saveOriginals(); // Only need to revert the applyList action if the previous // state doesn't have a higher priority revert already QDeclarativeSimpleAction r(action); additionalReverts << r; } } else { bool found = false; action.fromBinding = QDeclarativePropertyPrivate::binding(action.property); for (int jj = 0; jj < d->revertList.count(); ++jj) { if (d->revertList.at(jj).property() == action.property) { found = true; if (d->revertList.at(jj).binding() != action.fromBinding) { action.deleteFromBinding(); } break; } } if (!found) { if (!action.restore) { action.deleteFromBinding();; } else { // Only need to revert the applyList action if the previous // state doesn't have a higher priority revert already QDeclarativeSimpleAction r(action); additionalReverts << r; } } } } // Any reverts from a previous state that aren't carried forth // into this state need to be translated into apply actions for (int ii = 0; ii < d->revertList.count(); ++ii) { bool found = false; if (d->revertList.at(ii).event()) { QDeclarativeActionEvent *event = d->revertList.at(ii).event(); if (!event->isReversable()) continue; for (int jj = 0; !found && jj < applyList.count(); ++jj) { const QDeclarativeAction &action = applyList.at(jj); if (action.event && action.event->typeName() == event->typeName()) { if (action.event->override(event)) found = true; } } } else { for (int jj = 0; !found && jj < applyList.count(); ++jj) { const QDeclarativeAction &action = applyList.at(jj); if (action.property == d->revertList.at(ii).property()) found = true; } } if (!found) { QVariant cur = d->revertList.at(ii).property().read(); QDeclarativeAbstractBinding *delBinding = QDeclarativePropertyPrivate::setBinding(d->revertList.at(ii).property(), 0); if (delBinding) delBinding->destroy(); QDeclarativeAction a; a.property = d->revertList.at(ii).property(); a.fromValue = cur; a.toValue = d->revertList.at(ii).value(); a.toBinding = QDeclarativeAbstractBinding::getPointer(d->revertList.at(ii).binding()); a.specifiedObject = d->revertList.at(ii).specifiedObject(); a.specifiedProperty = d->revertList.at(ii).specifiedProperty(); a.event = d->revertList.at(ii).event(); a.reverseEvent = d->revertList.at(ii).reverseEvent(); if (a.event && a.event->isRewindable()) a.event->saveCurrentValues(); applyList << a; // Store these special reverts in the reverting list d->reverting << d->revertList.at(ii).property(); } } // All the local reverts now become part of the ongoing revertList d->revertList << additionalReverts; #ifndef QT_NO_DEBUG_STREAM // Output for debugging if (stateChangeDebug()) { foreach(const QDeclarativeAction &action, applyList) { if (action.event) qWarning() << " QDeclarativeAction event:" << action.event->typeName(); else qWarning() << " QDeclarativeAction:" << action.property.object() << action.property.name() << "From:" << action.fromValue << "To:" << action.toValue; } } #endif d->transitionManager.transition(applyList, trans); } QDeclarativeStateOperation::ActionList QDeclarativeStateOperation::actions() { return ActionList(); } QDeclarativeState *QDeclarativeStateOperation::state() const { Q_D(const QDeclarativeStateOperation); return d->m_state; } void QDeclarativeStateOperation::setState(QDeclarativeState *state) { Q_D(QDeclarativeStateOperation); d->m_state = state; } QT_END_NAMESPACE
nonrational/qt-everywhere-opensource-src-4.8.6
src/declarative/util/qdeclarativestate.cpp
C++
lgpl-2.1
25,066
package techcore import "github.com/nsf/termbox-go" type Color int const ( ColorBlack Color = 1 << iota ColorBlue ColorCyan ColorGreen ColorMagenta ColorRed ColorWhite ColorYellow ColorAlpha ) func (c Color) GetTermboxColor() termbox.Attribute { switch c { case ColorBlack: return termbox.ColorBlack case ColorBlue: return termbox.ColorBlue case ColorCyan: return termbox.ColorCyan case ColorGreen: return termbox.ColorGreen case ColorMagenta: return termbox.ColorMagenta case ColorRed: return termbox.ColorRed case ColorWhite: return termbox.ColorWhite case ColorYellow: return termbox.ColorYellow case ColorAlpha: return termbox.ColorDefault default: return termbox.ColorDefault } }
christianap/TechCore
colors.go
GO
lgpl-2.1
730
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "ldparser.h" #include "projectexplorerconstants.h" #include "task.h" using namespace ProjectExplorer; namespace { // opt. drive letter + filename: (2 brackets) const char * const FILE_PATTERN = "(([A-Za-z]:)?[^:]+\\.[^:]+):"; // line no. or elf segment + offset (1 bracket) // const char * const POSITION_PATTERN = "(\\d+|\\(\\.[^:]+[+-]0x[a-fA-F0-9]+\\):)"; const char * const POSITION_PATTERN = "(\\d|\\(\\..+[+-]0x[a-fA-F0-9]+\\):)"; const char * const COMMAND_PATTERN = "^(.*[\\\\/])?([a-z0-9]+-[a-z0-9]+-[a-z0-9]+-)?(ld|gold)(-[0-9\\.]+)?(\\.exe)?: "; } LdParser::LdParser() { setObjectName(QLatin1String("LdParser")); m_regExpLinker.setPattern(QLatin1Char('^') + QString::fromLatin1(FILE_PATTERN) + QLatin1Char('(') + QString::fromLatin1(FILE_PATTERN) + QLatin1String(")?(") + QLatin1String(POSITION_PATTERN) + QLatin1String(")?\\s(.+)$")); m_regExpLinker.setMinimal(true); m_regExpGccNames.setPattern(QLatin1String(COMMAND_PATTERN)); m_regExpGccNames.setMinimal(true); } void LdParser::stdError(const QString &line) { QString lne = rightTrimmed(line); if (lne.startsWith(QLatin1String("TeamBuilder ")) || lne.startsWith(QLatin1String("distcc[")) || lne.contains(QLatin1String("ar: creating "))) { IOutputParser::stdError(line); return; } if (lne.startsWith(QLatin1String("collect2:"))) { emit addTask(Task(Task::Error, lne /* description */, Utils::FileName() /* filename */, -1 /* linenumber */, Core::Id(Constants::TASK_CATEGORY_COMPILE))); return; } else if (m_regExpGccNames.indexIn(lne) > -1) { QString description = lne.mid(m_regExpGccNames.matchedLength()); Task task(Task::Error, description, Utils::FileName(), /* filename */ -1, /* line */ Core::Id(Constants::TASK_CATEGORY_COMPILE)); if (description.startsWith(QLatin1String("warning: "))) { task.type = Task::Warning; task.description = description.mid(9); } else if (description.startsWith(QLatin1String("fatal: "))) { task.description = description.mid(7); } emit addTask(task); return; } else if (m_regExpLinker.indexIn(lne) > -1) { bool ok; int lineno = m_regExpLinker.cap(7).toInt(&ok); if (!ok) lineno = -1; Utils::FileName filename = Utils::FileName::fromUserInput(m_regExpLinker.cap(1)); if (!m_regExpLinker.cap(4).isEmpty() && !m_regExpLinker.cap(4).startsWith(QLatin1String("(.text"))) filename = Utils::FileName::fromUserInput(m_regExpLinker.cap(4)); QString description = m_regExpLinker.cap(8).trimmed(); Task task(Task::Error, description, filename, lineno, Core::Id(Constants::TASK_CATEGORY_COMPILE)); if (description.startsWith(QLatin1String("At global scope")) || description.startsWith(QLatin1String("At top level")) || description.startsWith(QLatin1String("instantiated from ")) || description.startsWith(QLatin1String("In "))) task.type = Task::Unknown; if (description.startsWith(QLatin1String("warning: "), Qt::CaseInsensitive)) { task.type = Task::Warning; task.description = description.mid(9); } emit addTask(task); return; } IOutputParser::stdError(line); }
duythanhphan/qt-creator
src/plugins/projectexplorer/ldparser.cpp
C++
lgpl-2.1
5,136
/* This file is part of the Grantlee template system. Copyright (c) 2008 Stephen Kelly <steveire@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the Licence, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "texthtmlbuilder.h" #include <QtCore/QList> #include <QtGui/QTextDocument> namespace Grantlee { class TextHTMLBuilderPrivate { public: TextHTMLBuilderPrivate( TextHTMLBuilder *b ) : q_ptr( b ) { } QList<QTextListFormat::Style> currentListItemStyles; QString m_text; TextHTMLBuilder *q_ptr; Q_DECLARE_PUBLIC( TextHTMLBuilder ) }; } using namespace Grantlee; TextHTMLBuilder::TextHTMLBuilder() : AbstractMarkupBuilder(), d_ptr( new TextHTMLBuilderPrivate( this ) ) { } TextHTMLBuilder::~TextHTMLBuilder() { delete d_ptr; } void TextHTMLBuilder::beginStrong() { Q_D( TextHTMLBuilder );; d->m_text.append( QStringLiteral( "<strong>" ) ); } void TextHTMLBuilder::endStrong() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</strong>" ) ); } void TextHTMLBuilder::beginEmph() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "<em>" ) ); } void TextHTMLBuilder::endEmph() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</em>" ) ); } void TextHTMLBuilder::beginUnderline() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "<u>" ) ); } void TextHTMLBuilder::endUnderline() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</u>" ) ); } void TextHTMLBuilder::beginStrikeout() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "<s>" ) ); } void TextHTMLBuilder::endStrikeout() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</s>" ) ); } void TextHTMLBuilder::beginForeground( const QBrush &brush ) { Q_D( TextHTMLBuilder ); d->m_text.append( QString::fromLatin1( "<span style=\"color:%1;\">" ).arg( brush.color().name() ) ); } void TextHTMLBuilder::endForeground() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</span>" ) ); } void TextHTMLBuilder::beginBackground( const QBrush &brush ) { Q_D( TextHTMLBuilder ); d->m_text.append( QString::fromLatin1( "<span style=\"background-color:%1;\">" ).arg( brush.color().name() ) ); } void TextHTMLBuilder::endBackground() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</span>" ) ); } void TextHTMLBuilder::beginAnchor( const QString &href, const QString &name ) { Q_D( TextHTMLBuilder ); if ( !href.isEmpty() ) { if ( !name.isEmpty() ) { d->m_text.append( QString::fromLatin1( "<a href=\"%1\" name=\"%2\">" ).arg( href ).arg( name ) ); } else { d->m_text.append( QString::fromLatin1( "<a href=\"%1\">" ).arg( href ) ); } } else { if ( !name.isEmpty() ) { d->m_text.append( QString::fromLatin1( "<a name=\"%1\">" ).arg( name ) ); } } } void TextHTMLBuilder::endAnchor() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</a>" ) ); } void TextHTMLBuilder::beginFontFamily( const QString &family ) { Q_D( TextHTMLBuilder ); d->m_text.append( QString::fromLatin1( "<span style=\"font-family:%1;\">" ).arg( family ) ); } void TextHTMLBuilder::endFontFamily() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</span>" ) ); } void TextHTMLBuilder::beginFontPointSize( int size ) { Q_D( TextHTMLBuilder ); d->m_text.append( QString::fromLatin1( "<span style=\"font-size:%1pt;\">" ).arg( QString::number( size ) ) ); } void TextHTMLBuilder::endFontPointSize() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</span>" ) ); } void TextHTMLBuilder::beginParagraph( Qt::Alignment al, qreal topMargin, qreal bottomMargin, qreal leftMargin, qreal rightMargin ) { Q_D( TextHTMLBuilder ); // Don't put paragraph tags inside li tags. Qt bug reported. // if (currentListItemStyles.size() != 0) // { QString styleString; if ( topMargin != 0 ) { styleString.append( QString::fromLatin1( "margin-top:%1;" ).arg( topMargin ) ); } if ( bottomMargin != 0 ) { styleString.append( QString::fromLatin1( "margin-bottom:%1;" ).arg( bottomMargin ) ); } if ( leftMargin != 0 ) { styleString.append( QString::fromLatin1( "margin-left:%1;" ).arg( leftMargin ) ); } if ( rightMargin != 0 ) { styleString.append( QString::fromLatin1( "margin-right:%1;" ).arg( rightMargin ) ); } // Using == doesn't work here. // Using bitwise comparison because an alignment can contain a vertical and a horizontal part. if ( al & Qt::AlignRight ) { d->m_text.append( QStringLiteral( "<p align=\"right\" " ) ); } else if ( al & Qt::AlignHCenter ) { d->m_text.append( QStringLiteral( "<p align=\"center\" " ) ); } else if ( al & Qt::AlignJustify ) { d->m_text.append( QStringLiteral( "<p align=\"justify\" " ) ); } else if ( al & Qt::AlignLeft ) { d->m_text.append( QStringLiteral( "<p" ) ); } else { d->m_text.append( QStringLiteral( "<p" ) ); } if ( !styleString.isEmpty() ) { d->m_text.append( QStringLiteral( " \"" ) + styleString + QLatin1Char( '"' ) ); } d->m_text.append( QLatin1Char( '>' ) ); // } } void TextHTMLBuilder::beginHeader( int level ) { Q_D( TextHTMLBuilder ); switch ( level ) { case 1: d->m_text.append( QStringLiteral( "<h1>" ) ); break; case 2: d->m_text.append( QStringLiteral( "<h2>" ) ); break; case 3: d->m_text.append( QStringLiteral( "<h3>" ) ); break; case 4: d->m_text.append( QStringLiteral( "<h4>" ) ); break; case 5: d->m_text.append( QStringLiteral( "<h5>" ) ); break; case 6: d->m_text.append( QStringLiteral( "<h6>" ) ); break; default: break; } } void TextHTMLBuilder::endHeader( int level ) { Q_D( TextHTMLBuilder ); switch ( level ) { case 1: d->m_text.append( QStringLiteral( "</h1>" ) ); break; case 2: d->m_text.append( QStringLiteral( "</h2>" ) ); break; case 3: d->m_text.append( QStringLiteral( "</h3>" ) ); break; case 4: d->m_text.append( QStringLiteral( "</h4>" ) ); break; case 5: d->m_text.append( QStringLiteral( "</h5>" ) ); break; case 6: d->m_text.append( QStringLiteral( "</h6>" ) ); break; default: break; } } void TextHTMLBuilder::endParagraph() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</p>\n" ) ); } void TextHTMLBuilder::addNewline() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "<p>&nbsp;" ) ); } void TextHTMLBuilder::insertHorizontalRule( int width ) { Q_D( TextHTMLBuilder ); if ( width != -1 ) { d->m_text.append( QString::fromLatin1( "<hr width=\"%1\" />\n" ).arg( width ) ); } d->m_text.append( QStringLiteral( "<hr />\n" ) ); } void TextHTMLBuilder::insertImage( const QString &src, qreal width, qreal height ) { Q_D( TextHTMLBuilder ); d->m_text.append( QString::fromLatin1( "<img src=\"%1\" " ).arg( src ) ); if ( width != 0 ) d->m_text.append( QString::fromLatin1( "width=\"%2\" " ).arg( width ) ); if ( height != 0 ) d->m_text.append( QString::fromLatin1( "height=\"%2\" " ).arg( height ) ); d->m_text.append( QStringLiteral( "/>" ) ); } void TextHTMLBuilder::beginList( QTextListFormat::Style type ) { Q_D( TextHTMLBuilder ); d->currentListItemStyles.append( type ); switch ( type ) { case QTextListFormat::ListDisc: d->m_text.append( QStringLiteral( "<ul type=\"disc\">\n" ) ); break; case QTextListFormat::ListCircle: d->m_text.append( QStringLiteral( "\n<ul type=\"circle\">\n" ) ); break; case QTextListFormat::ListSquare: d->m_text.append( QStringLiteral( "\n<ul type=\"square\">\n" ) ); break; case QTextListFormat::ListDecimal: d->m_text.append( QStringLiteral( "\n<ol type=\"1\">\n" ) ); break; case QTextListFormat::ListLowerAlpha: d->m_text.append( QStringLiteral( "\n<ol type=\"a\">\n" ) ); break; case QTextListFormat::ListUpperAlpha: d->m_text.append( QStringLiteral( "\n<ol type=\"A\">\n" ) ); break; case QTextListFormat::ListLowerRoman: d->m_text.append( QStringLiteral("\n<ol type=\"i\">\n") ); break; case QTextListFormat::ListUpperRoman: d->m_text.append( QStringLiteral("\n<ol type=\"I\">\n") ); break; default: break; } } void TextHTMLBuilder::endList() { Q_D( TextHTMLBuilder ); switch ( d->currentListItemStyles.last() ) { case QTextListFormat::ListDisc: case QTextListFormat::ListCircle: case QTextListFormat::ListSquare: d->m_text.append( QStringLiteral( "</ul>\n" ) ); break; case QTextListFormat::ListDecimal: case QTextListFormat::ListLowerAlpha: case QTextListFormat::ListUpperAlpha: case QTextListFormat::ListLowerRoman: case QTextListFormat::ListUpperRoman: d->m_text.append( QStringLiteral( "</ol>\n" ) ); break; default: break; } d->currentListItemStyles.removeLast(); } void TextHTMLBuilder::beginListItem() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "<li>" ) ); } void TextHTMLBuilder::endListItem() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</li>\n" ) ); } void TextHTMLBuilder::beginSuperscript() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "<sup>" ) ); } void TextHTMLBuilder::endSuperscript() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</sup>" ) ); } void TextHTMLBuilder::beginSubscript() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "<sub>" ) ); } void TextHTMLBuilder::endSubscript() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</sub>" ) ); } void TextHTMLBuilder::beginTable( qreal cellpadding, qreal cellspacing, const QString &width ) { Q_D( TextHTMLBuilder ); d->m_text.append( QString::fromLatin1( "<table cellpadding=\"%1\" cellspacing=\"%2\" width=\"%3\" border=\"1\">" ) .arg( cellpadding ) .arg( cellspacing ) .arg( width ) ); } void TextHTMLBuilder::beginTableRow() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "<tr>" ) ); } void TextHTMLBuilder::beginTableHeaderCell( const QString &width, int colspan, int rowspan ) { Q_D( TextHTMLBuilder ); d->m_text.append( QString::fromLatin1( "<th width=\"%1\" colspan=\"%2\" rowspan=\"%3\">" ).arg( width ).arg( colspan ).arg( rowspan ) ); } void TextHTMLBuilder::beginTableCell( const QString &width, int colspan, int rowspan ) { Q_D( TextHTMLBuilder ); d->m_text.append( QString::fromLatin1( "<td width=\"%1\" colspan=\"%2\" rowspan=\"%3\">" ).arg( width ).arg( colspan ).arg( rowspan ) ); } void TextHTMLBuilder::endTable() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</table>" ) ); } void TextHTMLBuilder::endTableRow() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</tr>" ) ); } void TextHTMLBuilder::endTableHeaderCell() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</th>" ) ); } void TextHTMLBuilder::endTableCell() { Q_D( TextHTMLBuilder ); d->m_text.append( QStringLiteral( "</td>" ) ); } void TextHTMLBuilder::appendLiteralText( const QString &text ) { Q_D( TextHTMLBuilder ); d->m_text.append( text.toHtmlEscaped() ); } void TextHTMLBuilder::appendRawText( const QString &text ) { Q_D( TextHTMLBuilder ); d->m_text.append( text ); } QString TextHTMLBuilder::getResult() { Q_D( TextHTMLBuilder ); QString ret = d->m_text; d->m_text.clear(); return ret; }
cutelyst/grantlee
textdocument/lib/texthtmlbuilder.cpp
C++
lgpl-2.1
11,981
// --------------------------------------------------------------------- // // Copyright (C) 2004 - 2013 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #include <deal.II/lac/petsc_vector.h> #ifdef DEAL_II_WITH_PETSC # include <cmath> DEAL_II_NAMESPACE_OPEN namespace PETScWrappers { Vector::Vector () { Vector::create_vector (0); } Vector::Vector (const size_type n) { Vector::create_vector (n); } Vector::Vector (const Vector &v) : VectorBase () { // first create a dummy vector, then copy // over the other one Vector::create_vector (1); Vector::operator = (v); } Vector::Vector (const MPI::Vector &v) { // first create a dummy vector, then copy // over the other one Vector::create_vector (1); Vector::operator = (v); } void Vector::reinit (const size_type n, const bool fast) { // only do something if the sizes // mismatch if (size() != n) { // FIXME: I'd like to use this here, // but somehow it leads to odd errors // somewhere down the line in some of // the tests: // const int ierr = VecSetSizes (vector, n, n); // AssertThrow (ierr == 0, ExcPETScError(ierr)); // so let's go the slow way: if (attained_ownership) { #if DEAL_II_PETSC_VERSION_LT(3,2,0) int ierr = VecDestroy (vector); #else int ierr = VecDestroy (&vector); #endif AssertThrow (ierr == 0, ExcPETScError(ierr)); } create_vector (n); } // finally clear the new vector if so // desired if (fast == false) *this = 0; } void Vector::reinit (const Vector &v, const bool fast) { reinit (v.size(), fast); } void Vector::create_vector (const size_type n) { const int ierr = VecCreateSeq (PETSC_COMM_SELF, n, &vector); AssertThrow (ierr == 0, ExcPETScError(ierr)); attained_ownership = true; } } DEAL_II_NAMESPACE_CLOSE #endif // DEAL_II_WITH_PETSC
flow123d/dealii
source/lac/petsc_vector.cc
C++
lgpl-2.1
2,571